<template>
  <div class="dm-wrap">
    <el-input type="text" placeholder="请输入卡券代码/微盟wid" prefix-icon="el-icon-search" style="width: 300px" clearable v-model.trim="search" @change="onSearch"></el-input>
    <!-- <el-button style="float: right;margin-left: 10px" type="primary" @click="onMultipleReasyn">批量重新同步</el-button> -->
    <el-button style="float: right;color:#2F54EB;border-color:#2F54EB" @click="onMultipleCancel">批量不处理</el-button>
    <el-table :data="logs" style="margin-top: 20px" ref="multipleTable" @selection-change="onSelectChange">
      <el-table-column type="selection" width="40px"></el-table-column>
      <el-table-column label="同步时间">
        <div slot-scope="{ row }" style="line-height: normal">
          <p>{{ formatDateTimeByType(row.updateTime, 'yyyy-MM-dd-HH-mm-ss', true).y }}</p>
          <p>{{ formatDateTimeByType(row.updateTime, 'yyyy-MM-dd-HH-mm-ss', true).h }}</p>
        </div>
      </el-table-column>
      <el-table-column label="错误提示" prop="wmResponse"></el-table-column>
      <el-table-column label="同步类型" prop="sendType">
        <template slot-scope="{ row }">{{ row.sendType == 1 ? '推送卡券' : row.sendType == 2 ? '核销卡券' : '--' }}</template>
      </el-table-column>
      <el-table-column label="卡券代码" prop="couponCode"></el-table-column>
      <el-table-column label="WID/会员卡号" prop="wid"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="text" @click="onReasyn(row)">重新同步</el-button>
          <el-button type="text" @click="onCancel(row)">不处理</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination v-if="pager.total > 0" style="margin-top: 20px;text-align: right" layout="total,sizes,prev,pager,next" background :total="pager.total" :page-sizes="pager.pageSizes" :page-size="pager.pageSize" :current-page="pager.currentPage" @current-change="onCurrentChange" @size-change="onSizeChange"></el-pagination>
  </div>
</template>

<script>
import { getCouponLogs, delCouponLog, sendCouponReset, consumeCoupon } from '@/service/api/cardApi.js';
import { formatDateTimeByType } from '@/utils/index.js';

export default {
  name: 'card-async-logs',
  data() {
    return {
      logs: [],
      search: '',
      pager: {
        total: 0,
        pageSizes: [20, 40, 60, 80],
        pageSize: 20,
        currentPage: 1
      },
      multipleSelect: {
        multipleType: '', // 无全选：0，选择本页：1，选择全部：2
        selected: []
      }
    };
  },
  created() {
    this.getLogs();
  },
  methods: {
    formatDateTimeByType,
    getLogs() {
      const { currentPage, pageSize } = this.pager;
      const params = {
        searchStr: this.search,
        pageNum: currentPage,
        rowCount: pageSize
      };
      getCouponLogs(params).then(res => {
        const { errorCode, message, result } = res || {};
        if (errorCode != 0) {
          this.$message.error(message);
          return;
        }
        this.pager.total = result.totalCount;
        this.logs = result.result || [];
        if (this.multipleSelect.multipleType == 2) {
          this.$refs.multipleTable.toggleAllSelection();
          this.$nextTick(() => {
            this.multipleSelect.multipleType = 2;
          });
        }
      });
    },
    onSearch() {
      // 查询
      this.pager.currentPage = 1;
      this.getLogs();
    },
    onCurrentChange(currentPage) {
      // 改变页码
      this.pager.currentPage = currentPage;
      this.getLogs();
    },
    onSizeChange(pageSize) {
      // 改变数量
      this.pager.pageSize = pageSize;
      this.onSearch();
    },
    onSelectChange(selected) {
      // table全选、取消全选
      const multipleType = this.multipleSelect.multipleType;
      this.multipleSelect.selected = selected;
      if (!(selected.length == this.logs.length && multipleType == 2)) {
        this.multipleSelect.multipleType = selected.length == this.logs.length ? 1 : 0;
      }
    },
    onCommand(type) {
      // 选择本页、选择全部
      const multipleType = this.multipleSelect.multipleType;
      if (multipleType == 0 || multipleType == type) {
        this.$refs.multipleTable.toggleAllSelection();
      }
      this.multipleSelect.multipleType = this.multipleSelect.multipleType == type ? 0 : type;
    },
    onMultipleCancel() {
      // 批量不处理
      const selected = this.multipleSelect.selected || [];
      if (selected.length == 0) {
        this.$message.error('请先选择数据');
        return;
      }
      this.delCouponLog(selected.map(el => el.couponErLogId));
    },
    onCancel(logData) {
      // 单条不处理
      this.delCouponLog([logData.couponErLogId]);
    },
    delCouponLog(ids) {
      // 不处理接口
      delCouponLog({ couponErLogIds: ids.join(',') }).then(res => {
        const { errorCode, message } = res || {};
        if (errorCode != 0) {
          this.$message.error(message);
          return;
        }
        this.$message.success('已经取消处理');
        this.multipleSelect.multipleType = 0;
        this.getLogs();
      });
    },
    onReasyn(logData) {
      // 单条重新同步
      this.reAsyn(logData);
    },
    reAsyn(logData) {
      // 重新同步接口，分为重新推送卡券和重新核销卡券两种情况
      const { pid, couponTemplateId, memberId, couponCode } = logData;
      // "sendType":1, //1 为推送卡券,2 核销卡券
      if (logData.sendType == 1) {
        // cardTemplateStr	是	字符串数组	发送优惠券列表信息 其中的string元素为 微盟pid_cardTemplateId拼接成
        // memberId	是	string	会员ID
        // couponCode	否	string	非必填 ，不填时，微盟卡券自动生成券号
        sendCouponReset({ memberId, couponCode, cardTemplateStr: `${pid}_${couponTemplateId}` }).then(res => callback.call(this, res));
      } else if (logData.sendType == 2) {
        // memberId	是	string	会员ID
        // couponCode	是	string	微盟卡券券号
        consumeCoupon({ memberId, couponCode }).then(res => callback.call(this, res));
      }
      function callback(respData) {
        const { errorCode } = respData;
        if (errorCode != 0) {
          // 诸侯、测试说这里提示文案写死
          this.$message.error('卡券重新同步失败，失败原因已更新');
          return;
        }
        this.$message.success('重新同步成功，请稍后刷新页面查看同步结果');
        this.multipleSelect.multipleType = 0;
        this.getLogs();
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.dm-wrap {
  /deep/ .el-table-column--selection .cell {
    padding-left: 10px;
  }
}
</style>
