<template>
  <div class="group-list" v-loading="memberGroupLoading">
    <div class="search-box">
      <el-input v-model="listsParams.classifyName" clearable prefix-icon="el-icon-search" placeholder="请输入分类名称" @change="onSearch"></el-input>
    </div>
    <ul class="lists-box" @scroll="onScroll">
      <li v-for="(list, i) in lists" :key="i" :class="['member-list', { 'active-li': i == currentIndex }]" @click="handleChangeIndex(i, list)">
        <div class="wrap">
          <span class="name-txt" :title="list.classifyName" v-show="!list.edit">{{ list.classifyName }}</span>
          <span style="vertical-align: top">({{ list.groupNum }})</span>
        </div>
        <el-popover placement="bottom" trigger="click" v-if="operatorName(list)">
          <p class="more" :limit-code="$buttonCode.memberTagEditCateGory" v-if="$getButtonLimit($buttonCode.memberTagEditCateGory)" @click="editGroupName(list)">编辑分类</p>
          <p class="more" :limit-code="$buttonCode.memberTagDelCateGory" v-if="$getButtonLimit($buttonCode.memberTagDelCateGory)" @click="deleteGroupName(list, i)">删除分类</p>
          <i slot="reference" class="iconfont icon-gengduo icon"></i>
        </el-popover>
      </li>
      <!-- <li >
         <div class="el-loading-spinner" style="width: 86%;" v-if="memberGroupLoading">
            <i class="el-icon-loading"></i>
          </div>
      </li> -->
    </ul>
    <p v-if="searchTip" class="searchTip">没有找到和“{{ listsParams.classifyName }}”相关的内容</p>
    <div v-if="$getButtonLimit($buttonCode.memberTagAddCateGory) && activeType == 1" class="add-category">
      <el-button @click="editDialog.visible = true" :limit-code="$buttonCode.memberTagAddCateGory" type="primary" class="ghost-btn add-group" v-if="addType && lists.length">新增分类</el-button>
    </div>
    <!--编辑分类-->
    <el-dialog :title="editDialog.list.memberTagGroupClassifyId ? '编辑分类' : '新增分类'" :visible.sync="editDialog.visible" width="600px" top="30vh" :close-on-click-modal="false" @close="closeEditGroup">
      <div>
        分类名称：
        <el-input class="m-t-10" placeholder="请输入分类名称" v-model="editDialog.classifyName" :maxlength="8" show-word-limit clearable></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="editDialog.loading" @click="modifyName">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { memberGroupList, memberGroupModify, memberGroupDelete } from '@/request/api';

