<template>
  <div class="p20" v-loading="loading">
    <div class="clearfix flex-center mb20">
      <span class="gray01 fz16 mrAuto">卡券（共{{ total }}张）</span>
      <ul class="toggle-btn">
        <li @click="active = 'card'" :class="{ active: active === 'card' }"><i class="iconfont-market4 icon-kapian"></i></li>
        <li @click="active = 'list'" :class="{ active: active === 'list' }"><i class="iconfont-market4 icon-liebiao"></i></li>
      </ul>
      <dm-perm-button type="primary" @click="$router.push('/gic-card/add')" :disabled="$itemPerm($itemCode.gicCardFormAdd)">新建卡券</dm-perm-button>
    </div>
    <div class="clearfix flex-center mb20">
      <el-date-picker class="mr10" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh" />
      <el-select class="dm-select mr10 w160" clearable v-model="listParams.cardType" placeholder="所有卡券类型" @change="refresh">
        <el-option v-for="(v, i) in cardType" :key="i" :label="v.label" :value="v.value"></el-option>
      </el-select>
      <el-input class="vertical-middle w300 mr10" v-model="listParams.search" clearable placeholder="卡券名称/备注名" @change="refresh"><i slot="prefix" class="el-input__icon el-icon-search"></i></el-input>
      <el-checkbox size="medium" :true-label="1" :false-label="0" label="仅展示有效卡券" border v-model="listParams.showFlag" @change="refresh" />
    </div>
    <!-- card -->
    <div v-show="active === 'card'" class="card-content clearfix" :style="`max-height:${mainHeight(72 + 47)}px;overflow-y: auto;`">
      <card-item @adjust-stock="preAdjustStock" @upload-code="uploadCode" :item="v" v-for="(v, i) in tableList" :key="i" @delete-card="delData" @handler="handler"></card-item>
      <div class="el-table__empty-block" v-if="!tableList.length">
        <div class="empty-table">
          <span class="el-table__empty-text">暂无数据</span>
        </div>
      </div>
    </div>
    <!-- list -->
    <el-table v-show="active === 'list'" tooltip-effect="dark" :data="tableList" style="width:100%" :max-height="mainHeight(52 + 52)">
      <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-if="v.famount">{{ scope.row[v.prop] | amountFormat(null, 0, null) }}</span>
            <span v-else>{{ scope.row[v.prop] || '--' }}</span>
            <el-button v-if="v.kc && [11, 12].includes(scope.row._status) && scope.row.customCodeFlag === 0" @click="preAdjustStock(scope.row)" class="hover-btn" icon="el-icon-edit-outline ml5" type="text"></el-button>
            <el-button v-if="v.kc && [11, 12].includes(scope.row._status) && scope.row.customCodeFlag == 2" class="hover-btn" @click="uploadCode(scope.row)" icon="iconfont-market4 icon-shangchuan" type="text"></el-button>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="left" width="150px" fixed="right">
        <template slot-scope="scope">
          <!-- 编辑状态：排除已结束和已禁用、审核中 -->
          <!-- 失效状态的卡券操作只保留查看详情和删除操作 -->
          <mk-button class="mr16" :option="{ perm: $itemPerm($itemCode.gicCardFormEdit), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }" type="text" v-if="[2, 4, 6, 11, 12].includes(scope.row._status)" @click="handler(3, scope.row, $itemPerm($itemCode.gicCardFormEdit))">编辑</mk-button>
          <el-popover popper-class="option-dropdown" trigger="hover">
            <ul>
              <li :class="{ disabled: $itemPerm($itemCode.gicCardFormCopy) || scope.row.deleteFlag }" v-if="[2, 4, 6, 7, 8, 11, 12, 13].includes(scope.row._status)">
                <mk-button type="text" @click="handler(6, scope.row)" :option="{ perm: $itemPerm($itemCode.gicCardFormCopy), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }">复制</mk-button>
              </li>
              <!-- <li v-if="[12, 13].includes(scope.row._status)"><mk-button type="text" @click="handler(2, scope.row)" :disabled="">报表</mk-button></li> -->
              <li :class="{ disabled: $itemPerm($itemCode.gicCardFormInfo) }">
                <dm-perm-button @click="handler(5, scope.row)" :disabled="$itemPerm($itemCode.gicCardFormInfo)" type="text">详情</dm-perm-button>
              </li>
              <li :class="{ disabled: $itemPerm($itemCode.gicCardGroupSendForm) || scope.row.deleteFlag }" v-if="[4, 6, 11, 12].includes(scope.row._status) && scope.row.remainedStock > 0">
                <mk-button @click="handler(1, scope.row)" :option="{ perm: $itemPerm($itemCode.gicCardGroupSendForm), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }" type="text">投放</mk-button>
              </li>
              <li :class="{ disabled: $itemPerm($itemCode.gicCardSyncStock) || scope.row.deleteFlag }" v-if="[11, 12].includes(scope.row._status)">
                <mk-button @click="handler(7, scope.row)" :option="{ perm: $itemPerm($itemCode.gicCardSyncStock), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }" type="text">同步</mk-button>
              </li>
              <li :class="{ disabled: $itemPerm($itemCode.gicCardFormDel) }">
                <dm-perm-button @click="handler(4, scope.row)" :disabld="$itemPerm($itemCode.gicCardFormDel)" type="text">删除</dm-perm-button>
              </li>
              <li :class="{ disabled: $itemPerm($itemCode.gicCardGroupBtn) || scope.row.deleteFlag }" v-if="[12, 13].includes(scope.row._status)">
                <mk-button @click="handler(8, scope.row)" :option="{ perm: $itemPerm($itemCode.gicCardGroupBtn), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }" type="text">领取记录</mk-button>
              </li>
            </ul>
            <el-button type="text" slot="reference">更多<i class="ml5 el-icon-arrow-down"></i></el-button>
          </el-popover>
        </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>
    <adjust-stock ref="adjust" :show.sync="adjustStock" :total-count="currentCard.remainedStock" @handleSubmit="adjustStockBack" /><!-- 调整库存 -->
    <sync-stock :visible.sync="syncStock.visible" :coupon-id="syncStock.couponId" :type="1" @syncSuccess="getTableList" /><!-- 同步库存 -->
    <import-code :coupon-id="codeDialog.couponId" ref="importCode" :visible.sync="codeDialog.visible" @close="(len) => { if(len) { getTableList(); } }" /><!-- 导入券码 -->
  </div>
