<template>
  <section>
    <div class="mb-10 mt-20 pl-16 pr-15">
      <el-input placeholder="请输入分组名称" maxlength="50" v-model="searchGroupInput" @keyup.native="value => searchGroup(value)">
        <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.releationNum})` }}</span>
          </div>
          <el-popover placement="bottom" trigger="hover" v-if="isShowGroupListItemMore(listItem)">
            <p class="more" @click="editGroupListItem(listItem)">编辑</p>
            <p class="more" @click="delGroupListItem(listItem)" v-if="!listItem.releationNum">删除</p>
            <i slot="reference" class="iconfont-hb3 icongengduo icon"></i>
          </el-popover>
        </li>
      </ul>
    </div>
    <div class="add-category">
      <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 { findActCodeGroupListApi, addActCodeGroupApi, editActCodeGroupApi, delActCodeGroupApi } from '@/api/actCode.js';
export default {
  name: 'staffActCodeGroupList',
  data() {
    const groupList = [
      {
        groupName: '全部分组',
        releationNum: 11,
        groupId: 1
      },
      {
        groupName: '默认分组',
        releationNum: 10,
        groupId: 2
      }
    ];
    let i = 3;
    while (i <= 15) {
      groupList.push({
        groupName: '单人分组',
        releationNum: i,
        groupId: i
      });
      i++;
    }

    return {
      currentListItemUuid: 1,
      searchGroupInput: '',
      groupList: groupList,
      scrollLoad: false,
      title: '新增分组',
      addOrEditGroupDialog: false,
      groupListForm: {
        groupName: '',
        groupId: ''
      },
      groupListFormRules: {
        groupName: [{ required: true, message: '请输入分组名称', trigger: 'blur' }]
      },
      isEditGroup: false,
      // 分页相关
      pageNum: 1,
      allPageNum: 1,
      pageSize: 20
    };
  },
  created() {
    // this.searchGroup();
  },
  methods: {
    load() {
      // const length = this.groupList.length;
      // if (length > 50) {
      //   return (this.scrollLoad = true);
      // }
      // for (let index = 0; index < 6; index++) {
      //   this.groupList.push({
      //     groupName: '单人分组',
      //     number: length + index,
      //     groupId: length + index
      //   });
      // }
      if (this.allPageNum > this.pageNum) {
        this.pageNum++;
        this.searchGroup();
      } else {
        this.scrollLoad = true;
      }
    },
    clickGroupListItem(listItem) {
      this.currentListItemUuid = listItem.groupId;
    },
    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.errorCode == 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.groupList.splice(listItemIndex, 1);
            }
          });
        })
        .catch(() => {});
    },
    handleGroupListItem() {
      this.$refs.groupListForm.validate(async valid => {
        if (valid) {
          // 用来接收编辑或者新增后的返回结果
          let res = {};
          let resSucTip = `${this.isEditGroup ? '修改' : '新增'}成功`;
          let resErTip = `${this.isEditGroup ? '修改' : '新增'}失败`;
          if (this.isEditGroup) {
            res = await editActCodeGroupApi(this.groupListForm);
          } else {
            let params = {
              groupName: this.groupListForm.groupName
            };
            res = await addActCodeGroupApi(params);
          }
          if (res.errorCode == 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.pageNum = 1;
              this.searchGroup();
            }
            this.addOrEditGroupDialog = false;
          } else {
            this.$message({
              type: 'error',
              message: resErTip
            });
          }
        }
      });
    },
    searchGroup(val) {
      if (this.pageNum == 1) {
        this.groupList = [];
      }
      this.pageNum < this.allPageNum && this.pageNum++;
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize
      };
      if (String(this.searchGroupInput)) {
        params.groupName = this.searchGroupInput;
      }
      findActCodeGroupListApi(params).then(res => {
        if (res.errorCode == 0) {
          const { list, pageInfo } = res.result || {};
          if (Array.isArray(list)) {
            list.reduce((pre, cur) => pre.push(cur), this.groupList);
          }
          this.allPageNum = pageInfo.pages || 1;
        }
      });
    }
  }
};
</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,
  &.active-li {
    color: #2f54eb;
    background: #ebeffe;
  }
}
.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;
}
</style>
