<!--
 * @Descripttion: 导购标签
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-08-28 16:51:22
 * @LastEditors: 无尘
 * @LastEditTime: 2020-12-01 18:09:00
-->

<template>
  <div class="common-app-right no-padding">
    <div class="clerk-tag-body flex">
      <div class="clerk-tag-left border-box">
        <div class="clerk-tag-add text-center m-b-10">
          <el-button class="w-117" icon="el-icon-plus" @click="toAddCate">新建分类</el-button>
        </div>
        <tag-classify-list :tag-list="tagsClassifyData" :current-classify-id="currentClassify" :brand-id="brandId" @refreshClassify="refreshClassify" @changeClass="changeClass" @resetCurrentId="resetCurrentId"></tag-classify-list>
      </div>
      <div class="clerk-tag-right p-20 border-box">
        <div class="clerk-tag-search">
          <div class="flex flex-space-between">
            <div><el-input placeholder="请输入标签名称" maxlength="50" v-model="searchVal" style="width: 298px;" prefix-icon="el-icon-search" @keyup.native="value => toInput(value, searchVal)" clearable @clear="clearInput"></el-input></div>
            <div>
              <el-tooltip v-show="licenseData.count < licenseData.limit" class="item" effect="dark" placement="top-start">
                <div slot="content">
                  <span>当前标签数量/购买license：{{licenseData.count}}/{{licenseData.limit}}</span>
                </div>
                <el-button type="primary" @click="toAddTag">新建标签</el-button>
              </el-tooltip>
              <el-tooltip v-show="licenseData.count >= licenseData.limit" class="item" effect="dark" placement="top-start">
                <div slot="content">
                  <span >当前标签数量已达license，请先删除不使用的标签或扩容license</span>
                </div>
                <div class="el-button el-tooltip item is-disabled">新建标签</div>
              </el-tooltip>
            </div>
          </div>
        </div>
        <div class="m-t-20">
          <el-table
            :data="tagsData"
            row-key="tagId"
            v-loading="loading"
            ref="tagsData"
            style="width: 100%">
            <el-table-column v-show="currentClassify === '' && searchVal === ''" prop="" label="" width="56" class-name="move-row-cell">
              <template>
                <span :class="['font-22 iconfont icontuozhuaiopen color-c0c4cc', searchVal === '' && currentClassify === '' ? 'show-icon' : 'hide-icon']" style="cursor: move;"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="标签名称"
              show-overflow-tooltip>
              <template slot-scope="scope">{{scope.row.tagName || '--'}}</template>
            </el-table-column>
            <el-table-column
              prop=""
              label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="toEditTag(scope.$index, scope.row)">编辑</el-button>
                <el-button type="text" @click="toEditVisiable(scope.$index, scope.row)">编辑可见范围</el-button>
                <el-button type="text" @click="toDelTag(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <tag-classify-dialog v-if="showTagCate" :brand-id="brandId" @closeClassify="closeClassify"></tag-classify-dialog>
    <edit-tag-dialog v-if="showTagDialog" :current-category-id="currentClassify" :brand-id="brandId" :edit-row="editRow" @closeTag="closeTag"></edit-tag-dialog>
    <edit-visiable v-if="showTagVisiable" :brand-id="brandId" :set-item-id="setItemId" :set-type="'tag'" :select-mode="selectMode" :range-data="rangeData" @refreshData="refreshData"></edit-visiable>
  </div>
</template>

