<template>
  <div class="member-grade-card-table">
    <div class="card-table-header">
      <p class="card-table-line"></p>
      <p class="card-table-title">{{type|typeFilter}}</p>
      <p class="card-table-tip">{{type|typeTipFilter}}</p>
    </div>
    <div class="add-level">
      <el-button @click="editSort" v-if="type==1">调整顺序</el-button>
      <el-button type="primary" @click="addCard(type)">新增{{type|typeFilter}}
      </el-button>
    </div>
    <el-table class="only-header-table">
      <el-table-column label="等级" width="80" v-if="type==='1'"/>
      <el-table-column label="卡面预览" width="260" />
      <el-table-column label="等级编码" />
      <el-table-column label="等级折扣" />
      <el-table-column label="计算方式" />
      <el-table-column label="升级条件" />
      <el-table-column label="操作" />
    </el-table>
    <div class="sort-btn-wrap" v-show="isEditSort">
      <p class="sort-btn-tip">拖拽表格上下移动，调整等级顺序</p>
      <el-button type="text" @click="cancelEditSort">取消</el-button>
      <span class="sort-btn-line"></span>
      <el-button type="text" @click="submitSort">保存</el-button>
    </div>
    <el-table :class="['only-content-table',`sortable-table-type${type}`]" :data="list"
      style="width: 100%" row-key="gradeId" v-loading="loading">
      <el-table-column prop="" label="等级" width="80" v-if="type==='1'">
        <template slot-scope="scope">
          <div class="card-index-item">
            <p>LV.{{scope.$index| indexFilter}}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" label="卡面预览" width="260">
        <template slot-scope="{row}">
          <div class="card-cell" :style="{background: row.cardColor}" :title="row.gradeName">
            <img :src="logoImg" />
            <span :style="{color: row.cardFontColor}">{{row.gradeName}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="gradeCode" label="等级编码">
      </el-table-column>
      <el-table-column prop="discountRate" label="等级折扣">
        <template slot-scope="{row}">{{row.discountRate||10}}折</template>
      </el-table-column>
      <el-table-column prop="gradeCode" label="计算方式">
        <template
          slot-scope="{row}">{{row.calculationMethod===1?'就低原则':row.calculationMethod===2?'折上折':''}}</template>
      </el-table-column>
      <el-table-column prop="upGradeCondition" label="升级条件">
      </el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="{$index,row}">
          <el-button @click="editCliqueLevel($index, row, list, type)" type="text" :disabled="isEditSort">编辑</el-button>
          <delete-tip @confirm="delCliqueLevel($index,row,list)" tips="确认删除吗?">
            <el-button type="text" :disabled="isEditSort">删除</el-button>
          </delete-tip>
        </template>
      </el-table-column>
      <template slot="empty">
        <div class="no-data-wrap">
          <div class="no-data-icon">
            <img src="../../../../../static/img/no-data_icon.png" alt="">
          </div>
          <p>暂无数据</p>
        </div>
      </template>
    </el-table>
  </div>
</template>
<script>
import { postRequest, postJson, getRequest } from '@/api/api';
import showMsg from '@/common/js/showmsg';
import errMsg  from '@/common/js/error';
import Sortable from 'sortablejs';
export default {
  name: 'MemberCardTable',
  props: {
    tableData: {
      typeL: Array,
      default: () => {
        return [];
      }
    },
    logoImg: {
      typeL: String,
      default: ''
    },
    type: {
      typeL: String,
      default: '1' // type 1 常规卡   2 特殊卡   3 付费卡
    },
    // 企业id，不传时查集团数据，否则查该id的商户数据
    enterpriseId: {
      type: String,
      default: ''
    }
  },
  watch: {
    tableData: {
      handler (n, o){
        this.list = JSON.parse(JSON.stringify(n));
      },
      deep: true,
      immediate: true
    }
  },
  filters: {
    indexFilter: (v) => {
      return v < 9 ? `0${v + 1}` : `${v + 1}`;
    },
    typeFilter: (v) => {
      switch (v) {
        case '1': return '常规卡';
        case '2': return '特殊卡';
        default:return '';
      }
    },
    typeTipFilter: (v) => {
      switch (v) {
        case '1': return '会员等级根据从低到高的顺序，自上而下进行排序';
        case '2': return '特殊卡不支持会员等级升降级';
        default:return '';
      }
    }
  },
  mounted() {
    if (this.type==1) {
      this.rowDrop();//行拖拽排序
      this.getOpenThird();
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      isEditSort: false,
      sortTable: null,
      isExist: false,
    };
  },
  methods: {
    getOpenThird() {
      getRequest('/api-admin/judge-enterprise-third-channel', {}).then(res => {
        res.data.result.isExist = true
        const { result } = res.data || {};
        this.isExist = result.isExist;
      });
    },
    checkOpenThird() {
      // 未开通的商户，不提示
      // 开通的商户才提示
      // 点击已完成才进行下一步操作
      return new Promise((resolve, reject) => {
        if (this.isExist && this.type == 1) {
          this.$confirm('您已对接「天猫」、「抖音」渠道的会员等级，为确保每个渠道的会员等级对应关系一致，在调整会员等级顺序或者新增会员等级前请联系运营经理确认是否对应渠道的会员等级关系已维护完成！', '提示', {
            cancelButtonText: '未完成',
            confirmButtonText: '已完成'
          }).then(resolve);
          return;
        }
        resolve();
      });
    },
    // 编辑集团
    editCliqueLevel(index, row, obj, type) {
      this.$emit('edit', row, type);
    },
    // 删除
    delCliqueLevel(index, row, obj) {
      let para = {
        gradeId: row.gradeId,
        enterpriseId: '',
      };
      let list=[].concat(obj)
      postRequest('/api-admin/delete-member-grade', para)
        .then((res) => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            showMsg.showmsg('删除成功', 'success');
            list.splice(index, 1)
            this.list = JSON.parse(JSON.stringify(list));
            return;
          }
          errMsg.errorMsg(resData);

        });
    },
    addCard(type) {
      this.checkOpenThird().then(() => {
        if (this.tableData.length >= 20) return this.$message.warning('每个卡类型最多可创建20张会员卡')
        this.$emit('add', type);
      });
    },
    editSort() {
      this.checkOpenThird().then(() => {
        if (!this.list.length) return this.$message.warning(`暂无${this.$options.filters.typeFilter(this.type)}！`);
        this.isEditSort = true;
        this.sortTable.option('sort', true);
      });
    },
    cancelEditSort() {
      this.isEditSort = false;
      this.sortTable.option('sort', false);
      this.list = JSON.parse(JSON.stringify(this.tableData));
    },
    submitSort() {
      this.loading = true;
      this.isEditSort = false;
      this.sortTable.option('sort', false);
      let data = {
        gradeIds: this.list.map(el => (el.gradeId)),
        gradeType: this.type
      };
      if (this.enterpriseId) {
        data.enterpriseId = this.enterpriseId;
      }
      postJson('/api-admin/sort-member-grade', data)
        .then((res) => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            this.$message.success('设置成功');
            return;
          }
        }).finally(_ => {
          this.loading = false;
        });
    },
    // 行拖拽
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector(`.sortable-table-type${this.type} .el-table__body-wrapper tbody`);
      const that = this;
      this.sortTable = new Sortable(tbody, {
        //  指定父元素下可被拖拽的子元素
        draggable: '.el-table__row',
        sort: this.isEditSort,
        onEnd({ newIndex, oldIndex }) {
          const currRow = that.list.splice(oldIndex, 1)[ 0 ];
          that.list.splice(newIndex, 0, currRow);
        }
      });
    },
  }
}
</script>
<style lang="less" scoped>
/deep/.only-header-table.el-table {
  .el-table__body-wrapper {
    display: none;
  }
}
/deep/.only-content-table.el-table {
  .el-table__header-wrapper {
    display: none;
  }
}
.member-grade-card-table+.member-grade-card-table{
  margin-top: 40px;
}
.sort-btn-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 40px;
  background: #fcf6f1;
  .sort-btn-tip {
    margin-right: 20px;
    font-size: 13px;
    font-weight: 400;
    color: #303133;
    line-height: 18px;
    cursor: default;
  }
  .sort-btn-line {
    display: block;
    width: 1px;
    height: 13px;
    margin: 0 10px;
    background: #c4c7cd;
  }
}
.card-cell {
  display: inline-flex;
  align-items: center;
  padding: 0 15px;
  max-width: 150px;
  height: 40px;
  border-radius: 4px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  img {
    width: 20px;
    height: 20px;
    border-radius: 50%;
  }
  span {
    margin-left: 10px;
    font-size: 14px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: default;
  }
}
.add-level {
  width: 100%;
  margin-bottom: 24px;
  text-align: right;
}
.card-table-header {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40px;
  margin-bottom: 20px;
  background: #ffffff;
  border-bottom: 1px solid #e4e7ed;
  .card-table {
    &-line {
      width: 3px;
      height: 14px;
      margin-right: 8px;
      background: #1890ff;
    }
    &-title {
      margin-right: 20px;
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      line-height: 20px;
    }
    &-tip {
      font-size: 12px;
      font-weight: 400;
      color: #606266;
      line-height: 17px;
    }
  }
}
.card-index-item {
  width: 40px;
  height: 20px;
  line-height: 16px;
  text-align: center;
  color: #778aff;
  // background: #778aff;
  border: 2px solid #778aff;
  border-radius: 8px;
  p {
    font-size: 12px;
    font-weight: bold;
    transform: scale(0.9);
  }
}
/deep/.el-table__empty-text::before{
  background: none;
}
</style>
<style lang="less">
.el-tooltip__popper.member-grade-edit-form-tooltip {
  max-width: 400px;
  line-height: 18px;
}
</style>
