<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-04-12 17:56:45
 * @LastEditors: 无尘
 * @LastEditTime: 2020-08-28 14:39:03
 -->
<template>
  <section class="common-right-wrap">
    <div class="p-20">
      <div class="flex flex-space-between m-b-20">
        <div style="line-height:32px;">
          <span class="font-13 color-909399 p-l-10 font-w-300">内购券针对企业内部员工发下的卡券，最多新建5个策略</span>
        </div>
        <el-button :disabled="tableData.length >= 5 ? true : false" type="primary" @click="toNewCard">新增策略</el-button>
      </div>
      <el-table class="select-table" ref="multipleCateTable" row-key="policyId" v-loading="loading" :data="tableData" tooltip-effect="dark" style="width: calc(100% - 0px);">
        <el-table-column prop="" label="" width="100" class-name="move-row-cell">
          <template slot-scope="scope">
            <span class="font-22 iconfont-hb3 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="卡券模板" show-overflow-tooltip>
          <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 ? '已下线' : '已上线' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="策略状态">
          <template slot-scope="scope">
            <div>{{ scope.row.policyStatus == 0 ? '无效' : '有效' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" width="228">
          <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" :policyId="policyId" @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: '',
      loading: false,
      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.policyId = row.policyId;
      that.recordShow = true;
    },
    closeSendRecord() {
      const that = this;
      that.policyId = '';
      that.recordShow = false;
    },
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      const that = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          /* eslint-disable */
          if (newIndex == oldIndex) {
            return false;
          }
          let arr = JSON.parse(JSON.stringify(that.tableData));
          const currRow = arr.splice(oldIndex, 1)[0];
          arr.splice(newIndex, 0, currRow);
          that.postSort(arr);
        }
      });
    },
    postSort(arr) {
      const that = this;
      const para = {
        json: JSON.stringify(arr)
      };
      postRequest('/haoban-app-customer-web/inner/change-sort', para)
        .then(res => {
          const resData = res.data;
          that.getTableList();
          if (resData.errorCode == 1) {
            showMsg.showmsg('操作成功', 'success');
            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 = {
        wxEnterpriseId: that.wxEnterpriseId,
        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`);
    },
    /**
     * 分页---页码变化
     *  @param {Number} val
     */
    handleSizeChange(val) {
      let that = this;
      that.currentPage = 1;
      that.pageSize = val;
      that.getTableList();
    },

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

    /**
     * 获取列表数据
     */
    getTableList() {
      const that = this;
      that.loading = true;
      let para = {
        wxEnterpriseId: that.wxEnterpriseId
      };
      postRequest('/haoban-app-customer-web/inner/list-policy', para)
        .then(res => {
          let resData = res.data;
          that.loading = false;
          if (resData.errorCode == 1) {
            that.tableData = JSON.parse(JSON.stringify(resData.result)) || [];
            return;
          }
          errMsg.errorMsg(resData);
        })
        .catch(function(error) {
          that.loading = false;
          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.getTableList();
    that.$nextTick( () => {
      that.rowDrop();
    })
  }
};
</script>
<style type="text/scss" lang="scss" scoped>
.w-123 {
  width: 123px;
}
.p-20 {
  padding: 20px;
  box-sizing: border-box;
}
.font-22 {
  font-size: 22px;
}
.color-c4c6cf {
  color: #c4c6cf
}
.font-w-300 {
  font-weight: 300;
}
.move-row-cell {
  .icontuozhuaiopen {
    display: none;
  }
  &:hover {
    .icontuozhuaiopen {
      display: inline-block;
      vertical-align: middle;
    }
  }
}

.el-table {
  >>> .el-table__body {
    .el-table__row {
      &:hover {
        cursor: pointer;
        .icontuozhuaiopen {
          display: inline-block;
          vertical-align: middle;
          line-height: 18px;
        }
      }
    }
  }
}
</style>
