<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <el-date-picker class="w350 mr10" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh"></el-date-picker>
      <!-- <el-select class="w160 mr10" v-model="listParams.destoryMode" clearable placeholder="所有销毁方式" @change="refresh">
        <el-option v-for="(item, index) in destoryType" :key="index" :label="item.label" :value="item.value"></el-option>
      </el-select> -->
      <el-input v-model="listParams.search" class="w260 mrAuto" placeholder="请输入卡券名称" clearable @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <dm-perm-button class="specter" :disabled="$itemPerm($itemCode.gicCardDestory)" type="danger" @click="showDialog('add', {})">销毁卡券</dm-perm-button>
    </div>
    <el-table tooltip-effect="dark" :data="tableList" style="width:100%">
      <el-table-column v-for="(v, i) in tableHeader" :fixed="v.fixed" :show-overflow-tooltip="v.tooltip" :width="v.width" :min-width="v.minWidth" :align="v.align" :key="i" :prop="v.prop" :label="v.label" :formatter="v.formatter" :sortable="v.sortable">
          <template slot-scope="scope">
            <span v-if="v.formatter" v-html="v.formatter(scope.row)"></span>
            <span v-else>{{ scope.row[v.prop] || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="120px" fixed="right">
          <template slot-scope="scope">
            <dm-perm-button type="text" @click="showExport(scope.row)" :disabled="$itemPerm($itemCode.gicCardDestoryExport)">导出结果</dm-perm-button>
          </template>
        </el-table-column>
    </el-table>
    <div class="clearfix">
      <dm-pagination class="fr mb0" v-if="tableList.length" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listParams.currentPage" :page-sizes="[20, 40, 60, 80]" :page-size="listParams.pageSize" layout="total, sizes, prev, pager, next" :total="total"></dm-pagination>
    </div>
    <destory-dialog :show.sync="dialog.show" v-bind="dialog" @refresh="getTableList" />
    <dm-export-data ref="exportData" :visible.sync="exportVisible" :sens-value="true" :fields="fields" :label="label" :value="value" :sens-key="sensKey" :loading="loading" :is-created="isCreated" @export="onExport" @closed="isCreated = false" :default-select-keys="defaultSelectKeys"></dm-export-data>
  </div>
</template>

<script>
import { page, formate } from '@/mixins/table.js';
import { listTime } from '@/utils/index.js';
import fetch from '@/api/gic-card.js';
import { dealExportParams } from '@/utils/common.js';
import destoryDialog from './module/destory-dialog';
const { cardDestoryList, exportDestroyLogExcel } = fetch;
export default {
  name: 'SendList',
  components: {
    destoryDialog
  },
  mixins: [ page, formate ],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      dateTime: [],
      listParams: {
        beginTime: '',
        endTime: '',
        search: '',
        destoryMode: '',
        currentPage: 1,
        pageSize: 20
      },
      // destoryType: [{ value: 0, label: '全部销毁' }, { value: 1, label: '部分销毁' }], // eslint-disable-line
      total: 0,
      dialog: {
        show: false,
        destoryItem: '',
        type: 'add'
      },
      tableList: [],
      tableHeader: [
        {
          label: '卡券名称',
          minWidth: '120',
          align: 'left',
          fixed: 'left',
          formatter: function(row) {
            return `<span p-key="couponId" title="${row.couponId}">${ row.cardName || '--' }</span>`;
          }
        },
        {
          label: '销毁时间',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            return listTime(row.createTime);
          }
        },
        {
          label: '销毁方式',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            // 卡券销毁方式（0：全部销毁，1：部分销毁）
            return row.destroyMode ? '部分销毁' : '全部销毁';
          }
        },
        {
          label: '计划销毁数量',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            return (row.sucessCount + row.failCount) || '--';
          }
        },
        {
          label: '销毁结果',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            return `<p>成功：<span style="color:#33af4a;">${ row.sucessCount }</span></p>
                    <p>失败：<span style="color:#F5222D;">${ row.failCount }</span></p>`;
          }
        }
      ],
      // 导出组件
      exportDestroyPlanId: '',
      exportVisible: false,
      isCreated: false,
      // eslint-disable-next-line
      fields: [{label:'券码',value:'cardCode',sensKey:false},{label:'销毁结果', value: 'destroyRemark', sensKey: false},{label:'错误信息',value:'errMsg',sensKey:false}],
      sensKey: 'sensKey',
      defaultSelectKeys: [ 'cardCode', 'destroyRemark', 'errMsg' ],
      // sensValue: '',
      label: 'label',
      value: 'value'
    };
  },
  created() {
    this.$emit('updateBread', [ { breadName: '福利中心', breadPath: '/index' }, { breadName: '卡券销毁列表' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      this.getTableList();
    }
  },
  methods: {
    showDialog(type, destoryItem) {
      this.dialog.type = type;
      this.dialog.show = true;
      if (type !== 'add') {
        this.dialog.destoryItem = destoryItem;
      }
    },
    getTableList() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      this.formatterTimeFunc('beginTime', 'endTime', 'yyyy-MM-dd', 'dateTime');
      let params = { ...this.listParams, ...{ memberCardId: this.currentAreaId } };
      cardDestoryList(params).then(res => {
        this.loading = false;
        const data = res.result;
        this.tableList = data.result || [];
        this.total = data.totalCount;
        // 删除至最后一页没数据的情况，页码-1
        if (this.tableList.length === 0 && this.listParams.currentPage !== 1) {
          this.listParams.currentPage -= 1;
          this.getTableList();
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    // ********数据导出*************
    showExport({ destroyPlanId }) {
      if(!this.tableList.length) {
        this.$tips({ message: '没有要导出的数据', type: 'warning' });
        return;
      }
      this.exportDestroyPlanId = destroyPlanId;
      this.exportVisible = true;
    },
    onExport(config) {
      let params = dealExportParams({ config, listParams: { destroyPlanId: this.exportDestroyPlanId }, fieldList: this.fields, path: this.$route.path, pathName: 'GIC卡券-卡券销毁记录', query: { areaId: this.currentAreaId } });
      console.log(params);
      // 将config转换为请求参数
      // const params = config;
      // 导出数据完成后，必须调导出组件的applyReport方法
      // applyReport方法的第一个参数表示是否生成导出数据，第二个参数为导出数据的id
      exportDestroyLogExcel(params).then(res => {
        this.$refs.exportData.applyReport(true, res.result);
      }).catch(err => {
        this.$refs.exportData.applyReport();
      });
    }
  },
};
</script>
