<template>
  <!-- 具体标签 -->
  <div class="tag-some-list">
    <el-table :data="tableData" style="width: 100%" @sort-change="sortChange">
      <el-table-column label="标签名称" prop="tagName" min-width="170" fixed>
        <template slot-scope="scope">
          <span class="tag-name">{{ scope.row.tagName }}</span>
          <el-tooltip class="item" effect="dark" content="添加标签" placement="bottom">
            <i class="iconfont icon-tag-name icon-PlusOutlined" v-if="getCodeAuth" :limit-code="getCode" v-track:common.click="handleTrackParam('addTag', scope.row)" @click="addTag(scope.row)"></i>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="上级分类名称" min-width="110" prop="tagLevelGroupName">
        <template slot-scope="{ row }">
          <span>{{ row.tagLevelGroupName || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="覆盖人数" prop="memberCount" min-width="110" show-overflow-tooltip>
        <template slot="header">
          覆盖人数
          <el-popover width="260" trigger="hover" placement="top">
            <div style="color: #303133;">
              标签下不同标签值可能覆盖相同的会员，因此此处“标签”覆盖人数去重显示（如“喜欢的颜色-白、红、黑、蓝”，某会员身上可能同时具备“白、黑”二种标签值）
            </div>
            <i slot="reference" class="iconfont icon-QuestionCircleOutlined refresh"></i>
          </el-popover>
        </template>

        <template slot-scope="scope">
          {{ scope.row.memberCount ? (scope.row.memberCount | formatNum) + '人' : '--' }}
        </template>
      </el-table-column>
      <el-table-column label="标签类型" prop="isMultiple" min-width="100">
        <template slot-scope="{ row }">
          <div>{{ row.isMultiple ? '多选': '单选' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="标签描述" prop="tagDescribe" min-width="150">
        <template slot-scope="scope">
          <div>{{ scope.row.tagDescribe ? scope.row.tagDescribe : '--' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" min-width="100" sortable="custom">
        <template slot="header">
          排序
          <el-popover width="260" trigger="hover" placement="top">
            <div style="color: #303133;">
              控制好办上标签展示顺序，按照数字降序排序
            </div>
            <i slot="reference" class="iconfont icon-QuestionCircleOutlined refresh"></i>
          </el-popover>
        </template>
        <template slot-scope="scope">
          <span class="sort" v-if="scope.row.numRool" @click="onClickSort(scope.row)">{{ scope.row.sort }}</span>
          <el-input v-else :ref="'input' + scope.row.tagId" v-model.number="scope.row.sort" @input="validateInput(scope.row)" @blur="blurNumInput(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" min-width="100">
        <template slot-scope="{ row }">
          <template v-if="row.createTime">
            <p>{{ dateformat(new Date(row.createTime), 'yyyy-MM-dd') }}</p>
            <p>{{ dateformat(new Date(row.createTime), 'hh:mm:ss') }}</p>
          </template>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-if="((getCodeAuth('edit') || getCodeAuth('setValue') || getCodeAuth('delete')) && resource != 'memberGroupEdit')" min-width="200" fixed="right">
        <template slot-scope="scope">
          <div class="font-0">
          <el-button class="m-r-12" type="text" v-if="!isWeim && getCodeAuth('edit') && !weimId.includes(scope.row.tagLevelGroupId)" :limit-code="getCode('edit')" @click="editHandTag(scope.row)">编辑</el-button>
          <el-button class="m-r-12" type="text" v-if="getCodeAuth('setValue')" :limit-code="getCode('setValue')" @click="editHandTagValue(scope.row)">详情</el-button>
          <el-button class="m-r-12" type="text" v-if="!isWeim && getCodeAuth('delete') && !weimId.includes(scope.row.tagLevelGroupId)" :limit-code="getCode('delete')" @click="deleteHandTag(scope.row, scope.$index, $event)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <delete-tag-dialog :visible.sync="deleteTagDialog.visible" :data="deleteTagDialog.deleteData" @submit="doDelete" />
    <i id="tagAniIcon" class="iconfont icon-biaoqian tagAniIcon" :style="{ right: `${animationPos.x}px`, bottom: `${animationPos.y}px` }"></i>
  </div>
</template>

<script>
import Emitter from '@/mixins/emitter';
import tagDetails from '@/components/tagDetail/mixin/index';
import DeleteTagDialog from '../manualTag/delete-tag-dialog.vue';
import { delThirdHandTag, changeTagSort } from '@/request/api';
import { dateformat } from '@/utils/formatTime';
import errMsg from '@/common/js/error';
import { getRequest } from '@/api/api';
export default {
  name: 'tag-container',

  mixins: [tagDetails, Emitter],

  props: {
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    groupId: String,
    refersh: Object,
    isWeim: Boolean,
    resource: String
  },

  data() {
    return {
      tableData: [],
      dateformat,
      deleteTagDialog: {
        visible: false,
        deleteData: {}
      },
      weimId: ['3d11ac15963b4c0790762e6147ea9315', '5bdac971673b4f40a9af981e3c9215bf'],
      animationPos: {}
    };
  },
  methods: {
    // 将标签添加到已选标签 弹框里面操作
    addTag(list) {
      this.$emit('addTag', list);
    },
    editHandTag(list) {
      this.$emit('editHandTag', list);
    },
    editHandTagValue(list) {
      this.$emit('setGroupId');
      localStorage.setItem('jumpTag', '');
      localStorage.setItem('jumpThirdTag', '');
      this.$router.push({
        path: '/manualTagValueEdit',
        query: { tagId: list.tagId, type: 'manual' }
      });
    },
    deleteHandTag(list, index, e) {
      this.deleteTagDialog.visible = true;
      this.deleteTagDialog.deleteData = {
        ...list,
        currentIndex: index,
        e
      };
    },
    doDelete(list) {
      const { currentIndex: index, e, memberCount } = list;
      // memberCount为0时不加入垃圾桶,直接删除
      if (memberCount == 0) {
        this.directDelTag(list);
      } else {
        this.intoTrash(list, index, e);
      }
    },
    directDelTag(list) {
      const param = {
        tagId: list.tagId,
        requestProject: 'gic-member-tag-web'
      };
      delThirdHandTag(param)
        .then(res => {
          if (res.errorCode == 0) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            });
            this.$emit('deleteHandTag', this.groupId);
          }
        })
    },
    // 加入到垃圾桶
    intoTrash(item, index, e) {
      const para = {
        itemId: item.tagId,
        type: 1
      };
      getRequest('/delTagItem/add', para).then(res => {
        const { errorCode } = res.data;
        if (errorCode == 0) {
          item.delStatus = 0;
          this.startAnimation(e);
          this.$store.commit('changeDelTrashNum', this.$store.state.delTrashNum + 1);
          this.$message.success('添加成功，请点击右侧「垃圾桶」图标进行删除');
          return;
        }
        errMsg.errorMsg(res.data);
      }).catch(error => {
        this.$message.error({
          duration: 1000,
          message: error.message
        });
      });
    },
    startAnimation(e) {
      this.animationPos = {
        x: document.body.offsetWidth - e.pageX - 30,
        y: document.body.offsetHeight - e.pageY
      }
      document.getElementById('tagAniIcon').style.display = 'block';
      setTimeout(() => {
        document.getElementById('tagAniIcon').style.display = 'none';
      }, 1800)
    },
    handleTrackParam(type, data) {
      let fn = {
        addTag: () => {
          return {
            data: { id: data.tagId, name: data.tagName }
          };
        }
      }[type];
      return { fn: () => {}, data: fn ? fn() : {} };
    },
    onClickSort(row) {
      row.numRool = false;
      this.$nextTick(() => this.$refs[`input${row.tagId}`].focus())
    },
    // 排序输入框失去焦点
    blurNumInput(row) {
      if (!row.sort) return this.$message.error('排序值不能为空');
      if (row.sort > 100000 || row.sort < 1) return this.$message.error('仅支持输入1-1-100000之间的整数');
      row.numRool = true;
      this.sortMenu(row);
    },
    validateInput(row) {
      const res = /^[0-9]+$/;
      if (!res.test(row.sort)) {
        row.sort = null;
      }
    },
    async sortMenu(row) {
      const params = { tagId: row.tagId, sort: row.sort };
      await changeTagSort(params);
      this.$message.success('排序成功');
      this.$emit('change')
    },
    sortChange({ order, prop }) {
      this.$emit('remote-sort', prop, order);
    }
  },
  watch: {
    data: {
      immediate: true,
      handler(newval) {
        this.tableData = newval;
      }
    },
    refersh: {
      immediate: true,
      handler(newval) {
        // 刷新
        if (newval.changeRefersh) {
          let index = this.tableData.findIndex(el => newval.tagId === el.tagId);
          this.tableData[index].refersh = true;
        }
      }
    }
  },
  computed: {
    getCodeAuth() {
      return label => {
        let code;
        code = label == 'add' ? 'memberTagCreateGroup' : label == 'edit' ? 'memberTagEditTag' : label == 'setValue' ? 'memberTagSetTagValue' : 'memberTagDelTag';
        return this.$getButtonLimit(this.$buttonCode[code]);
      };
    },
    getCode() {
      return label => {
        let code;
        code = label == 'add' ? 'memberTagCreateGroup' : label == 'edit' ? 'memberTagEditTag' : label == 'setValue' ? 'memberTagSetTagValue' : 'memberTagDelTag';
        return this.$buttonCode[code];
      };
    }
  },
  components: {
    DeleteTagDialog
  }
};
</script>

<style lang="scss" scoped>
.tag-some-list {
  margin: 0 20px;
}
.tag-name {
  display: inline-block;
  word-break: break-all;
  max-width: 120px;
}
.icon-tag-name {
  display: inline-block;
  vertical-align: top;
  font-size: 16px;
  cursor: pointer;
  transition: all .3s;
  color: #2f54eb;
  &:hover {
    transform: scale(1.25);
  }
}
.refresh {
  color: #606266;
  position: relative;
  top: 1px;
}
.sort {
  height: 24px;
  padding: 0 7px;
  display: inline-block;
  text-align: center;
  line-height: 24px;
  box-sizing: border-box;
  border-radius: 2px;
  color: #303133;
  border: 1px dashed #C4C6CF;
}
#tagAniIcon {
  display: none;
  position: fixed;
  z-index: 99999;
  color: #2F54EB;
  font-size: 26px;
  animation: toTrash 2s infinite;
  opacity: 0;
}
@keyframes toTrash {
  0% {
    opacity: 1;
  }
  40% {
    opacity: 1;
    right: 38px;
    bottom: 345px;
    transform: scale(0.5);
  }
  50% {
    opacity: 0.5;
    right: 37px;
    bottom: 345px;
    transform: scale(1.2);
  }
  100% {
    opacity: 0.5;
    right: 37px;
    bottom: 345px;
    transform: scale(0);
  }
}
</style>
