<template>
  <!-- 具体标签 -->
  <div class="tag-some-list">
    <el-table :data="tableData" style="width: 100%" @sort-change="sortChange">
      <el-table-column label="标签名称" prop="tagName" min-width="140" 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="150">
        <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'))" min-width="200" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" v-if="!isWeim && getCodeAuth('edit')" :limit-code="getCode('edit')" @click="editHandTag(scope.row)">编辑</el-button>
          <el-button type="text" v-if="getCodeAuth('setValue')" :limit-code="getCode('setValue')" @click="editHandTagValue(scope.row)">详情</el-button>
          <el-button type="text" v-if="!isWeim && getCodeAuth('delete')" :limit-code="getCode('delete')" @click="deleteHandTag(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
      <delete-tag-dialog :visible.sync="deleteTagDialog.visible" :data="deleteTagDialog.deleteData" @submit="doDelete" />
  </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';


export default {
  name: 'tag-container',

  mixins: [tagDetails, Emitter],

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

  data() {
    return {
      tableData: [],
      dateformat,
      deleteTagDialog: {
        visible: false,
        deleteData: {}
      },
    };
  },
  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) {
      this.deleteTagDialog.visible = true;
      this.deleteTagDialog.deleteData = list;
    },
    doDelete(list) {
      const param = {
        tagId: list.tagId,
        requestProject: 'gic-member-tag-web'
      };
      delThirdHandTag(param)
        .then(res => {
          if (res.errorCode == 1) {
            this.$message({
              message: '删除成功',
              type: 'success',
              duration: 1000
            });
            this.$emit('deleteHandTag', this.groupId);
          }
        })
    },
    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;
}
.icon-tag-name {
  display: inline-block;
  vertical-align: bottom;
  font-size: 16px;
  cursor: pointer;
  transition: all .3s;
  color: #2f54eb;
  &:hover {
    transform: scale(1.25);
  }
}
.refresh {
  color: #909399;
  position: relative;
  top: 1px;
  &:hover {
    color: #2f54eb;
  }
}
.sort {
  // /deep/ .el-input__inner {
  //   height: 24px;
  //   width: 24px;
  //   padding: 0 7px;
  // }
  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;
}
</style>
