<template>
  <div class="group-list">
      <tempalte v-show="activeType == '1'">
        <ul class="lists">
          <li v-for="(list, i) in lists" :key="i" :class="['member-list', { 'active-li': i == currentIndex }]" @click="handleChangeIndex(i, list)">
            <div class="wrap">
              <span :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, 0)">编辑分类</p>
              <p class="more" :limit-code="$buttonCode.memberTagDelCateGory" v-if="$getButtonLimit($buttonCode.memberTagDelCateGory)" @click="deleteGroupName(list, 0)">删除分类</p>
              <i slot="reference" class="iconfont icon-gengduo icon"></i>
            </el-popover>
          </li>
        </ul>
      </tempalte>
      <ul class="lists" v-show="activeType == '3'">
        <li v-for="(list, i) in groupLists" :key="i" :class="['member-list', { 'active-li': i == currentLevelIndex }]" @click="handleChangeLevel(i, list)">
          <div class="wrap">
            <span>{{ list.aliasName }}</span>
            <span>({{ levelNums(list.aliasName) }})</span>
          </div>
        </li>
      </ul>
      <ul class="lists" v-show="activeType == '2'">
        <li v-for="(list, i) in fixedLists" :key="i" :class="['member-list', { 'active-li': i == currentFixedIndex }]" @click="handleChangeFixed(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, 1)">编辑分类</p>
            <p class="more" :limit-code="$buttonCode.memberTagDelCateGory" v-if="$getButtonLimit($buttonCode.memberTagDelCateGory)" @click="deleteGroupName(list, 1)">删除分类</p>
            <i slot="reference" class="iconfont icon-gengduo icon"></i>
          </el-popover>
        </li>
      </ul>
    <!--新增分类-->
    <el-dialog :title="title" :visible.sync="addGroupDialog" width="600px" top="30vh" :close-on-click-modal="false" @close="$emit('update:addGroupDialog', false)">
      <div>
        分类名称：
        <el-input class="m-t-10" placeholder="请输入分类名称" v-model="groupName" :maxlength="8" show-word-limit clearable></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:addGroupDialog', false)">取 消</el-button>
        <el-button type="primary" @click="handleGroupDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑分类-->
    <el-dialog title="编辑分类" :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.groupName" :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" @click="handleEditGroup">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue';
import { CollapseTransition } from 'element-ui';
import { memberGroupList, memberGroupModify, memberGroupDelete, hasLevelFeature, getTagLists } from '@/request/api';
import { aliasNames } from '@/config'

Vue.component(CollapseTransition.name, CollapseTransition);

