<template>
  <section>
    <div class="mb-10 mt-20 pl-16 pr-15">
      <el-input placeholder="请输入分组名称" maxlength="50" v-model="pageP.groupName" clearable @change="onSearch">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
    </div>
    <div class="lists-content-box infinite-list-wrapper">
      <ul class="list" v-infinite-scroll="load" infinite-scroll-disabled="scrollLoad" infinite-scroll-immediate="false" infinite-scroll-distance="1">
        <li v-for="listItem in groupList" :key="listItem.groupId" :class="['list-item', 'member-list', { 'active-li': listItem.groupId == currentListItemUuid }]" @click="clickGroupListItem(listItem)">
          <div class="wrap">
            <span :title="listItem.groupName" class="listItemName overflow-ellipsis">{{ listItem.groupName }}</span>
            <span>{{ `(${listItem.referNum})` }}</span>
          </div>
          <el-popover placement="bottom" trigger="click" v-if="isShowGroupListItemMore(listItem)">
            <p class="more" @click="editGroupListItem(listItem)">编辑</p>
            <p class="more" @click="delGroupListItem(listItem)" v-if="!listItem.referNum">删除</p>
            <i slot="reference" class="iconfont-hb3 icongengduo icon iconhover" v-if="listItem.groupName != '全部分组' && listItem.groupName != '默认分组'"></i>
          </el-popover>
        </li>
        <li>
          <div class="el-loading-spinner" style="width: 86%;" v-if="groupLoading">
            <i class="el-icon-loading"></i>
          </div>
        </li>
      </ul>
      <p v-if="searchTip" class="searchTip">没有找到和“{{ pageP.groupName }}”相关的内容</p>
    </div>
    <div class="add-category" v-if="groupList.length > 1">
      <el-button type="primary" class="ghost-btn add-group" @click="addGroup">新增分组</el-button>
    </div>
    <!-- 新增/编辑分组 -->
    <el-dialog :title="isEditGroup ? '编辑分组' : '新增分组'" :visible.sync="addOrEditGroupDialog" width="500px" top="30vh" :close-on-click-modal="false">
      <el-form :model="groupListForm" :rules="groupListFormRules" ref="groupListForm">
        <el-form-item label="分组名称" prop="groupName">
          <el-input placeholder="请输入分组名称" v-model="groupListForm.groupName" :maxlength="10" show-word-limit clearable></el-input>
          <p class="addGroupTip" v-show="!isEditGroup">分组名称不可重复，建议"创建人姓名-分组名称"</p>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOrEditGroupDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleGroupListItem">确 定</el-button>
      </span>
    </el-dialog>
  </section>
</template>

