<template>
  <div class="manualTagEdit-wrap common-wrap">
    <div class="right-content">
      <div class="right-box">
        <div class="manualTagEdit-wrap__title">
         <span>
            <dm-sub-title :text="tagInfo.tagName" />
            <p class="tip">导购标签排序应用于好办小程序，好办端展示按照排序从上到下展示</p>
         </span>
          <div class="operation-btn">
            <el-button v-if="$route.query.type == 'manual'" type="primary" class="ghost-btn" @click="importMember">
              <i class="iconfont icon-shangc" />
              导入多标签值会员
            </el-button>
            <el-button type="primary" class="ghost-btn" @click="exportMember">
              <i class="iconfont icon-xiazai" />
              导出人群
            </el-button>
          </div>
        </div>
        <div class="tag-value-wrapper">
          <el-table :data="tagValTableData" v-loading="loading" ref="sortTable" row-class-name="table-row" row-key="tagItemId">
            <el-table-column width="40" class-name="tag-cell sort-cell" label-class-name="tag-head">
              <template>
                <el-tooltip placement="top" content="拖动排序" trigger="hover" effect="dark" popper-class="drag-tooltip">
                  <i class="iconfont icon-tuozhuaipaixu deactive" />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="标签值" prop="tagItemName" min-width="100" class-name="tag-cell" label-class-name="tag-head">
              <template slot-scope="{ row }">
                <span>{{ row.tagItemName }}</span>
                <el-tooltip content="复制标签值" trigger="hover" placement="top">
                  <i class="iconfont copy-icon icon-fuzhi" @click="copy(row.tagItemName, $event)" />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="覆盖人数" prop="memberCount" min-width="200" class-name="tag-cell" label-class-name="tag-head"></el-table-column>
            <el-table-column label="操作" min-width="220" class-name="tag-cell" label-class-name="tag-head">
              <template slot-scope="scope">
                <template>
                  <el-button type="text" size="small" class="m-r-20" @click="toTagDetail(scope.row)">
                    查看
                  </el-button>
                  <el-button type="text" size="small" v-if="getCodeAuth && $route.query.type == 'manual'" :limit-code="getCode" class="m-r-20" :disabled="scope.row.status === 5" @click="showImportPop(scope.$index, scope.row)">
                    导入会员
                  </el-button>
                  <!-- 删除中的状态 -->
                  <template v-if="scope.row.status === 5">
                    <span class="color-c0c4cc">删除中...</span>
                  </template>
                  <!-- 删除的初始状态 -->
                  <template v-else>
                    <el-button type="text" size="small" @click="onDeleteTag(scope.row, scope.$index, $event)">删除</el-button>
                  </template>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--单独会员标签值导入-->
        <import-dialog :visiable.sync="importPop.isShow" :data="importPop" @submit="tagItemImport" @close="closeImportPop" />
        <!--导入多标签会员-->
        <import-dialog :visiable.sync="importBatchPop.isShow" :data="importBatchPop" @submit="tagItemBatchImport" @close="closeImportBatchPop" />
      </div>
    </div>
    <Trash ref="Trash" @beginClean="getValueData" />
    <!--导出人群-->
    <vue-gic-export-excel
      :dialogVisible.sync="exportMemberData.show"
      :excelUrl="exportMemberData.excelUrl"
      :params="exportMemberData.params"
      :dataArr="tagValTableData"
      type="2"
      projectName="member-tag"
    ></vue-gic-export-excel>
    <!--表格字段-->
    <dm-table-filed :visible.sync="tableFiledVisible" projectName="member-tag" pageName="memberTag" :max="20" :defaultDisabled="['memberName']" :checkedFields="checkFields" @submit="onSubmiTableFiled" />
    <i id="aniIcon" class="iconfont icon-shougongbiaoqian aniIcon" :style="{ right: `${animationPos.x}px`, bottom: `${animationPos.y}px` }"></i>
    <delete-tag-dialog :visible.sync="deleteTagDialog.visible" :data="deleteTagDialog.deleteData" @submit="delTagApi" />
  </div>
</template>
<script>
import './manualTagEdit.css';
import copy from '@/utils/clipboard';
import navCrumb from '@/components/nav/nav.vue';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import Trash from '@/components/Trash.vue';
import importDialog from './import-member-dialog.vue';
import DeleteTagDialog from './delete-tag-dialog.vue';
/* eslint-disable */
import { getRequest, postForm } from '@/api/api';
import Sortable from 'sortablejs';
/**
 * 通过excel导入会员的业务逻辑 2019-5-27
 * 轮询接口的实现方式
 *  refreshTag用来保存需要轮询的标签值tagItemIndex索引和tagItemId ID
 *  页面打开后，会调用getValueData根据取到的标签值的状态，将需要轮询的标签值存入refreshTag中，然后开始轮询
 *  添加和删除标签值后，会重新调用getValueData，执行上一步操作
 *  当有标签值状态更新后，会将refreshTag中对应的标签值移除
 *  当refreshTag中无数据时，终止轮询。
 * */
