<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-04-12 17:56:45
 * @LastEditors: 无尘
 * @LastEditTime: 2020-04-26 16:17:47
 -->
<template>
  <section class="common-right-wrap">
    <div class="p-20">
      <div class="flex flex-space-between m-b-20">
        <div>
          <span class="font-14 color-909399 p-l-10">内购券针对企业内部员工发下的卡券，最多新建5个策略</span>
        </div>
        <el-button v-if="tableData.length < 5" type="primary" @click="toNewCard">新增策略</el-button>
      </div>
      <el-table class="select-table" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: calc(100% - 3px);">
        <el-table-column prop="" label="" width="100">
          <template slot-scope="scope">
            <span class="font-14 iconfont icontuozhuaiopen color-c4c6cf" style="cursor: move;"></span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="卡券策略名称" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.policyName }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="卡券模板">
          <template slot-scope="scope">
            {{ scope.row.cardTemplates }}
            <!-- <span v-for="(item, key) in scope.row.cardTemplateJson" :key="key + 'temp'">{{ item.templateName }}</span> -->
          </template>
        </el-table-column>
        <el-table-column prop="" label="状态">
          <template slot-scope="scope">
            <div>{{ scope.row.onlineFlag == 0 ? '已下线' : '已上线' }}, {{ scope.row.policyStatus == 0 ? '无效' : '有效' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text" @click="toSwitch(scope.$index, scope.row)">{{ scope.row.onlineFlag == 0 ? '上线' : '下线' }}</el-button>
            <el-button type="text" @click="toEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" @click="toRecord(scope.$index, scope.row)">记录</el-button>
            <el-button v-if="scope.row.onlineFlag == 0" type="text" @click="toDel(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <record-detail v-if="recordShow" :coupCardId="coupCardId" @closeSendRecord="closeSendRecord"></record-detail>
  </section>
</template>

<script>
import recordDetail from '@/components/app/protectCard/record-detail.vue';
import Sortable from 'sortablejs';
import errMsg from '@/common/js/error';
import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
import { postRequest } from '@/api/api';
export default {
  components: { recordDetail },
  props: {
    brandId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      activeId: '2',
      wxEnterpriseId: localStorage.getItem('userInfos') ? JSON.parse(localStorage.getItem('userInfos')).wxEnterpriseId : '',
      searchInput: '',
      tableData: [],
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      recordShow: false,
      coupCardId: ''
    };
  },
  watch: {
    brandId(val) {
      if (!!val) {
        this.getTableList();
      }
    }
  },
  methods: {
    /**
     * 详情卡券
     */
    toRecord(index, row) {
      const that = this;
      that.coupCardId = row.coupCardId;
      that.recordShow = true;
    },
    closeSendRecord() {
      const that = this;
      that.coupCardId = '';
      that.recordShow = false;
    },
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      const that = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          /* eslint-disable */
          const currRow = that.tableData.splice(oldIndex, 1)[0];
          that.tableData.splice(newIndex, 0, currRow);
          console.log(that.tableData, newIndex, oldIndex);
          that.postSort();
        }
      });
    },
    postSort() {
      const that = this;
      let para = {
        json: JSON.stringify(that.tableData)
      };
      postRequest('/haoban-app-customer-web/inner/change-sort', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.getTableList();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 删除
     */
    toDel(index, row) {
      const that = this;
      that
        .$confirm('是否要删除选中的卡券策略?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.delCardList(row.policyId);
        })
        .catch(() => {});
    },
    /**
     * 删除卡券
     */
    delCardList(policyId) {
      const that = this;
      let para = {
        policyId: policyId
      };
      postRequest('/haoban-app-customer-web/inner/delete-policy', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('删除成功', 'success');
            that.getTableList(that.brandId);
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 编辑卡券
     */
    toEdit(index, row) {
      const that = this;
      that.$router.push(`/newCardStrategy?policyId=${row.policyId}`);
    },
    /* 上线/下线*/
    toSwitch(index, row) {
      const that = this;
      let para = {
        onlineFlag: row.onlineFlag == 1? 0: 1,
        policyId: row.policyId
      };
      postRequest('/haoban-app-customer-web/inner/on-off-line', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            that.getTableList();
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    },
    /**
     * 输入
     */
    toInput: _debounce(function(e, value) {
      const that = this;
      that.currentPage = 1;
      that.getTableList(that.brandId);
    }, 500),
    // 搜索清除
    clearInput() {
      const that = this;
      that.currentPage = 1;
      that.getTableList(that.brandId);
    },
    /**
     * 新建卡券
     */
    toNewCard() {
      const that = this;
      that.$router.push(`/newCardStrategy`);
    },
    /**
     * 分页---页码变化
     */
    handleSizeChange(val) {
      let that = this;
      that.pageSize = val;
      that.getTableList();
    },

    /**
     * 分页---当前页变化
     */
    handleCurrentChange(val) {
      let that = this;
      that.currentPage = val;
      that.getTableList();
    },
    /**
     * 切换年
     */
    changeYear() {
      let that = this;
      that.currentPage = 1;
      that.getTableList();
    },

    /**
     * 获取列表数据
     */
    async getTableList() {
      const that = this;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId
      };
      postRequest('/haoban-app-customer-web/inner/list-policy', para)
        .then(res => {
          let resData = res.data;
          if (resData.errorCode == 1) {
            that.tableData = resData.result || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.$message.error({
            duration: 1000,
            message: error.message
          });
        });
    }
  },
  mounted() {
    let that = this;
    that.$emit('showTab', '2');
    // 阻止默认行为
    document.body.ondrop = function(event) {
      event.preventDefault();
      event.stopPropagation();
    };
    that.rowDrop();
    that.getTableList();
  }
};
</script>
<style type="text/less" lang="less" scoped>
.w-123 {
  width: 123px;
}
.p-20 {
  padding: 20px;
  box-sizing: border-box;
}
</style>