export default {
  name: 'group-list',
  props: {
    activeType: String,
    addGroupDialog: Boolean
  },
  data() {
    return {
      lists: [],
      expendTxt: '收起',
      expendTxtTag: '收起',
      expendTxtFixed: '收起',
      groupName: '',
      title: '新增分类名称',
      currentIndex: -1,
      currentTagIndex: 0,
      currentFixedIndex: -1,
      active: false,
      Taglists: [],
      classTagName: 'tag-name',
      // 是否分层
      hasLevel: false,
      currentLevelIndex: -1,
      groupLists: [],
      fixedLists: [],
      editDialog: {
        visible: false,
        groupName: '',
        type: 0,
        list: {}
      }
    };
  },

  computed: {
    expendClass() {
      if (this.expendTxt != '展开') {
        return 'is-caret';
      } else {
        return '';
      }
    },
    expendTagClass() {
      if (this.expendTxtTag != '展开') {
        return 'is-caret';
      } else {
        return '';
      }
    },
    expendFixedClass() {
      return this.expendTxtFixed != '展开' ? 'is-caret' : ''
    }
  },

  methods: {
    // 处理分层
    handleChangeLevel(i, list) {
      this.currentLevelIndex = i;
      // 重置其他组的选项
      this.currentIndex = 0;
      this.currentFixedIndex = 0;
      this.$emit('second-list', { list: list, isTag: true });
    },
    // 分层
    _getTagLists() {
      getTagLists({ requestProject: 'gic-member-tag-web' }).then(res => {
        if (res.errorCode === 1) {
          this.groupLists = res.result;
        }
      });
    },
    handleChangeTag(i, list) {
      this.active = false;
      this.classTagName = 'tag-name active-name'
      this.currentTagIndex = i;
      // 第二级的分组数据
      this.$emit('second-list', { list: list, isTag: true });
    },
    // 如果编辑二级会员分组分类 但是没有编辑有切换到其他的分类
    handleNoEditClassifyName() {
      this.lists = this.lists.map(el => ({
        ...el,
        edit: false
      }));
    },
    handleChangeIndex(i, list) {
      this.classTagName = 'tag-name';
      this.active = false;
      this.currentIndex = i;
      // 重置其他组的选项
      this.currentLevelIndex = 0;
      this.currentFixedIndex = 0;
      // 第二级的分组数据
      this.$emit('second-list', list);
    },
    handleChangeFixed(i, list) {
      this.classTagName = 'tag-name';
      this.active = false;
      this.currentFixedIndex = i;
      // 重置其他组的选项
      this.currentLevelIndex = 0;
      this.currentIndex = 0;
      this.$emit('second-list', { isFixed: true, list });
    },
    /**
     * 修改和删除分组
     * 鼠标悬浮在分组名称上，显示编辑和删除按钮
     * 点击编辑之后，编辑按钮切换为保存按钮，删除按钮切换为不保存按钮。
     */
    editGroupName(list, type) {
      if (!this.operatorName(list)) {
        return;
      }
      this.editDialog.visible = true;
      this.editDialog.groupName = list.classifyName;
      this.editDialog.type = type;
      this.editDialog.list = list;
    },
    // 删除
    deleteGroupName(list, type) {
      // type 1 我的分组 2 固化分组
      if (!this.operatorName(list)) {
        return;
      }
      if (list.edit) {
        list.edit = false;
        !type && this.getMemberGroupList();
        type && this.getFixedMemberGroupList();
        return;
      }
      this.$confirm('删除分类名称，包括该分类下的内容，确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 删除操作
          this.excludeName(list, type);
        })
        .catch(() => {});
    },
    excludeName(list, type) {
      const param = {
        requestProject: 'gic-member-tag-web',
        memberTagGroupClassifyId: list.memberTagGroupClassifyId,
        type
      };
      memberGroupDelete(param).then(res => {
        if (res.errorCode == 1) {
          !type && this.getMemberGroupList();
          type && this.getFixedMemberGroupList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      });
    },
    // 修改分组名称
    modifyName(list, type, classifyName) {
      if (!classifyName) {
        this.$message({
          message: `分类名称不能为空！`,
          type: 'warning',
          duration: 2000
        });
        return;
      }
      const param = {
        requestProject: 'gic-member-tag-web',
        classifyName,
        memberTagGroupClassifyId: list.memberTagGroupClassifyId,
        type
      };
      memberGroupModify(param).then(res => {
        if (res.errorCode == 1) {
          this.editDialog.visible = false;
          this.activeType == 1 && this.getMemberGroupList();
          this.activeType == 2 && this.getFixedMemberGroupList();
          this.$message({
            type: 'success',
            message: '修改成功',
            duration: 2000
          });

        }
      });
    },

    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 = {
        visible: false,
        groupName: '',
        type: 0,
        list: {}
      }
    },
    /*
       编辑会员分组分类
    */
    handleEditGroup() {
      this.modifyName(this.editDialog.list, this.editDialog.type, this.editDialog.groupName);
    },
    /**
     * 新增会员分组分类
     */
    handleGroupDialog() {
      if (!this.groupName) {
        this.$message({
          type: 'warning',
          message: '分类名称不能为空'
        });
        return;
      }
      const param = {
        requestProject: 'gic-member-tag-web',
        classifyName: this.groupName,
        type: this.activeType == 1 ? 0 : 1
      };
      memberGroupModify(param).then(res => {
        if (res.errorCode == 1) {
          this.activeType == 1 && this.getMemberGroupList();
          this.activeType == 2 && this.getFixedMemberGroupList();
          this.groupName = '';
          this.$emit('update:addGroupDialog', false)
          this.$message({
            type: 'success',
            message: '添加成功'
          });
        }
      });
    },
    /**
     * 会员分组分类
     */
    getMemberGroupList() {
      memberGroupList({
        requestProject: 'gic-member-tag-web',
        type: 0
      }).then(res => {
        if (res.errorCode === 1) {
          this.lists = res.result.map(el => ({
            ...el,
            edit: false
          }));
        }
      });
    },
    getFixedMemberGroupList() {
      memberGroupList({
        requestProject: 'gic-member-tag-web',
        type: 1
      }).then(res => {
        if (res.errorCode === 1) {
          this.fixedLists = res.result.map(el => ({
            ...el,
            edit: false
          }));
        }
      });
    },
    // 收起
    handleExpend() {
      this.currentIndex = -1;
      this.currentLevelIndex = -1;
      this.currentFixedIndex = -1;
      this.expendTxt = this.expendTxt === '展开' ? '收起' : '展开';
      this.$emit('second-list', 'all');
    },
    handleExpendTag() {
      this.currentIndex = -1;
      this.currentLevelIndex = -1;
      this.currentFixedIndex = -1;
      this.expendTxtTag = this.expendTxtTag === '展开' ? '收起' : '展开';
      this.$emit('second-list', 'allLevel');
    },
    handleExpendFixed() {
      this.currentIndex = -1;
      this.currentLevelIndex = -1;
      this.currentFixedIndex = -1;
      this.expendTxtFixed = this.expendTxtFixed === '展开' ? '收起' : '展开';
      this.$emit('second-list', 'showFixedList');
    },
    _hasLevelFeature() {
      hasLevelFeature().then(res => {
        if (res.errorCode === 1) {
          this.hasLevel = res.result;
        }
      });
    },
    levelNums(name) {
      switch(name) {
        case '核心客户':
          return 3;
        case '潜力客户':
          return 5;
        case '普通客户':
          return 4;
        case '未消费客户':
          return 2;
      }
    }
  },
  activated() {
    switch(this.activeType) {
      case '2':
        this.getFixedMemberGroupList();
        break;
      default:
        break;
    }
  },
  beforeMount() {
    this.getMemberGroupList();
    this.getFixedMemberGroupList();
    this._getTagLists();
    this._hasLevelFeature();
  },
  filters: {
    aliasTips(name) {
      let item = aliasNames.find(el => el.name === name);
      if (item) {
        return item.title;
      }
      return '';
    },
  },
  watch: {
    activeType(newVal) {
      switch(newVal) {
        case '1':
          this.handleExpend();
          break;
        case '2':
          this.handleExpendFixed();
          break;
        case '3':
          this.handleExpendTag();
          break;
        default:
          break;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.add-category {
  position: absolute;
  bottom: 0;
  left: 20px;
  right: 20px;
  z-index: 5;
}
.group-list {
  max-height: calc(100% - 86px);
  overflow-y: scroll;
  .recommend-list {
    margin-top: 10px;
    padding-left: 37px;
    line-height: 30px;
    font-size: 14px;
    font-weight: bold;
    color: #303133;
    cursor: pointer;
  }
  .recommend-active {
    color: #2F54EB;
  }
}
.member-group {
  padding: 5px 10px 20px 20px;
  font-size: 14px;
  color: #303133;
  font-weight: bold;
  cursor: pointer;
  &:hover {
    color: #2F54EB;
  }
  .icon-right {
    float: right;
  }
  .icon-list {
    color: #909399;
    &:hover {
      color: #303133;
    }
  }
  .tag-name {
    display: inline-block;
    vertical-align: middle;
    color: #303133;
    margin-left: 19px;
    font-weight: bold;
  }
  .active-name {
    color: #2F54EB;
  }
  .active-li {
    color: #2F54EB !important;
  }
}
.light-group, .active-item {
  color: #2F54EB;
}
.member-list {
  height: 40px;
  margin: 0 15px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .icon {
    margin: 0 4px;
  }
  &:hover {
    color: #2F54EB;
    .oper-area {
      display: inline;
    }
  }
  .name-txt {
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .oper-area {
    // display: none;
    float: right;
    margin-right: 10px;
  }
}
.lists {
  color: #303133;
  .active-li {
    color: #2F54EB;
    background-color: #EBEFFE;
    .icon {
      color: #2f54eb;
    }
  }
  .wrap span{
    padding-left: 6px;
    color: #303133;
  }
  li:hover {
    background-color: #EBEFFE;
    span {
      color: #2f54eb;
    }
    .icon {
      color: #2f54eb;
    }
  }
}

.icon-list-oper {
  color: #c0c4cc;
  &:hover {
    color: #909399;
  }
}
.icon-transform {
  transition: transform 0.3s;
  transform: rotate(90deg);
  &.is-caret {
    transform: rotate(0deg);
  }
}
.more {
  line-height: 26px;
  text-align: center;
  cursor: pointer;
  &:hover {
    color: #2f54eb;
  }
}
</style>