export default {
  name: 'manual-tag-value-edit',
  data() {
    return {
      // 编辑标签的时候,获取标签的 id
      tagId: '',
      // 标签的基本信息
      tagInfo: {
        tagName: '',
        tagDescribe: '',
        tagLevelGroupId: '',
        tagLevelGroupName: ''
      },

      // excel单独标签值导入的弹窗的相关数据
      importPop: {
        isShow: false,
        // 标签值的索引
        tagItemIndex: '',
        // 标签值的id
        tagItemId: '',
        // false=0: 不删除, true=1: 删除
        optType: false,
        title: '',
        // 当前上传 excel 的表格名字
        excelName: '',
        // 当前上传 excel 内容的数据
        excelData: [],
        // 当前上传 excel 表头的数据
        excelHeader: [],
        downLoadUrl: '/gic-member-tag-web/memberTag/member-import-template-download?requestProject=gic-member-tag-web'
      },
      // excel多个标签值导入的弹窗的相关数据
      importBatchPop: {
        isShow: false,
        // 标签值的索引
        tagItemIndex: '',
        // 标签值的id
        tagItemId: '',
        // false=0: 不删除, true=1: 删除
        optType: false,
        title: '',
        // 当前上传 excel 的表格名字
        excelName: '',
        // 当前上传 excel 内容的数据
        excelData: [],
        // 当前上传 excel 表头的数据
        excelHeader: [],
        downLoadUrl: '/gic-member-tag-web/memberTag/member-import-template-download?requestProject=gic-member-tag-web&type=2'
      },

      // 标签值列表的数据
      tagValTableData: [],
      // 需要查询进度的标签值索引和id
      // 每次获取标签值列表时更新、标签值有新的状态时更新
      refreshTag: [],
      // 需要显示上传完成的标签值id
      uploadedTag: [],
      timer: null,
      animationPos: {
        x: 1000,
        y: 500
      },
      isShowAdd: true,
      exportMemberData: {
        show: false,
        excelUrl: '/gic-member-tag-web/memberTag/memberTagExportExcel',
        params: {
        },
      },
      deleteTagDialog: {
        visible: false,
        deleteData: {}
      },
      tableFiledVisible: false,
      checkFields: ['cardNo','gradeName','crateCardDateStringFormat','lastCostTimeFormat','costTimes','avgCost','birthdayMDFormat','pointsCurrent','costAll','mainStoreName','openStoreName'],
      loading: false
    };
  },
  computed: {
    getCodeAuth() {
        let code = "memberTagImportMember";
        return this.$getButtonLimit(this.$buttonCode[code]);
    },
    getCode() {
      let code = "memberTagImportMember";
      return this.$buttonCode[code];
    }
  },
  methods: {

    // 添加和编辑标签值
    addTagItem(tagItemId, tagItemName) {
      const para = {
        tagItemId: tagItemId,
        tagItemName: tagItemName,
        tagId: this.tagId
      };

      getRequest('/memberTag/saveHandTagItem', para).then(res => {
        const { errorCode } = res.data;
        if (errorCode === 1) {
          showMsg.showmsg('添加成功', 'success');
          this.getValueData();
          return;
        }
        errMsg.errorMsg(res.data);
      }).catch(error => {
        this.$message.error({
          duration: 1000,
          message: error.message
        });
      });
    },

    // 删除标签值
    delTagApi(data) {
      const item = data;
      const { currentIndex: index, e, memberCount, tagItemId } = data;
      // memberCount为0时不加入垃圾桶,直接删除
      if (memberCount == 0) {
         this.directDelTag(tagItemId);
      } else {
         this.intoTrash(item, index, e);
      }
    },
    // 加入到垃圾桶
    intoTrash(item, index, e) {
        const para = {
          itemId: item.tagItemId
        };
        this.refreshTag.push({
          tagItemIndex: index,
          tagItemId: item.tagItemId
        });
        this.tagValTableData[index].showDelPopOver = false;
        getRequest('/delTagItem/add', para).then(res => {
          const { errorCode, result } = res.data;
          if (errorCode === 1) {
            item.delStatus = 0;
            this.$refs.Trash.getTrashList();
            this.handleRefreshTag();
            this.startAnimation(e)
            return;
          }
          this.$message.error(result)
        }).catch(error => {
          this.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    // 直接删除标签值
    directDelTag(tagItemId) {
      console.log(tagItemId);
      const para = { tagItemId };
      getRequest('/member-tag-value/delTagItem', para).then(res => {
        const { errorCode, result } = res.data;
        if (errorCode === 1) {
          this.$message.success('删除成功');
          this.getValueData();
          return;
        }
        this.$message.error(result)
      })
    },
    startAnimation(e) {
      this.animationPos = {
        x: document.body.offsetWidth - e.pageX,
        y: document.body.offsetHeight - e.pageY
      }
      document.querySelector('#aniIcon').style.display = 'block'
      setTimeout(_ => {
        document.querySelector('#aniIcon').style.display = 'none'
      }, 1800)
    },

    // 获取标签值列表
    getValueData() {
      this.loading = true;
      const para = {
        tagId: this.tagId
      };
      getRequest('/memberTag/queryHandTagItem', para).then((res) => {
        const { errorCode, result } = res.data;
        if (errorCode === 1) {
          /**
           * 前端自定义的扩展字段
           * 为了实现一个标签值的数据上传中另一个标签值仍可以上传的功能
           * 上传完毕后，扩展字段需要重置
           * */
          this.refreshTag = [];
          result.forEach((ele, index) => {
            ele.showDelPopOver = false;
            // 上传进度百分比值
            ele.percent = 0;
            // 4 删除中 5删除项 6 处理中
            if (ele.status === 4 || ele.status === 5 || ele.status === 6) {
              this.refreshTag.push({tagItemIndex: index, tagItemId: ele.tagItemId});
            }
            ele.isCurrent = false;
          });
          this.tagValTableData = result;
          if (result.some(v => v.isWeimob)) this.isShowAdd = false;
          this.handleRefreshTag();
          return;
        }
        errMsg.errorMsg(res.data);
      }).catch(error => {
        this.$message.error({
          duration: 1000,
          message: error.message
        });
      }).finally(() => this.loading = false);
    },
    // 跳转会员标签人数详情页面
    toTagDetail(row){
      this.$router.push(`/manualTagValueEditInfo?tagId=${row.tagId}&tagItemId=${row.tagItemId}`)
    },
    // 单独标签值导入会员--------------------------------------------------------------------------------
    // 显示导入会员的弹窗
    showImportPop(index, row) {
      // 状态为删除中，不可以导入会员
      this.importPop.isShow = true;
      this.importPop.tagItemIndex = index;
      this.importPop.tagItemId = row.tagItemId;
      this.importPop.title = `${row.tagItemName}-导入会员`
    },

    // 关闭导入会员的弹窗
    closeImportPop() {
      this.resetImportData();
    },

    // 重置导入的表格数据
    resetImportData() {
      this.importPop.excelName = '';
      this.importPop.excelData = [];
      this.importPop.excelHeader = [];
      this.importPop.optType = false;
      this.importPop.isShow = false;
    },

    // 导入数据到服务端
    tagItemImport(fileData, uploadVm) {
      // 该标识用来防止多次被点击
      if (this.flag) return;
      this.flag = true;
      uploadVm.value = '';
      this.refreshTag.push({
        tagItemIndex: this.importPop.tagItemIndex,
        tagItemId: this.importPop.tagItemId
      });
      let {tagItemId, optType } = this.importPop;
      const param = new FormData();
      param.append("file", fileData);
      param.append("optType", optType ? 1 : 0);
      param.append("tagItemId", tagItemId);
      param.append("requestProject", 'member-tag');
      postForm('/memberTag/uploadTagItemExcel', param).then((res) => {
        const { errorCode } = res.data;
        if (errorCode === 1) {
          this.closeImportPop();
          this.$toTaskCenter(res.data.result);
          this.flag = false;
        } else {
          this.flag = false;
          errMsg.errorMsg(res.data);
        }
      })
    },


    // 多个标签值导入会员----------------------------------------------------------------------------------
    importMember() {
      this.importBatchPop.isShow = true;
      this.importBatchPop.title = `导入多标签值会员`;
    },
    // 关闭导入会员的弹窗
    closeImportBatchPop() {
      this.importBatchPop.excelName = '';
      this.importBatchPop.excelData = [];
      this.importBatchPop.excelHeader = [];
      this.importBatchPop.optType = false;
      this.importBatchPop.isShow = false;
    },
    // 导入数据到服务端
    tagItemBatchImport(fileData, uploadVm) {
      if (this.flag) return;
      this.flag = true;
      uploadVm.value = '';
      let { optType } = this.importBatchPop;
      const param = new FormData();
      param.append("file", fileData);
      param.append("optType", optType ? 1 : 0);
      param.append("tagId", this.tagId);
      param.append("requestProject", 'member-tag');
      postForm('/memberTag/uploadTagExcel', param).then((res) => {
        const { errorCode } = res.data;
        if (errorCode === 1) {
          // 关闭上传的弹窗
          this.closeImportBatchPop();
          this.$toTaskCenter(res.data.result);
          this.flag = false;
        } else {
          this.flag = false;
          errMsg.errorMsg(res.data);
        }
      })
    },
    // --------------------------------------------------------------------------------------------------
    handleRefreshTag() {
      // 根据refreshTag的tagItemIndex比对tagValueTableData的tagItemId是否相同，如果相同，就操作tagValueTableData的数据，不同就不操作
      // 新增和删除标签值完成后，重新执行getValueData方法，刷新标签值列表数据，重启轮询
      // 当refreshTag的length为0时，终止轮询
      if (this.refreshTag.length === 0) return;
      let allPro = [];
      this.refreshTag.forEach(item => {
        allPro.push(this.getImportReport(item.tagItemIndex, item.tagItemId));
      })
      Promise.all(allPro).then(() => {
        clearTimeout(this.timer);
        this.timer = setTimeout(this.handleRefreshTag, 1000);
      })
    },
    // 查询上传、删除的进度
    getImportReport(tagItemIndex, tagItemId) {
      return getRequest('/memberTag/getImportReport', { tagItemId }).then((res) => {
        const { errorCode, result } = res.data;
        if (errorCode === 1) {
          // 0 删除 1正常 2导入中 3 导入完成 4 删除中 5删除项 6 处理中 7 异常 8 处理成功
          switch (result.status) {
            case 0:
              // 已删除
              if (this.tagValTableData[tagItemIndex].tagItemId === tagItemId) {
                this.refreshTag = this.refreshTag.filter(item => item.tagItemId !== tagItemId)
                this.getValueData();
              }
              break;
            case 5:
              // 删除进行中
              if (this.tagValTableData[tagItemIndex].tagItemId === tagItemId) {
                this.tagValTableData[tagItemIndex].status = 5;
              }
              break;
            case 4:
            case 6:
              // 导入进行中
              if (this.tagValTableData[tagItemIndex].tagItemId === tagItemId) {
                this.tagValTableData[tagItemIndex].status = result.status;
                const num =result.totalNum == 0 ? 0 : parseInt((result.totalNum - result.needExec) / result.totalNum * 100);
                this.tagValTableData[tagItemIndex].percent = num === 100 ? 99 : num;
              }
              break;
            case 8:
              // 导入完成
              if (this.tagValTableData[tagItemIndex].tagItemId === tagItemId) {
                this.tagValTableData[tagItemIndex].status = result.status;
                // 已经上传完成的标签值不在轮询
                this.refreshTag = this.refreshTag.filter(item => item.tagItemId !== tagItemId);
                this.uploadedTag.push(tagItemId);
                // 上传的错误数量
                this.tagValTableData[tagItemIndex].errorCount = result.needError;
                // 重置百分比为0
                this.tagValTableData[tagItemIndex].percent = 0;
                this.getValueData();
              }
              break;
            default:
              if (this.tagValTableData[tagItemIndex].tagItemId === tagItemId) {
                this.tagValTableData[tagItemIndex].status = result.status;
                // 已经上传完成的标签值不在轮询
                this.refreshTag = this.refreshTag.filter(item => item.tagItemId !== tagItemId);
                // 重置错误数量、百分比为0
                this.tagValTableData[tagItemIndex].errorCount = 0;
                this.tagValTableData[tagItemIndex].percent = 0;
              }
              break;
          }
        } else {
          errMsg.errorMsg(res.data);
        }
      }).catch(error => {
        this.$message.error({
          duration: 1000,
          message: error.message
        });
      });
    },

    // 获取三级分类列表
    getOptionsThree(tagLevelGroupId) {
      getRequest('/tagLevel/handThirdLevel', { tagLevelGroupId }).then(res => {
        const { errorCode, result } = res.data;
        if (errorCode === 1) {
          let tagGroup = result.filter(item => item.tagLevelGroupId === this.tagInfo.tagLevelGroupId);
          if (tagGroup.length > 0) {
            this.tagInfo.tagLevelGroupName = tagGroup[0].levelName;
          }
        }
      }).catch(error => {
        this.$message.error({
          duration: 1000,
          message: error.message
        });
      });
    },

    // 编辑时获取当前标签数据
    getTagData(tagId) {
      getRequest('/memberTag/getTagById', { tagId }).then(res => {
        const { errorCode, result } = res.data;
        if (errorCode === 1) {
          this.tagInfo = {
            tagName: result.tagName,
            tagLevelGroupId: result.tagLevelGroupId,
            tagDescribe: result.tagDescribe
          }
          // 获取标签值列表
          this.getValueData();
          this.getOptionsThree(result.tagTwoLevelGroupId);
        }
      }).catch(err => {
        console.log(err);
      });
    },
    exportMember() {
      const isExiteRecordPerson = this.tagValTableData.some(el => +el.memberCount > 0);
      if (!this.tagValTableData.length || !isExiteRecordPerson) return this.$message.error('没有要导出的数据');
      this.tableFiledVisible = true;
    },
    onSubmiTableFiled(data) {
      const { exportMemberData: { params: exportParams } } = this;
      this.exportMemberData.excelUrl = '/gic-member-tag-web/memberTag/memberTagExportExcel';
      this.exportMemberData.show = true;
      exportParams.exportFields = data.toString();
      exportParams.tagId = this.tagId;
      let origin = window.location.origin;
      origin = origin.indexOf('localhost') >= 0 ? 'http://gicdev.demogic.com/' : origin;
      this.exportMemberData.excelUrl = origin + this.exportMemberData.excelUrl;
    },
    onDeleteTag(row, index, e) {
      this.deleteTagDialog.visible = true;
      this.deleteTagDialog.deleteData = {
        ...row,
        currentIndex: index,
        e
      };
    },
    //  拖拽
    drag() {
      let _this = this;
      const tbody = this.$refs.sortTable.$el.querySelector('.el-table__body tbody');
      const sort = Sortable.create(tbody, {
        onChoose(e) {
          // 针对icon触发事件
          const isSortIcon = e.originalEvent.target.classList.contains('icon-tuozhuaipaixu');
          sort.option('sort', isSortIcon);
        },
        onEnd({ newIndex, oldIndex }) {
          const isRemote = sort.options.sort;
          const currRow = _this.tagValTableData.splice(oldIndex, 1)[0];
          _this.tagValTableData.splice(newIndex, 0, currRow);
          if (isRemote) {
            const tagItemIdAfter = newIndex > 0 ? _this.tagValTableData[newIndex - 1].tagItemId : null;
            const params = { tagId: _this.$route.query.tagId,  tagItemId: currRow.tagItemId, tagItemIdAfter};
            _this.remoteDragData(params);
          }
        }
      })
    },
    remoteDragData(params) {
      getRequest('/member-tag-value/tag-item-sort', params);
    },
    // 复制文字
    copy(text, e) {
      copy(text, e);
    }
  },
  mounted() {
    const tagId = this.$route.query.tagId;
    if (tagId) {
      this.tagId = tagId;
      this.getValueData();
      this.getTagData(tagId);
    }
    this.drag();
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  components: {
    navCrumb,
    Trash,
    importDialog,
    DeleteTagDialog
  }
}
</script>
<style lang="less" scoped>
  .manualTagEdit-wrap {
    padding-bottom: 56px;
  }
  .right-box {
    padding: 0 !important;
    min-height: 68vh;
    .manualTagEdit-wrap__title {
      margin-bottom: 0;
      padding: 22px 24px 18px;
      width: 100%;
      font-size: 16px;
      color: #303133;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 2px solid #EDEFF2;
    }
    .tag-value-wrapper {
      padding: 24px;
    }
  }
  .aniIcon {
    display: none;
    position: absolute;
    z-index: 99999;
    color: #2F54EB;
    font-size: 26px;
    animation: toTrash 2s infinite;
    opacity: 0;
  }
  @keyframes toTrash {
    0% {
      opacity: 1;
    }
    100% {
      right: 30px;
      bottom: 380px;
      font-size: 12px;
    }
  }
  .tip {
    color: #606266;
    font-size: 12px;
    margin-top: 10px;
  }
  .table-row:hover {
    .deactive {
      color: #606266;
      display: block;
      cursor: grabbing;
    }
  }
  .deactive {
    display: none;
  }
  .copy-icon {
    display: inline-block;
    margin-left: 3px;
    width: 24px;
    height: 24px;
    font-size: 14px;
    text-align: center;
    color: #606266;
    border-radius: 2px;
    cursor: pointer;
    &:hover {
      background-color: #E5E6EB;
    }
  }
</style>