export default {
  name: 'group-list',
  props: {
    activeType: String,
  },
  data() {
    return {
      searchTip: false,
      addGroupDialog: false,
      listsParams: {
        // type: '', // 类型 0:客户分组，1:固化分组
        pageNum: 1, // 页码，从1开始
        pageSize: 20, // 页面大小
        totalPage: 1,
        classifyName: '' // 分类名
      },
      lists: [],
      currentIndex: -1,
      editDialog: {
        visible: false,
        loading: false,
        classifyName: '',
        list: {}
      },
      memberGroupLoading: false,
      addType: true
    };
  },

  methods: {
    onSearch() {
      this.listsParams.pageNum = 1;
      this.getMemberGroupList();
    },
    onPageNumChange() {
      if (this.listsParams.pageNum >= this.listsParams.totalPage) return;
      this.listsParams.pageNum++;
      this.getMemberGroupList();
    },
    onScroll(e) {
      if ((e.target.scrollTop + e.target.clientHeight) >= this.lists.length * 40) {
        this.onPageNumChange();
      }
    },
    handleChangeIndex(i, list) {
      this.currentIndex = i;
      // 第二级的分组数据
      this.$emit('second-list', this.activeType == 1 ? list : { isFixed: true, list });
    },
    /**
     * 修改和删除分组
     * 鼠标悬浮在分组名称上，显示编辑和删除按钮
     * 点击编辑之后，编辑按钮切换为保存按钮，删除按钮切换为不保存按钮。
     */
    editGroupName(list) {
      if (!this.operatorName(list)) {
        return;
      }
      this.editDialog.visible = true;
      this.editDialog.classifyName = list.classifyName;
      this.editDialog.list = list;
    },
    // 删除
    deleteGroupName(list, index) {
      if (!this.operatorName(list)) {
        return;
      }
      this.$confirm('删除分类名称，包括该分类下的内容，确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除操作
          this.excludeName(list.memberTagGroupClassifyId, index);
        });
    },
    excludeName(memberTagGroupClassifyId, index) {
      const param = {
        requestProject: 'gic-member-tag-web',
        memberTagGroupClassifyId,
        type: this.activeType == 1 ? 0 : 1
      };
      memberGroupDelete(param).then(res => {
        if (res.errorCode == 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.lists.splice(index, 1);
          if (index == this.currentIndex) {
            const item = index >= this.lists.length ? this.lists[index - 1] : this.lists[index];
            this.$emit('second-list', this.activeType == 1 ? item : { isFixed: true, item });
          }
        }
      });
    },
    // 修改分组名称
    modifyName() {
      const { classifyName, list } = this.editDialog;
      if (classifyName.length == 0) {
        this.$message({
          message: `分类名称不能为空！`,
          type: 'warning',
          duration: 2000
        });
        return;
      }
      this.editDialog.loading = true;
      const param = {
        requestProject: 'gic-member-tag-web',
        classifyName,
        memberTagGroupClassifyId: list.memberTagGroupClassifyId,
        // type 0 我的分组 1 固化分组
        type: this.activeType == 1 ? 0 : 1
      };
      memberGroupModify(param).then(res => {
        if (res.errorCode == 0) {
          this.$message({
            type: 'success',
            message: '修改成功',
            duration: 2000
          });
          if (list.memberTagGroupClassifyId) {
            this.editDialog.list.classifyName = this.editDialog.classifyName;
          } else {
            this.listsParams.pageNum = 1;
            this.getMemberGroupList();
          }
          this.editDialog.visible = false;
        }
      }).finally(() => {
        setTimeout(() => this.editDialog.loading = false, 500);
      });
    },

    operatorName(list) {
      if (list.memberTagGroupClassifyId == '0' || list.memberTagGroupClassifyId == '1') {
        // this.$message({
        //   message: `${list.classifyName}的不能操作`,
        //   type: 'warning',
        //   duration: 2000
        // });
        return false;
      }
      return true;
    },
    // 关闭编辑会员分组
    closeEditGroup() {
      this.editDialog.classifyName = '';
      this.editDialog.list = {};
    },
    /**
     * 会员分组分类
     */
    getMemberGroupList() {
      this.memberGroupLoading = true;
      const { pageNum, pageSize, classifyName } = this.listsParams;
      if (pageNum == 1) {
        this.lists = [];
      }
      memberGroupList({
        requestProject: 'gic-member-tag-web',
        type: this.activeType == 1 ? 0 : 1,
        pageNum,
        pageSize,
        classifyName
      }).then(res => {
        this.memberGroupLoading = false;
        if (res.errorCode == 0) {
          const { result, totalPage } = res.result || {};
          if (this.listsParams.classifyName == '') {
            this.searchTip = false;
            this.addType = true;
          } else if (this.listsParams.classifyName != '') {
            this.addType = false;
            if (result.length <= 0) {
              this.searchTip = true;
            }else {
              this.searchTip = false;
            }
          }
          if (pageNum == 1) {
            this.lists = [];
          }
          if (Array.isArray(result)) {
            this.lists = this.lists.concat(result.map(el => ({ ...el, edit: false })));
          }
          this.listsParams.totalPage = totalPage;
        }
      });
    }
  },
  activated() {
    this.listsParams.pageNum = 1;
    this.listsParams.classifyName = '';
    this.getMemberGroupList();
  },
  created() {
    this.getMemberGroupList();
  },
  watch: {
    activeType(newVal) {
      this.listsParams.pageNum = 1;
      this.listsParams.classifyName = '';
      this.getMemberGroupList();
      if (newVal == 1) {
        this.$emit('second-list', 'all');
      } else if (newVal == 2) {
        this.$emit('second-list', 'showFixedList');
      } else if (newVal == 3) {
        this.$emit('second-list', 'allLevel');
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.add-category, .search-box {
  padding: 0 15px;
}
.add-group {
  width: 100%;
  margin-top: 12px;
}
.group-list {
  height: calc(100% - 40px);
}
.member-list {
  height: 40px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    padding: 1px;
    border-radius: 2px;
    margin: 0 4px;
  }
  &:hover {
    color: #2F54EB;
    background: #F2F3F5;
    .icon:hover {
      background: RGBA(229, 230, 235, 1);
    }
  }
  .name-txt {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.lists-box {
  padding: 0 15px;
  max-height: calc(100% - 86px);
  color: #303133;
  overflow-y: auto;
  .active-li {
    color: #2F54EB;
    background-color: #ebeffe;
    .wrap span{
    padding-left: 6px;
    color: #2f54eb;
    }
    .icon:hover {
      background: #d8defc;
    }
  }
  .wrap span{
    padding-left: 6px;
    color: #303133;
  }
}


.more {
  line-height: 26px;
  text-align: center;
  cursor: pointer;
  &:hover {
    color: #2f54eb;
  }
}
.searchTip {
  width: 100%;
  text-align: center;
  margin-top: 80%;
  color: #909399;
  font-size: 14px;
}
</style>
