<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <el-select class="dm-select mr10 w140" clearable v-model="listParams.status" placeholder="所有状态" @change="refresh">
        <el-option v-for="(v, i) in sendStatus" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-input class="vertical-middle w300 mrAuto" v-model="listParams.search" clearable placeholder="请输入创建人/计划名称" @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <dm-perm-button type="primary" @click="$router.push('/gic-card/group-send/add')" :disabled="$itemPerm($itemCode.gicCardGroupSendForm)">新建卡券投放</dm-perm-button>
    </div>
    <el-table tooltip-effect="dark" :data="tableList" style="width:100%" :max-height="mainHeight(52)">
      <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-if="v.famount">{{ scope.row[v.prop] | amountFormat(null, 0, null) }}</span>
          <span v-else>{{ scope.row[v.prop] }}</span>
          <time-count v-if="v.timmer && scope.row.gicAuditingStatus === 1 && scope.row.status === 0" class="primary-color fz12" :default-val="scope.row.putOnTime" :auto-start="true" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="180px" fixed="right">
        <template slot-scope="scope">
          <dm-perm-button :disabled="$itemPerm($itemCode.gicCardGroupSendInfo)" type="text" @click="$router.push(`/gic-card/group-send/info?id=${scope.row.couponPlanId}`)">详情</dm-perm-button>
          <dm-perm-button :disabled="$itemPerm($itemCode.gicCardGroupSendInfoLog)" type="text" @click="$router.push(`/gic-card/group-send/info-log?id=${scope.row.couponPlanId}`)">记录</dm-perm-button>
          <!-- gic审核投放 status待投放 可禁用 -->
          <dm-perm-button :disabled="$itemPerm($itemCode.gicCardStopGroupSend)" type="text" v-if="scope.row.gicAuditingStatus === 1 && scope.row.status === 0" @click="stopOne(scope.row)">禁用</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>
  </div>
</template>

<script>
import { page, getMainHeight } from '@/mixins/table.js';
import { listTime } from '@/utils/index.js';
import { showConfirm } from '@/utils/common.js';
import { sendStatus, cardType } from '@/config/mapping/gic-card';
import timeCount from '@/components/libs/time-count';
import api from '@/api/gic-card.js';
const { groupSendList, stopGroupSend } = api;
export default {
  name: 'GroupSendList',
  components: {
    timeCount // eslint-disable-line
  },
  mixins: [ page, getMainHeight ],
  data() {
    return {
      loading: false,
      dateTime: [ , ],
      listParams: {
        search: '',
        status: '',
        currentPage: 1,
        pageSize: 20
      },
      sendStatus: Object.keys(sendStatus).map(v => { return sendStatus[v]; }), // , { label: '待审核', value: -3 }, { label: '审核失败', value: -2 } -3: 待审核, -2 审核失败,
      tableList: [],
      total: 0,
      tableHeader: [
        {
          label: '计划名称',
          align: 'left',
          minWidth: '120',
          fixed: 'left',
          tooltip: true,
          formatter: function(row) {
            return `<span p-key="couponPlanId" title="${row.couponPlanId}">${ row.name }</span>`;
          }
        },
        {
          label: '投放时间',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            return row.putOnTime ? listTime(row.putOnTime) : '--';
          }
        },
        {
          label: '投放卡券',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            const _cardType = cardType[row.cardType] || {};
            return `<p class="fz14 ellipsis" p-key="couponId" title="${row.couponId}">${row.cardName || '--'}</p><p class="fz12">${_cardType.label || '--'}</p>`;
          }
        },
        { label: '投放人数', prop: 'issuingQuantity', align: 'left', minWidth: '100', famount: true },
        { label: '领取数', prop: 'getedQuantity', align: 'left', minWidth: '100', famount: true },
        {
          label: '领取率',
          minWidth: '100',
          align: 'left',
          formatter: function(row) {
            return ((row.getedQuantity * 100) / (row.issuingQuantity === 0 ? 1 : row.issuingQuantity)).toFixed(2) + '%';
          }
        },
        { label: '使用数量', prop: 'usageQuantity', align: 'left', minWidth: '100' },
        {
          label: '核销率',
          minWidth: '100',
          align: 'left',
          formatter: function(row) {
            return ((row.usageQuantity * 100) / (row.getedQuantity === 0 ? 1 : row.getedQuantity)).toFixed(2) + '%';
          }
        },
        { label: '销售额', prop: 'saleAmount', align: 'left', minWidth: '100', famount: true },
        { label: '创建人', prop: 'creatorName', align: 'left', minWidth: '100' },
        { label: '数据对话', prop: 'mktActivityName', align: 'left', minWidth: '140' },
        {
          label: '状态',
          minWidth: '140',
          align: 'left',
          timmer: true,
          formatter: function(row) {
            // gic审核状态: (-1：审核失败，0：未审核(审核中)，1：审核通过)
            // 状态: （-1失效，0：待发送，1：已完成，2：发送失败,3:无可用模板;4.发送中）
            const { gicAuditingStatus, status } = row;
            if (gicAuditingStatus === -1) {
              return '<span class="state-point state-point-error">审核失败</span>';
            } else if (gicAuditingStatus === 0) {
              return '<span class="state-point state-point-warnning">审核中</span>';
            } else {
              const _status = sendStatus[status];
              if(_status) {
                return `<span class="state-point ${_status.cl}">${_status.label}</span>`;
              } else {
                return '<span class="state-point state-point-default">未知状态</span>';
              }
            }
          }
        }
      ]
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券投放', breadPath: '/gic-card/group-send/list' } ]);
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    stopOne({ couponPlanId }) {
      showConfirm('<div>确认禁用？</div><div>禁用后该计划会直接失败</div>', () => {
        this.loading = true;
        stopGroupSend({ couponPlanId }).then(res => {
          this.loading = false;
          this.getTableList();
        }).finally(() => {
          this.loading = false;
        });
      }, undefined, undefined, {
        dangerouslyUseHTMLString: true
      });
    },
    getTableList() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      let params = { ...this.listParams, ...{ memberCardId: this.currentAreaId } };
      groupSendList(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;
      });
    }
  },
};
</script>
