<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <el-select v-model="listParams.timeType" clearable class="mr10" placeholder="请选择有效期类型" @change="changeTimeType">
        <el-option label="长期有效" :value="1"></el-option>
        <el-option label="部分时间段" :value="2"></el-option>
      </el-select>
      <el-date-picker v-if="listParams.timeType !== 1" class="w300 mr10" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh"></el-date-picker>
      <el-input class="vertical-middle w250 mrAuto" v-model="listParams.searchParam" clearable placeholder="请输入计划名称/创建人" @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-button type="primary" class="w85" @click="$router.push('/gic-card/shelf/add')">新建计划</el-button>
    </div>
    <el-table tooltip-effect="dark" :data="tableList" :max-height="mainHeight(52)" style="width:100%">
      <template>
        <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="160px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="$router.push(`/gic-card/shelf/edit?id=${scope.row.couponShelfId}`)">编辑</el-button>
            <el-popover popper-class="option-dropdown" trigger="hover">
              <ul>
                <!-- <li @click="viewCoupon(scope.row.couponShelfId)"><span>所用卡券</span></li> -->
                <!-- area_typeint(1) NULL1会员卡 2服务号 3小程序 -->
                <li @click="$router.push(`/gic-card/shelf/receive-list?appCode=coupon-shelf&couponShelfId=${scope.row.couponShelfId}&title=${scope.row.title}`)"><span>领取记录</span></li>
                <li @click="delOne(scope.row.couponShelfId)"><span>删除</span></li>
              </ul>
              <el-button class="ml16" type="text" slot="reference">更多<i class="ml5 el-icon-arrow-down"></i></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </template>
    </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>
    <el-dialog title="所用卡券" :visible.sync="dialogVisible" width="700px">
      <el-table :data="gridData" v-loading="gridLoading">
        <el-table-column property="cardName" label="卡券名称" min-width="250"></el-table-column>
        <el-table-column property="couponStock" label="卡券库存" width="200"></el-table-column>
        <el-table-column property="remainedStock" label="卡券领取量" width="150">
          <template slot-scope="scope">{{ scope.row.couponStock - scope.row.remainedStock }}</template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { page, formate, getMainHeight } from '@/mixins/table.js';
import { formatDateTimeByType } from '@/utils/index.js';
import api from '@/api/gic-card.js';
import { showConfirm } from '@/utils/common.js';
// import { sendType, } from '@/config/mapping/gic-card';
const { getShelfList, delShelf, getShelfCoupon } = api;
export default {
  name: 'ShelfList',
  mixins: [ page, formate, getMainHeight ],
  data() {
    return {
      loading: false,
      dateTime: [ , ],
      listParams: {
        timeType: '',
        searchParam: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      },
      total: 0,
      tableList: [],
      tableHeader: [
        {
          label: '计划名称',
          align: 'left',
          minWidth: '120',
          fixed: 'left',
          tooltip: true,
          formatter: function(row) {
            return `<span p-key="couponShelfId" title="${row.couponShelfId}">${ row.title }</span>`;
          }
        },
        {
          label: '计划时间',
          minWidth: '150',
          align: 'left',
          formatter: function(row) {
            return row.timeType == 1 ? '长期有效' : `
              <p class="cell-time">${ formatDateTimeByType(row.startTime, 'yyyy-MM-dd HH-mm-ss') } ~</p>
              <p class="cell-time">${ formatDateTimeByType(row.endTime, 'yyyy-MM-dd HH-mm-ss') }</p>
            `;
          }
        },
        { label: '创建人', prop: 'creatorName', align: 'left', minWidth: '100' },
        { label: '卡券数量', prop: 'couponNum', align: 'left', minWidth: '100' },
        {
          label: '计划状态',
          align: 'left',
          minWidth: '120',
          formatter: function(row) {
            let statusBtn;
            if(row.timeType !== 1 && new Date() < new Date(row.startTime)) {
              statusBtn = '<span class="state-point state-point-warning">未生效</span>';
            }
            if(row.timeType == 1 || new Date() > new Date(row.startTime) && new Date() < new Date(row.endTime)) {
              statusBtn = '<span class="state-point state-point-loading-scale">进行中</span>';
            }
            if(row.timeType !== 1 && new Date() > new Date(row.endTime)) {
              statusBtn = '<span class="state-point state-point-default">已失效</span>';
            }
            return statusBtn;
          }
        }
      ],
      dialogVisible: false,
      gridLoading: false,
      gridData: []
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券展架', breadPath: '/gic-card/shelf/list' } ]);
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    changeTimeType() {
      this.dateTime = [];
      this.refresh();
    },
    // 查看所用卡券
    viewCoupon(shelfId) {
      this.dialogVisible = true;
      this.gridLoading = true;
      getShelfCoupon({ shelfId }).then(res => {
        this.gridLoading = false;
        this.gridData = res.result;
      }).finally(() => {
        this.gridLoading = false;
      });
    },
    // 删除
    delOne(shelfId) {
      showConfirm('<div>确认删除该展架？</div>', () => {
        this.loading = true;
        delShelf({ shelfId }).then(res => {
          this.loading = false;
          this.$tips({ message: '删除成功', type: 'success' });
          this.getTableList();
        }).finally(() => {
          this.loading = false;
        });
      });
    },
    getTableList() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      this.formatterTimeFunc('startTime', 'endTime', 'yyyy-MM-dd', 'dateTime');
      let params = { ...this.listParams, memberCardId: this.currentAreaId };
      getShelfList(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>