<script>
import tagClassifyList from '@/components/app/my-customer/tag-classify-list.vue';
import tagClassifyDialog from '@/components/app/my-customer/tag-classify-dialog.vue';
import editTagDialog from '@/components/app/my-customer/edit-tag-dialog.vue';
import editVisiable from '@/components/app/my-customer/edit-visiable.vue';
import fetch from '@/api/my-customer-app.js';
const { getTagClassify, getClerkTag, getTagLicense, getTagDetail, getTagVisiable, sortClerkTag, delClerkTag } = fetch;
import { _debounce } from '@/common/js/public.js';
import showMsg from '@/common/js/showmsg.js';
import Sortable from 'sortablejs';
export default {
  name: 'ClerkTag',
  components: {
    tagClassifyList,
    tagClassifyDialog,
    editTagDialog,
    editVisiable
  },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      currentClassify: '',
      searchVal: '',
      tagsClassifyData: [],
      tagsData: [],
      showTagDialog: false, // 标签
      loading: false,
      showTagCate: false, // 分类
      editRow: {},
      licenseData: {
        limit: 0, // 总数
        count: 0, // 使用数
      },
      // 可见范围
      showTagVisiable: false, // 可见范围
      selectMode: '',
      rangeData: [],
      setItemId: ''
    };
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    const that = this;
    that.$emit('showTab', '/clerk-tag');
    if (that.brandId) {
      that.getClassifyList();
    }
    that.rowDrop('tagsData');
  },
  // methods
  methods: {
    /**
     * @description: 获取标签 license
     * @author: 无尘
     */
    getTagLicenseData() {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId
      };
      getTagLicense(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.licenseData.limit = res.result.limit || 0;
          that.licenseData.count = res.result.count || 0;
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 刷新标签数据
     * @author: 无尘
     */
    refreshData() {
      const that = this;
      that.showTagVisiable = false;
      that.getTableList();
    },
    /**
     * @description: 选择分类
     * @param {Object} row
     * @author: 无尘
     */
    changeClass(row) {
      const that = this;
      that.currentClassify = row.categoryId;
      that.searchVal = '';
      that.tagsData = [];
      that.getTableList();
    },
    /**
     * @description: 新增分类
     * @author: 无尘
     */
    toAddCate() {
      const that = this;
      that.showTagCate = true;
    },
    closeClassify(res) {
      const that = this;
      that.showTagCate = false;
      that.getClassifyList();
      if (res == 'close') {
        return false;
      }
    },
    /**
     * @description: 拖拽排序
     * @param {String} data
     * @author: 无尘
     */
    rowDrop(data) {
      const tbody = this.$refs[data].$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
      const that = this;
      Sortable.create(tbody, {
        handle: '.icontuozhuaiopen',
        onEnd({ newIndex, oldIndex }) {
          if (newIndex == oldIndex || that.currentClassify != '') {
            return false;
          }
          let arr = JSON.parse(JSON.stringify(that[data]));
          const currRow = arr.splice(oldIndex, 1)[0];
          arr.splice(newIndex, 0, currRow);
          that.setSort(arr);
        }
      });
    },
    setSort(arr) {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        tagIds: arr.map(ele => ele.tagId).join(',')
      };
      sortClerkTag(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.getTableList();
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 刷新分类列表
     * @param {String} res
     * @author: 无尘
     */
    refreshClassify(res) {
      const that = this;
      that.getClassifyList();
    },
    /**
     * @description: 如果删除的分类是当前选中分类，就要重新设置当前选中分类
     * @author: 无尘
     */
    resetCurrentId() {
      const that = this;
      that.currentClassify = '';
      that.getClassifyList();
    },
    /**
     * @description: 添加标签
     * @author: 无尘
     */
    toAddTag() {
      const that = this;
      that.editRow = {};
      that.showTagDialog = true;
    },
    /**
     * @description: 编辑标签
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    toEditTag(index, row) {
      const that = this;
      that.getTagData(row.tagId);
    },
    closeTag(res) {
      const that = this;
      that.showTagDialog = false;
      if (res == 'close') {
        return false;
      }
      that.getTableList();
    },
    getTagData(tagId) {
      const that = this;
      const para = {
        tagId,
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId
      };
      getTagDetail(para, { headers: { sign: that.brandId } })
        .then(res => {
          if (res.result && !res.result.tagValueDTOList) {
            res.result.tagValueDTOList = [];
          }
          that.editRow = res.result || {};
          that.showTagDialog = true;
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 编辑可见范围
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    toEditVisiable(index, row) {
      const that = this;
      that.getVisiableData(row.tagId);
    },
    getVisiableData(tagId) {
      const that = this;
      const para = {
        relationId: tagId,
        relationType: '1',
        enterpriseId: that.brandId,
        wxEnterpriseId: that.wxEnterpriseId,
      };
      getTagVisiable(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.selectMode = String(res.result.storeMode);
          that.rangeData = res.result.bindRange ? JSON.parse(res.result.bindRange) : [];
          that.setItemId = tagId;
          that.showTagVisiable = true;
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 编辑后刷新数据
     * @author: 无尘
     */
    refreshTagData() {
      const that = this;
      that.getTableList();
    },
    /**
     * @description: 删除标签
     * @param {Number} index
     * @param {Object} row
     * @author: 无尘
     */
    toDelTag(index, row) {
      const that = this;
      that
        .$confirm('是否要删除选中的标签?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.delTagData(row.tagId, row.linkId);
        })
        .catch(() => {});
    },
    delTagData(tagId, linkId) {
      const that = this;
      const para = {
        tagId,
        linkId,
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId
      };
      delClerkTag(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.getTableList();
          if (res.code == '0000') {
            showMsg.showmsg('删除成功', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 搜索输入
     * @author: 无尘
     */
    toInput: _debounce(function() {
      const that = this;
      that.getTableList();
    }, 200),
    /**
     * @description: 搜索清除
     * @author: 无尘
     */
    clearInput() {
      const that = this;
      that.getTableList();
    },
    /**
     * @description: 获取列表数据
     * @author: 无尘
     */
    getTableList() {
      const that = this;
      that.loading = true;
      that.tagsData = [];
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        keyword: that.searchVal,
        categoryId: that.currentClassify
      };
      getClerkTag(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.loading = false;
          that.tagsData = res.result || [];
          that.getTagLicenseData();
        })
        .catch(function(error) {
          that.loading = false;
        });
    },
    /**
     * @description: 获取分类数据
     * @author: 无尘
     */
    getClassifyList() {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId
      };
      getTagClassify(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.tagsClassifyData = res.result || [];
          that.tagsClassifyData.unshift(
            {
              categoryId: '',
              categoryName: '所有',
              state: 0
            }
          );
          if (res.result && res.result.length) {
            that.getTableList();
          }
        })
        .catch(function(error) {

        });
    }
  },
  watch: {
    brandId(val) {
      const that = this;
      that.wxEnterpriseId = localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '';
      if (val) {
        that.searchVal = '';
        that.currentClassify = '';
        that.getClassifyList();
      }
    }
  }
};
</script>
<style lang='less' scoped>
  .w-117 {
    width: 117px;
  }
  .font-22 {
    font-size: 22px;
  }
  .move-row-cell {
    .icontuozhuaiopen {
      display: none;
      line-height: 20px;
    }
    &:hover {
      .show-icon {
        display: inline-block;
        vertical-align: middle;
      }
    }
  }
  .clerk-tag-body {
    .clerk-tag-left {
      position: relative;
      width: 200px;
      min-width: 200px;
      max-width: 200px;
      padding: 30px 0 0 0;
      .clerk-tag-add {
        .el-button {
          border-style: dashed;
        }
      }
    }
    .clerk-tag-right {
      position: relative;
      min-width: calc(100% - 200px);
      min-height: calc(100vh - 94px);
      border-left: 1px solid #e4e7ed;
    }
  }
</style>
