<template>
  <div class="right-wrap">
    <topNavNew :navpath="navpath"></topNavNew>
    <div class="right-content">
      <div class="right-box">
        <div class="attention-wrap">
          <div class="title">
            <div>会员等级根据从低到高的顺序，自上而下进行排序</div>
            <!-- <div class="add-btn"><el-button type="primary" @click="addGrade">新增等级</el-button></div> -->
            <div class="add-level">
              <el-button @click="editSort" :disabled="!memberTableData.length">调整顺序</el-button>
              <el-button type="primary" @click="addGrade">新增等级</el-button>
           </div>
          </div>
          <el-table class="only-header-table">
            <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',isEditSort?'isEditSort':'']" :data="memberTableData"
            style="width: 100%" row-key="gradeId" v-loading="loading">
            <el-table-column prop="gradeName" label="会员等级名称"/>
            <el-table-column prop="gradeCode" label="等级编码"/>
            <el-table-column prop="" label="等级类型">
              <template slot-scope="{row}">
                {{ row.gradeType == 1 ? '常规卡' : '特殊卡' }}
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作">
              <template slot-scope="{$index,row}">
                <el-button @click="editGrade($index,row,memberTableData)" type="text" :disabled="isEditSort">编辑</el-button>
                <delete-tip @confirm="delGrade($index,row,memberTableData)" 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>
      </div>
    </div>
    <!-- <vue-gic-footer></vue-gic-footer> -->
  </div>
</template>
<script>
import topNavNew from 'components/nav/navNew';
import Sortable from 'sortablejs';
import showMsg from '@/common/js/showmsg';
import errMsg from '@/common/js/error';
import { getRequest, postRequest,postJson } from '@/api/api';
// import { log } from '@/utils/index.js';

export default {
  name: 'memberGrade',
  data() {
    return {
      navpath: [
        {
          name: '集团管理',
          path: ''
        },
        {
          name: '会员制度',
          path: ''
        },
        {
          name: '会员卡设置',
          path: '/memberCardSet'
        },
        {
          name: '编辑商户会员等级',
          path: ''
        }
      ],
      // 商户id
      cliqueId: '',
      cliqueName: '', //商户 name
      memberTableData: [],
      tableData: [],
      isEditSort: false,
      loading: false,
      sortTable: null
    };
  },
  mounted() {
    let that = this;
    that.cliqueId = that.$route.query.enterpriseId;
    that.cliqueName = that.$route.query.name;
    that.navpath[3].name = '编辑【' + that.cliqueName + '】会员等级';
    that.getList();
    sessionStorage.removeItem('enterpriseId');
    this.rowDrop();
  },
  watch: {
    tableData: {
      handler (n, o){
        this.memberTableData = JSON.parse(JSON.stringify(n));
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    //获取列表
    getList() {
      let that = this;
      let para = {
        enterpriseId: that.cliqueId
      };
      postRequest('/api-admin/get-enterprise-member-grade-list', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            if (!!resData.result.List && !!resData.result.List.length) {
              resData.result.List.forEach(function(ele, index) {
                ele.popVisible = false;
              });
              that.tableData = resData.result.List;
            }

            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {});
    },
    editSort() {
      this.isEditSort = true;
      this.sortTable.option('sort', true);
    },
    cancelEditSort() {
      this.isEditSort = false;
      this.sortTable.option('sort', false);
      this.memberTableData = JSON.parse(JSON.stringify(this.tableData));
    },
    submitSort() {
      this.loading = true;
      this.isEditSort = false;
      this.sortTable.option('sort', false);
      let data = {
        gradeIds: this.memberTableData.map(el => (el.gradeId)),
        gradeType: -1
      };
      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 .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.memberTableData.splice(oldIndex, 1)[ 0 ];
          that.memberTableData.splice(newIndex, 0, currRow);
        }
      });
    },

    // 编辑
    editGrade(index, row, obj) {
      this.$router.push({
        path: '/editMemberGrade',
        query: {
          gradeId: row.gradeId,
          enterpriseId: this.cliqueId,
          name: this.cliqueName
        }
      });
    },

    // 新增等级
    addGrade() {
      this.$router.push({
        path: '/addMemberGrade',
        query: {
          enterpriseId: this.cliqueId,
          name: this.cliqueName
        }
      });
    },

    // 取消删除
    cancelPop(index, row, obj) {
      row.popVisible = false;
    },

    // 删除
    delGrade(index, row, obj) {
      let para = {
        gradeId: row.gradeId,
        enterpriseId: ''
      };
      getRequest('/api-admin/delete-member-grade', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 0) {
            showMsg.showmsg('删除成功', 'success');
            obj.splice(index, 1);
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {});
    },

    // 路由跳转
    changeRoute(route) {
      this.$router.push(route);
    }
  },
  components: {
    topNavNew
  },
  beforeRouteLeave(to, from, next) {
    let that = this;
    let d = to;
    if (d.path == '/editMemberGrade' || d.path == '/addMemberGrade') {
      sessionStorage.setItem('enterpriseId', that.cliqueId);
    }
    next();
  }
};
</script>
<style lang="less" scoped>
.attention-wrap {
  padding: 24px;
  background: #fff;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  .item-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 30px;
    span {
      display: inline-block;
      width: 80px;
    }
  }

  .title {
    padding: 0 0 22px 0;
    display: -webkit-flex;
    display: flex;
    align-items: center;
    color: #828282;
    .add-btn {
      text-align: right;
    }
    div {
      -webkit-flex: 1;
      -moz-flex: 1;
      -ms-flex: 1;
      -o-flex: 1;
      flex: 1;
      font-size: 13px;
    }
  }

  .el-icon-upload2 {
    font-size: 22px;
    cursor: pointer;
  }

  .el-icon-download {
    font-size: 22px;
    cursor: pointer;
  }

  i.icon-color {
    color: #606266;
  }
  i.disable {
    color: #e6e6e6;
    cursor: not-allowed;
  }
}
/deep/.only-header-table.el-table {
  .el-table__body-wrapper {
    display: none;
  }
}
/deep/.only-content-table.el-table {
  .el-table__header-wrapper {
    display: none;
  }
  &.isEditSort .el-table__row{
    cursor: move;
  }
}
.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;
  }
}
.add-level {
  width: 100%;
  text-align: right;
}
/deep/.el-table__empty-text::before{
  background: none;
}
</style>
