<template>
  <div class="second" :class="[isOtherTag && 'manual']">
    <span class="name" :class="{ 'manual-name': isOtherTag, 'light-active': tagList.name === tagRealName }" @click="handleSecondtag(tagList)">
      <span v-if="isOtherTag">
        <!-- tagList.icon -->
        <svg class="menu-icon" :class="[ { 'icon-tag-light': tagList.name === tagRealName }]" aria-hidden="true">
          <use :xlink:href="`#${tagList.icon}`"></use>
        </svg>
        <span class="tag-name" :class="{ 'icon-tag-light': tagList.name === tagRealName }">{{ tagList.name }}</span>
      </span>
      <span class="second-title" v-else>{{ tagList.name }}</span>
      <el-tooltip content="请去微盟后台创建标签，且仅同步微盟多选项标签" v-if="tagList.id === '3d11ac15963b4c0790762e6147ea9315'">
        <i class="iconfont icon-QuestionCircleOutlined"></i>
      </el-tooltip>
    </span>
    <i class="arrow-line iconfont icon-next-" v-if="!isOtherTag"></i>
    <template v-if="(['手工标签', '活动标签'].includes(tagName))&& tagList.id !== '3d11ac15963b4c0790762e6147ea9315'">
      <el-popover placement="bottom" width="30" trigger="click" v-if="getCode('add') || getCode('edit')">
        <li class="more" @click="addNewType" :limit-code="getCode('add')" v-if="getCodeAuth('add')">新增子分类</li>
        <li class="more" @click="handleEditType" :limit-code="getCode('edit')" v-if="getCodeAuth('edit')">编辑子分类</li>
        <i slot="reference" class="iconfont icon-gengduo icon-tag"></i>
      </el-popover>
    </template>
    <div class="third-list" :class="{ 'manual-tag': isOtherTag }">
      <span v-for="(item, i) in tagList.children" :key="i" :class="{ 'light-active': item.name === tagRealName }" class="tag-item" @click="handleThirdTag(item)">
        {{ item.name }}
      </span>
    </div>

    <!-- 编辑子分类 -->
    <el-dialog :title="newName" :visible.sync="editVisiable" :close-on-click-modal="false" width="600px">
      <el-table :data="editData" height="400">
        <el-table-column label="子分类名称" prop="levelName">
          <template slot-scope="scope">
            <el-input v-model="scope.row.levelName" v-if="scope.row.editName"></el-input>
            <span v-else>{{ scope.row.levelName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签数量" prop="count">
          <template slot-scope="scope">
            <span>{{ scope.row.count == null ?  '--' : scope.row.count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div class="btn-group">
              <el-button :disabled="scope.row.levelName.indexOf('未分类') > -1"  @click="handleEdit(scope.row, scope.$index)" type="text">{{ scope.row.editText }}</el-button>
              <el-button :disabled="scope.row.levelName.indexOf('未分类') > -1" type="text" @click="handleDelete(scope.row, scope.$index)" style="margin-left: 20px"> {{ scope.row.deleteText }} </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisiable = false">取消</el-button>
      </span>
    </el-dialog>

    <!-- 新增子分类 -->
    <el-dialog :title="newName" :visible.sync="dialogVisible" width="600px" top="20%" :close-on-click-modal="false" custom-class="add-tag-dialog">
      <div class="newtype">
        <p class="name"><span class="required">*</span>子分类 </p>
        <el-input style="width: 100%" placeholder="请输入分类名称" maxlength="10" v-model="typeName" show-word-limit> </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="newTag">添 加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Emitter from '@/mixins/emitter';
import { mapState } from 'vuex';
import { newHandTag, thirdHandTagList, deleteThirdTag, editThirdTag } from '@/request/api';

export default {
  mixins: [Emitter],

  name: 'second-type',

  componentName: 'second-type',

  props: {
    list: Object,
    tagName: String
  },
  data() {
    return {
      tagList: {},
      editData: [],
      dialogVisible: false,
      editVisiable: false,
      editText: '编辑',
      typeName: '',
      currentIndex: -1,
      newName: '' // 新增子分类
    };
  },

  watch: {
    list: {
      immediate: true,
      handler(newval) {
        let noClassIndex  = newval.children.findIndex(el => el.name.indexOf('未分类') > -1);
        if (noClassIndex > -1) {
          let noClassData = newval.children.splice(noClassIndex, 1);
          newval.children.unshift(noClassData[0]);
        }
        this.tagList = newval;
      }
    }
  },

  computed: {
    ...mapState(['tagRealName']),
    getCodeAuth() {
      return type => {
        let code;
        code = type == 'add' ? 'memberTagAddChildCategory' : 'memberTagEditChildCategory';
        return this.$getButtonLimit(this.$buttonCode[code]);
      }
    },
    getCode() {
      return type => {
        let code;
        code = type == 'add' ? 'memberTagAddChildCategory' : 'memberTagEditChildCategory';
        return this.$buttonCode[code];
      }
    },
    isOtherTag() {
      return ['手工标签', '活动标签'].includes(this.tagName);
    }
  },

  methods: {
    // 新增子分类
    addNewType() {
      this.newName = `${this.list.name} - 新增子分类`;
      this.dialogVisible = !this.dialogVisible;
    },
    // 编辑子分类
    handleEditType() {
      this.newName = `${this.list.name} - 编辑子分类`;
      this.editVisiable = !this.editVisiable;
      this.getThirdTag();
    },
    // 请求三级手工标签
    getThirdTag() {
      const param = {
        tagLevelGroupId: this.tagList.id,
        requestProject: 'gic-member-tag-web'
      };
      thirdHandTagList(param)
        .then(res => {
          if (res.errorCode == 1) {
            this.editData = res.result.map(el => ({
              ...el,
              editName: false,
              editText: '编辑',
              deleteText: '删除'
            }));
          } else {
            this.editData = [];
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleEdit(list, i) {
      if (!list.editName) {
        this.editData = this.editData.map(el => ({
          ...el,
          editName: false,
          editText: '编辑',
          deleteText: '删除',
          originLevelName: el.levelName
        }));
        this.editData[i].editName = true;
        this.editData[i].editText = '确认';
        this.editData[i].deleteText = '取消';
      } else {
        /** 提交修改的标签名
         *  不能为空
         */
        this.editThird(list, i);
      }
    },
    // 修改三级分类
    editThird(list, i) {
      if (!list.levelName) {
        this.$message({
          message: '子分类名称不能为空',
          type: 'warning',
          duration: 1000
        });
        return;
      }
      const param = {
        tagLevelGroupId: list.tagLevelGroupId,
        levelName: list.levelName,
        requestProject: 'gic-member-tag-web'
      };

      editThirdTag(param)
        .then(res => {
          if (res.errorCode == 1) {
            this.$message({
              message: '修改成功',
              type: 'success',
              duration: 1000
            });
            list.editName = false;
            list.editText = '编辑';
            list.deleteText = '删除';
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 删除子分类
    handleDelete(list, i) {
      // list.editName = false;
      // list.editText = '编辑';
      if (list.deleteText == '取消') {
        this.editData[i].editName = false;
        this.editData[i].editText = '编辑';
        this.editData[i].deleteText = '删除';
        this.editData[i].levelName = list.originLevelName;
        return;
      }
      const param = {
        tagLevelGroupId: list.tagLevelGroupId,
        requestProject: 'gic-member-tag-web'
      };
      deleteThirdTag(param)
        .then(res => {
          if (res.errorCode == 1) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            });
            this.getThirdTag();
            this.dispatch('member-tag', 'refersh-member-list');
            // this.editVisiable = false;
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    /**
     * 添加手工标签
     */
    newTag() {
      const params = {
        levelName: this.typeName,
        parentLevelGroupId: this.tagList.id,
        requestProject: 'gic-member-tag-web'
      };
      // 子分类名称不能为空
      if (!this.typeName) {
        this.$message({
          message: '子分类名称不能为空',
          type: 'warning',
          duration: 3000
        });
        return;
      }
      if (!this.addHandTagFlag) {
        this.addHandTagFlag = true;
        newHandTag(params)
          .then(res => {
            this.addHandTagFlag = false;
            if (res.errorCode == 1) {
              this.dispatch('member-tag', 'refersh-member-list');
              this.typeName = '';
              this.dialogVisible = false;
              this.$message({
                message: '添加成功',
                type: 'success',
                duration: 3000
              });
            }
          })
          .catch(err => {
            this.addHandTagFlag = false;
          });
      }
    },
    /**
     * 处理二级分类
     */
    handleSecondtag(list) {
      localStorage.setItem('jumpThirdTag', '');
      localStorage.setItem('jumpTag', JSON.stringify(list));
      this.dispatch('member-tag', 'handle-second-tag', this.tagList);
    },
    /**
     * 处理三级标签
     */
    handleThirdTag(list, i) {
      localStorage.setItem('jumpTag', JSON.stringify(this.tagList));
      localStorage.setItem('jumpThirdTag', JSON.stringify(list));
      this.dispatch('member-tag', 'handle-third-tag', list);
    }
  },
  created() {
    this.addHandTagFlag = false;
  }
};
</script>

<style lang="scss" scoped>
.second {
  position: relative;
  line-height: 26px;
  min-height: 26px;
  padding-left: 24px;
  overflow: hidden;
  .name {
    position: relative;
    top: 0;
    float: left;
    .second-title {
      font-weight: bold;
    }
    span:hover {
      color: #2f54eb;
    }
  }
  .light-active {
    color: #2f54eb;
  }
  .manual-name {
    display: block;
    float: none;
    text-align: left;
    line-height: 22px;
    margin-bottom: 16px;
  }
  .third-list {
    margin-left: 90px;
    font-size: 0;
    .tag-item {
      display: inline-block;
      line-height: 22px;
      height: 22px;
      margin-right: 8px;
      margin-bottom: 8px;
      font-size: 12px;
      padding: 0 8px;
      background: #F2F3F5;
      border-radius: 2px;
      color: #303133;
      &:hover {
        color: #2f54eb;
      }
    }
    .light-active {
      background: #EBEFFE;
      color: #2f54eb;
      font-weight: 500;
    }
    .icon-next- {
      font-size: 30px;
    }
  }
  .manual-tag {
    margin-left: 25px;
    .arrow {
      margin-right: 10px;
    }
  }
  .arrow-line {
    float: left;
    position: relative;
    top: 1px;
    font-size: 30px;
  }
  .icon-tag {
    position: absolute;
    right: 16px;
    top: 0;
    color: #303133;
    cursor: pointer;
    width: 24px;
    height: 24px;
    padding: 5px 11px;
    box-sizing: border-box;
    display: flex;
    border-radius: 2px;
    align-items: center;
    justify-content: center;
    &:hover {
      background: #F2F3F7;
    }
  }
  &.manual {
    padding: 0;
    margin-top: 18px;
    &:first-child {
      margin-top: 0;
    }
  }
  .icon-tag-light {
    color: #2f54eb;
    font-weight: bold;
  }
}
.more {
  line-height: 26px;
  text-align: center;
  cursor: pointer;
  &:hover {
    color: #2f54eb;
  }
}
.add-tag-dialog {
  .newtype {
    .name {
      margin-bottom: 10px;
    }
  }
  .required {
    color: red;
    margin-right: 5px;
  }
}
  /deep/ .el-dialog__header {
    padding-bottom: 0px;
  }
  /deep/ .el-dialog__title {
    font-size: 16px;
    font-weight: bold;
  }
  /deep/ .el-dialog__footer {
    padding-bottom: 20px;
  }
.tag-name {
  display: inline-block;
  margin-left: 5px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  cursor: pointer;
  &:hover {
    color: #2f54eb;
  }
}
.btn-group {
  font-size: 0;
}
.menu-icon {
    width: 16px; height: 16px;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}
</style>