</template>

<script>
import importCode from './module/import-code';
import { page, formate, getMainHeight } from '@/mixins/table.js';
import { cardType, cardStatus, mappingCardStatus } from '@/config/mapping/gic-card';
import { mixBeforeRouteLeave } from '@/mixins/mixRoute';
import { formatDateTimeByType } from '@/utils/index';
import { showConfirm } from '@/utils/common';
import cardItem from './module/card-item';
import adjustStock from '@/components/libs/adjust-stock';
import syncStock from './module/sync-stock';
import api from '@/api/gic-card';
const { cardList, deleteCard, updateCardStock } = api;

export default {
  name: 'CardList',
  components: {
    cardItem,
    adjustStock,
    syncStock,
    importCode
  },
  mixins: [ page, formate, mixBeforeRouteLeave, getMainHeight ],
  data() {
    return {
      active: this.$route.query.active == 'list' ? 'list' : 'card', // card list
      loading: false,
      cacheRoute: [ '/gic-card/add', '/gic-card/edit', '/gic-card/copy' ],
      dateTime: [ , ],
      listParams: {
        search: '',
        cardType: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20,
        showFlag: 0
      },
      cardType: Object.keys(cardType).map(v => { return cardType[v]; }),
      total: 0,
      tableList: [],
      adjustStock: false,
      syncStock: { //  同步dialog
        visible: false,
        couponId: '',
      },
      codeDialog: { // 导入券码dialog
        visible: false,
        couponId: '',
      },
      currentCard: {},
      tableHeader: [
        {
          label: '卡券名称',
          align: 'left',
          minWidth: '120',
          fixed: 'left',
          tooltip: true,
          formatter: function(row) {
            return `<span p-key="couponId" title="${row.couponId}">${ row.cardName }</span>`;
          }
        },
        {
          label: '有效期',
          minWidth: '150',
          align: 'left',
          formatter: (row) => {
            return this.effectiveDateFormate(row);
          }
        },
        { label: '使用说明', prop: 'useExplain', align: 'left', tooltip: true, minWidth: '180' },
        { label: '适用门店', prop: 'adaptStoreExplain', align: 'left', tooltip: true, minWidth: '140' },
        {
          label: '领券限制',
          minWidth: '140',
          tooltip: true,
          align: 'left',
          formatter: function(row) {
            return `每人限制 ${ row.getLimit } 张`;
          }
        },
        { label: '卡券库存', prop: 'remainedStock', align: 'left', minWidth: '130', famount: true, kc: true },
        {
          label: '卡券状态',
          minWidth: '150',
          align: 'left',
          formatter: (row) => {
            return this.renderStatus(row);
          }
        },
        { label: 'demo券号', prop: 'erpDemoCode', align: 'left', minWidth: '140' },
      ]
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券库' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      this.getTableList();
    }
  },
  activated() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券库' } ]);
    this.getTableList();
  },
  // beforeRouteLeave(to, from, next) {
  //   const excludeRoute = ['/gic-card/add', '/gic-card/edit', '/gic-card/copy'];
  //   if (!excludeRoute.includes(to.path)) {
  //     const idx = this.$vnode.parent.componentInstance.keys.indexOf(this.$route.fullPath);
  //     console.log(idx);
  //     const key = this.$vnode.parent.componentInstance.keys[idx];
  //     const cache = this.$vnode.parent.componentInstance.cache;
  //     delete cache[key];
  //   }
  //   next();
  // },
  methods: {
    effectiveDateFormate(item = {}) {
      const { cardEffectiveMode, startDate, expireDate, effectTimeMode, expireTimeCount, effectTimeCount } = item;
      if (cardEffectiveMode === 0) {
        return `<p>${formatDateTimeByType(startDate, 'yyyy-MM-dd')} ~ </p><p>${ formatDateTimeByType(expireDate, 'yyyy-MM-dd') }</p>`;
      }
      if (cardEffectiveMode === 1) {
      // 领取后第{{ info.effectTimeCount }}{{ info.effectTimeMode ? '月' : '天' }} - 第{{ info.expireTimeCount + info.effectTimeCount - 1 }}{{ info.effectTimeMode ? '月' : '天' }}
        const unit = effectTimeMode ? '月' : '天';
        let pre = '';
        switch (effectTimeCount) {
          case 1:
            pre = '当';
            break;
          case 2:
            pre = '次';
            break;
          default:
            pre = effectTimeCount;
            break;
        }
        return `<p>领取后${pre}${unit}生效，</p><p>有效天数${expireTimeCount}${unit}</p>`;
      }
      return '--';
    },
    // val： 1群发 2报表  3编辑  4删除 5详情 6复制 7同步 8领取详情
    handler(val, { couponId, remainedStock, welfareId }) {
      switch (val) {
        case 1:
          this.$router.push('/gic-card/group-send/add?couponId=' + couponId);
          break;
        case 2:
          // this.$tips({ message: '本期不做', type: 'warning' });
          // this.$router.push('/gic-card/analysis/' + couponId);
          break;
        case 3:
          this.$router.push('/gic-card/info-edit?id=' + couponId);
          break;
        case 4:
          this.delData(couponId);
          break;
        case 5:
          this.$router.push('/gic-card/info?id=' + couponId);
          break;
        case 6:
          this.$router.push('/gic-card/copy?copyId=' + couponId);
          break;
        case 7: // 同步
          this.syncStock.visible = true;
          this.syncStock.couponId = couponId;
          break;
        case 8: // 领取详情
          this.$router.push('/gic-card/log/member-get?id=' + couponId);
          break;
      }
    },
    renderStatus(item) {
      const { _status } = item;
      let _cl = '';

      switch (_status) {
        case 1:
        case 3:
        case 5:
        case 9:
        case 10:
          _cl = 'state-point-loading'; // 审核和使用中
          break;
        case 12:
          _cl = 'state-point-loading-scale'; // 使用中
          break;
        case 2:
        case 4:
        case 6:
        case 7:
        case 8:
          _cl = 'state-point-error'; // 审核失败
          break;
        case 11:
          _cl = 'state-point-warning'; // 未生效
          break;
        case 13:
          _cl = 'state-point-default'; // 已过期
          break;
        default:
          _cl = 'state-point-default';
          break;
      }
      return `<span class="state-point ${_cl}">${cardStatus[_status]}</span>`;
    },
    getTableList() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      this.formatterTimeFunc('beginTime', 'endTime');
      let params = { ...this.listParams, memberCardId: this.currentAreaId };
      cardList(params).then(res => {
        this.loading = false;
        const data = res.result;
        this.tableList = data.result.map(v => {
          v._status = mappingCardStatus(v);
          return v;
        }) || [];
        this.total = data.totalCount;
        // 删除至最后一页没数据的情况，页码-1
        if (this.tableList.length === 0 && this.listParams.currentPage !== 1) {
          this.listParams.currentPage -= 1;
          this.getTableList();
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    // *************子组件相关方法***************
    // 编辑库存 前置
    preAdjustStock(val) {
      this.currentCard = val;
      this.adjustStock = true;
    },
    // 请求修改库存
    adjustStockBack(params) {
      this.$refs.adjust.loading = true;
      params.couponId = this.currentCard.couponId;
      updateCardStock(params).then(res => {
        this.$refs.adjust.close();
        this.getTableList();
      }).catch(() => {
        this.$refs.adjust.close();
      });
    },
    // 删除卡券
    delData(val) {
      showConfirm('<div>确认删除该卡券？</div>', () => {
        this.deleteCard(val);
      });
    },
    // 删除卡券
    deleteCard(couponId) {
      this.loading = true;
      deleteCard({ couponId }).then(res => {
        this.$tips({ type: 'success', message: '删除成功!' });
        this.loading = false;
        this.getTableList();
      }).finally(() => {
        this.loading = false;
      });
    },
    // 上传券码dialog
    uploadCode({ couponId }) {
      this.codeDialog.couponId = couponId;
      this.codeDialog.visible = true;
      // 只要关闭弹窗就清除数据
      this.$refs.importCode.fileList = [];
      this.$refs.importCode.file = {};
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-table__row {
  .hover-btn {
    opacity: 0;
    transition: all 0.1s;
  }
  &.hover-row .hover-btn{
    opacity: 1;
  }
}
.toggle-btn {
  background: white;
  overflow: hidden;
  margin-right:10px;
  border:1px solid rgba(196,198,207,1);
  li {
    border-right:1px solid rgba(196,198,207,1);
    text-align: center;
    float: left;
    width:32px;
    height:30px;
    background: white;
    border-radius:0px 1px 1px 0px;
    color: $gray02;
    line-height: 30px;
    cursor: pointer;
    &.active {
      background:rgba(240,245,255,1);
      color: $gray01;
    }
    &:last-child {
      border-right: 0px;
    }
  }
}
</style>