<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-08-27 11:36:51
 * @LastEditors: 无尘
 * @LastEditTime: 2020-12-01 18:08:49
-->

<template>
  <div class="common-app-right">
    <div>
      <div class="data-dimension-tip">
        <common-alert-tip :width="'100%'" :tip-content="tipContent"></common-alert-tip>
      </div>
      <div class="data-dimension-table flex">
        <div class="data-dimension-table_left flex-1">
          <div class="m-b-18">
            <el-tooltip class="item" effect="dark" placement="right">
              <div slot="content">
                排序越靠上的权重越高，当一家门店拥有多个会员卡时，优先展示排序最靠上的会员卡
              </div>
              <span class="common-bottom-border table-title">会员卡权重</span>
            </el-tooltip>
          </div>
          <el-table
            ref="memberCardData"
            :data="memberCardData"
            row-key="id"
            v-loading="loadingMember"
            style="width: 100%">
            <el-table-column prop="" label="" width="56" class-name="move-row-cell show-icon">
              <template>
                <span class="font-22 iconfont icontuozhuaiopen color-c0c4cc" style="cursor: move;"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="会员卡名称"
              show-overflow-tooltip>
               <template slot-scope="scope">{{scope.row.name || '--'}}</template>
            </el-table-column>
          </el-table>
        </div>
        <div class="data-dimension-table_right flex-1">
          <div class="m-b-18">
            <el-tooltip class="item" effect="dark" placement="right">
              <div slot="content">
                排序越靠上的权重越高，当一家门店拥有多个服务号时，优先展示排序最靠上的服务号
              </div>
              <span class="common-bottom-border table-title">服务号权重</span>
            </el-tooltip>
          </div>
          <el-table
            ref="serviceNumData"
            :data="serviceNumData"
            row-key="id"
            v-loading="loadingService"
            style="width: 100%">
            <el-table-column prop="" label="" width="56" class-name="move-row-cell show-icon">
              <template>
                <span class="font-22 iconfont icontuozhuaiopen color-c0c4cc" style="cursor: move;"></span>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="服务号名称"
              show-overflow-tooltip>
               <template slot-scope="scope">{{scope.row.name || '--'}}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import commonAlertTip from '@/components/common/common-alert-tip.vue';
import Sortable from 'sortablejs';
import fetch from '@/api/my-customer-app.js';
const { getMemberData, saveSortMember } = fetch;
import showMsg from '@/common/js/showmsg.js';
export default {
  name: 'DataDimensionPage',
  components: {
    commonAlertTip
  },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      wxEnterpriseId: localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '',
      tipContent: '当商户有多个会员卡和服务号时，会造成单家门店适用于多个会员卡或服务号，即单个顾客会有多个域的身份信息，这容易造成门店成员的困扰。请为以下会员卡和服务号域做权重排序，当顾客有多个域的身份信息时，门店成员将只能看到权重最高域的一个身份信息。',
      memberCardData: [], // 会员卡列表
      serviceNumData: [], // 服务号列表
      loadingMember: false,
      loadingService: false,
    };
  },
  // 生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    const that = this;
    that.$emit('showTab', '/data-dimension');
    that.rowDrop('memberCardData');
    that.rowsDrop('serviceNumData');
    if (!!that.brandId) {
      that.getMemberCrad();
    }
  },
  // methods
  methods: {
    /**
     * @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) {
            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, data);
        }
      });
    },
    rowsDrop(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) {
            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, data);
        }
      });
    },
    setSort(arr, data) {
      const that = this;
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId,
        sorts: arr.map(ele => ele.id).join(','),
        type: data == 'memberCardData' ? '0' : '1'
      };
      saveSortMember(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.getMemberCrad();
          if (res.code == '0000') {
            showMsg.showmsg('操作成功', 'success');
          }else {
            showMsg.showmsg(res.message || '接口异常', 'warning');
          }
        })
        .catch(function(error) {

        });
    },
    /**
     * @description: 获取会员卡数据
     * @author: 无尘
     */
    getMemberCrad() {
      const that = this;
      that.loadingMember = true;
      that.loadingService = true;
      // 防止拖拽后排序失败页面无刷新情况
      that.memberCardData = [];
      that.serviceNumData = [];
      const para = {
        wxEnterpriseId: that.wxEnterpriseId,
        enterpriseId: that.brandId
      };
      getMemberData(para, { headers: { sign: that.brandId } })
        .then(res => {
          that.loadingMember = false;
          that.loadingService = false;
          if(res.result.cards && res.result.cards.length){
            that.memberCardData = that.sortTable(res.result.cards);
          }else {
            that.memberCardData = [];
          }
          if(res.result.services && res.result.services.length){
            that.serviceNumData = that.sortTable(res.result.services);
          }else {
            that.serviceNumData = [];
          }
        })
        .catch(function(error) {
          that.loadingMember = false;
          that.loadingService = false;
        });
    },
    /**
     * @description: 排序
     * @param {Array} arr
     * @returns {Array}
     * @author: 无尘
     */
    sortTable(arr) {
      arr.sort(function(a, b) {
        return (a.sort - b.sort);
      });
      return arr;
    }
  },
  watch: {
    brandId(val) {
      const that = this;
      that.wxEnterpriseId = localStorage.getItem('haoBanUser') ? JSON.parse(localStorage.getItem('haoBanUser')).wxEnterpriseId : '';
      if (val) {
        that.memberCardData = [];
        that.serviceNumData = [];
        that.getMemberCrad();
      }
    }
  }
};
</script>
<style lang='less' scoped>
  .font-22 {
    font-size: 22px;
  }
  .common-bottom-border {
    cursor: pointer;
    padding-bottom: 2px;
    border-bottom: 1px dashed #2f54eb;
    &.table-title {
      font-size: 14px;
      line-height: 20px;
      font-weight: 600;
      color: #303133;
    }
  }
  .data-dimension-table {
    margin-top: 32px;
    .m-b-18 {
      margin-bottom: 18px;
    }
    .data-dimension-table_left {
      width: calc((100% - 47px)/2);
    }
    .data-dimension-table_right {
      width: calc((100% - 47px)/2);
      margin-left: 47px;
    }
  }
</style>