<script>
import { addActCodeGroupApi, editActCodeGroupApi, delActCodeGroupApi } from '@/api/actCode.js';
import { getRequest } from '@/api/api';
export default {
  name: 'staffActCodeGroupList',
  data() {
    return {
      searchTip: false,
      groupLoading: false,
      currentListItemUuid: 1,
      groupList: [],
      scrollLoad: false,
      title: '新增分组',
      addOrEditGroupDialog: false,
      groupListForm: {
        groupName: '',
        groupId: ''
      },
      groupListFormRules: {
        groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }]
      },
      isEditGroup: false,
      // 分页相关
      allPageNum: 1,
      pageP: {
        groupName: '',
        pageNum: 1,
        pageSize: 20
      }
    };
  },
  created() {
    this.searchGroup();
  },
  methods: {
    onSearch() {
      this.pageP.pageNum = 1;
      this.searchGroup();
    },
    load() {
      if (this.pageP.pageNum < this.allPageNum) {
        this.pageP.pageNum++;
        this.searchGroup();
      } else {
        // this.scrollLoad = true;
      }
    },
    clickGroupListItem(listItem) {
      this.currentListItemUuid = listItem.groupId;
      this.$emit('updateList', this.currentListItemUuid);
    },
    isShowGroupListItemMore(listItem) {
      const hiddenListItemMore = [1, 2];
      return !hiddenListItemMore.includes(listItem.groupId);
    },
    addGroup() {
      this.scrollLoad = false;
      this.isEditGroup = false;
      this.groupListForm = {
        groupName: '',
        groupId: ''
      };
      this.$nextTick(() => {
        this.$refs.groupListForm.clearValidate();
      });
      this.addOrEditGroupDialog = true;
    },
    editGroupListItem(listItem) {
      this.isEditGroup = true;
      this.$nextTick(() => {
        this.$refs.groupListForm.clearValidate();
      });
      this.addOrEditGroupDialog = true;
      this.groupListForm = { ...listItem };
    },
    delGroupListItem(listItem) {
      this.$confirm('分组删除后，创建号活码时将无法选取到该分组，是否继续删除?', '删除提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除操作
          // const listItemIndex = this.groupList.findIndex(item => item.groupId === listItem.groupId);
          // if (listItemIndex < 0) return;
          let params = {
            groupId: listItem.groupId
          };
          delActCodeGroupApi(params).then(res => {
            if (res.data.code == 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              // this.groupList.splice(listItemIndex, 1);
              this.pageP.pageNum = 1;
              this.searchGroup();
            }
          });
        })
        .catch(() => {});
    },
    handleGroupListItem() {
      this.$refs.groupListForm.validate(async valid => {
        if (valid) {
          // 用来接收编辑或者新增后的返回结果
          let res = {};
          let resSucTip = `${this.isEditGroup ? '修改' : '新增'}成功`;
          let resErTip = `${this.isEditGroup ? '修改' : '新增'}失败`;
          if (this.isEditGroup) {
            let obj = {
              groupId: this.groupListForm.groupId,
              groupName: this.groupListForm.groupName
            };
            res = await editActCodeGroupApi(obj);
          } else {
            let params = {
              groupName: this.groupListForm.groupName
            };
            res = await addActCodeGroupApi(params);
          }
          if (res.data.code == 0) {
            this.$message({
              type: 'success',
              message: resSucTip,
              duration: 1000
            });
            if (this.isEditGroup) {
              const groupListItem = this.groupList.find(({ groupId }) => groupId == this.groupListForm.groupId);
              groupListItem.groupName = this.groupListForm.groupName;
            } else {
              // this.pageP.pageNum = 1;
              // this.searchGroup();
            }
            this.pageP.pageNum = 1;
            this.searchGroup();
            this.addOrEditGroupDialog = false;
          } else {
            this.$message({
              type: 'error',
              message: resErTip
            });
          }
        }
      });
    },
    async searchGroup(val) {
      this.groupLoading = true;
      const countNum = await getRequest('/haoban-manage3-web/hm/group/refer/count', {});
      if (this.pageP.pageNum == 1) {
        this.groupList = [
          {
            groupName: '全部分组',
            referNum: '',
            groupId: null
          }
        ];
        this.groupList[0].referNum = countNum.data.result;
      }
      // this.pageP.pageNum < this.allPageNum && this.pageP.pageNum++;
      if (String(this.pageP.groupName)) {
        this.pageP.pageNum = 1;
        this.groupList = [];
      }
      await getRequest('/haoban-manage3-web/hm/group/list', this.pageP).then(res => {
        if (res.data.code == 0) {
          const { result, pages } = res.data.result || {};
          this.groupList = this.groupList.concat(result);
          if (this.pageP.groupName == '') {
            this.searchTip = false;
          } else if (this.pageP.groupName != '') {
            // this.groupList.splice(0, 1);
            if (this.groupList.length <= 0) {
              this.searchTip = true;
            }
          }
          this.allPageNum = pages || 1;
          this.groupLoading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.mb-10 {
  margin-bottom: 10px;
}
.mt-20 {
  margin-top: 20px;
}
.pl-16 {
  padding-left: 16px;
}
.pr-15 {
  padding-right: 15px;
}
.add-category {
  padding: 0px 20px 0 19px;
}
.member-list {
  height: 40px;
  font-size: 14px;
  color: #303133;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px 0 10px;
  &:hover {
    color: #303133;
    background: #f2f3f5;
  }
  &.active-li {
    color: #2f54eb;
    background: #ebeffe;
    .iconhover:hover,
    .iconhover:active {
      background: #d8defc;
    }
  }
}
.more {
  line-height: 26px;
  text-align: center;
  cursor: pointer;
  &:hover {
    color: #2f54eb;
  }
}
.add-group {
  width: 100%;
  margin-top: 12px;
}
.lists-content-box {
  max-height: calc(100vh - 200px);
  overflow: auto;
  padding: 0 15px 0 16px;
  .wrap {
    display: flex;
    flex: 1;
    .listItemName {
      max-width: 110px;
      margin-right: 4px;
    }
  }
}
.addGroupTip {
  font-size: 12px;
  color: #909399;
}
.searchTip {
  width: 100%;
  text-align: center;
  margin-top: 80%;
  color: #909399;
  font-size: 14px;
}
</style>
