<template>
  <div class="p20" v-loading="loading">
    <div class="clearfix flex-center pb20">
      <span class="gray01 fz16 mr20">卡券筛选</span>
      <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 placeholder="请输入关键字搜索" class="w400 mr10" v-model="listParams.search" clearable @change="refresh">
        <el-select v-model="listParams.searchType" slot="prepend" style="width:120px;" placeholder="请选择" @change="refresh">
          <el-option label="卡券名称" :value="1"></el-option>
          <el-option label="备注名" :value="2"></el-option>
          <el-option label="副标题" :value="3"></el-option>
          <el-option label="demo券号" :value="4"></el-option>
        </el-select>
      </el-input>
      <el-select v-model="listParams.couponStatus" class="w160 mrAuto" placeholder="全部状态" clearable @change="refresh">
        <el-option label="使用中" :value="1"></el-option>
        <el-option label="已过期" :value="2"></el-option>
        <el-option label="已禁用" :value="3"></el-option>
      </el-select>
      <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 style="height:20px;width:calc(100% + 40px);position:relative;left:-20px;" class="bg-color mb20"></div>
    <div class="clearfix flex-center mb20">
      <label class="pr4 cursor" @click="changeSort">更新时间</label>
      <sort-btn class="mr10" :sort-type="sortType1" />
      <el-date-picker class="mr10" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh" />
      <label class="ml5 mr8">成本</label>
      <el-input-number class="prefix-amount hide-right w100" @change="refresh" v-model="listParams.costPriceBegin" controls-position="right" :precision="2" :min="listParams.costPriceBegin" :max="10000" placeholder="请输入" />
      <label class="ml5 mr5">-</label>
      <el-input-number class="prefix-amount hide-right w100" @change="refresh" v-model="listParams.costPriceEnd" controls-position="right" :precision="2" :min="1" :max="100000" placeholder="请输入" />
      <label class="ml15 mr8">可占用库存</label>
      <el-input-number class="hide-right w100" @change="refresh" v-model="listParams.remainedStockBegin" controls-position="right" :precision="0" :min="1" :max="10000" placeholder="请输入" />
      <label class="ml5 mr5">-</label>
      <el-input-number class="hide-right w100 mrAuto" @change="refresh" v-model="listParams.remainedStockEnd" controls-position="right" :precision="0" :min="listParams.remainedStockBegin" :max="100000" placeholder="请输入" />
      <dm-perm-button type="danger" class="specter" v-show="active === 'list'" :disabled="!multipleSelection.length" @click="mutiDel">批量删除</dm-perm-button>
    </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" @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 -->
    <!-- TODO: minheight -->
    <el-table v-show="active === 'list'" tooltip-effect="dark" :data="tableList" style="width:100%" :max-height="mainHeight(52 + 52)" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="卡券信息" min-width="200" fixed="left">
        <template slot-scope="scope">
        <div class="card">
          <p>
            <el-tooltip effect="dark" :content="scope.row.couponId" open-delay="200" placement="bottom">
              <span>{{ scope.row.cardName }}</span>
            </el-tooltip>
          </p>
          <p>{{ scope.row.subTitle }}</p>
          <p class="fz12 gray03">更新时间：2020-12-12 12:12:12</p>
        </div>
        </template>
      </el-table-column>
      <el-table-column label="使用有效期" min-width="140" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-html="effectiveDateFormate(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column label="领券限制" min-width="120">
        <template slot-scope="scope">{{ scope.row.getLimit }} 张 </template>
      </el-table-column>
      <el-table-column prop="name" label="卡券成本" min-width="120">
        <template slot-scope="scope">{{ scope.row.cardType == 1 || scope.row.cardType == 2 ? `￥${scope.row.costPrice}` : '--' }}</template>
      </el-table-column>
      <el-table-column label="卡券库存" min-width="180">
        <template slot-scope="scope">
          <p>可占库存：{{ scope.row.remainedStock || 0 }}
            <el-button v-if="[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="[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>
          </p>
          <p>已占用：{{ scope.row.occupyStock || 0 }}</p>
          <p>总库存：{{ scope.row.totalStock || 0 }}</p>
        </template>
      </el-table-column>
      <el-table-column label="卡券状态" min-width="120">
        <template slot="header">
          <el-tooltip content="tooltip" placement="top" open-delay="200">
            <div slot="content">使用中：在福利组件中展示；<br/>已过期：在福利组件中不展示，活动中卡券失效；<br/>已禁用：在福利组件中不展示，活动中卡券失效；</div>
            <span class="tooltip-icon">卡券状态</span>
          </el-tooltip>
        </template>
        <span slot-scope="scope" v-html="renderStatus(scope.row)"></span>
      </el-table-column>
      <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="[1,2].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 }">
                <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 :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.gicCardFormDel) }">
                <dm-perm-button @click="handler(4, scope.row)" :disabld="$itemPerm($itemCode.gicCardFormDel)" type="text">删除</dm-perm-button>
              </li>
              <li v-if="scope.row._status == 2">
                <dm-perm-button @click="handler(10, scope.row)" type="text">禁用</dm-perm-button>
              </li>
              <li v-if="[1,2].includes(scope.row._status)">
                <dm-perm-button @click="handler(9, scope.row)" type="text">库存记录</dm-perm-button>
              </li>
              <li v-if="[2, 3, 4].includes(scope.row._status)" :class="{ disabled: $itemPerm($itemCode.gicCardGroupBtn) || scope.row.deleteFlag }">
                <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 sortBtn from '@/components/sort/btn.vue';
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,
    sortBtn
  },
  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: [ , ],
      sortType1: '',
      listParams: {
        couponStatus: '',
        searchType: 1,
        search: '',
        cardType: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20,
        sortOrder: 'desc', // asc:升序; desc:倒序
        // orderType: '', // createTime  updateTime
        costPriceBegin: undefined,
        costPriceEnd: undefined,
        remainedStockBegin: undefined,
        remainedStockEnd: undefined,
      },
      multipleSelection: [], // 多选的数据
      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: {},
    };
  },
  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: {
    changeSort() {
      this.sortType1 = this.sortType1 === '' ? 'desc' : this.sortType1 === 'desc'  ? 'asc' : '';
      this.listParams.sortOrder = this.sortType1;
      this.refresh();
    },
    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领取详情 9库存记录 10禁用
    // 已无效的功能  1投放  2报表  7同步
    handler(val, { couponId }) {
      switch (val) {
        case 1:
          this.$router.push('/gic-card/group-send/add?couponId=' + 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 8: // 领取详情
          this.$router.push('/gic-card/log/member-get?id=' + couponId);
          break;
        case 9: // 库存记录
          this.$router.push('/gic-card/stock-list?id=' + couponId);
          break;
        case 10: // 禁用
          this.stopData(couponId);
          break;
      }
    },
    renderStatus({ _status }) {
      let _cl = '';
      switch (_status) {
        case 2:
          _cl = 'state-point-loading-scale'; // 使用中
          break;
        case 1:
          _cl = 'state-point-warning'; // 未生效
          break;
        case 3:
        case 4:
          _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.multipleSelection = [];
      this.loading = true;
      this.formatterTimeFunc('beginTime', 'endTime');
      let params = { ...this.listParams, memberCardId: this.currentAreaId };
      params.sortOrder = params.sortOrder || 'desc';
      if(params.searchType == 1) params.cardName = params.search;
      if(params.searchType == 2) params.subTitle = params.search;
      if(params.searchType == 3) params.remarkName = params.search;
      if(params.searchType == 4) params.erpDemoCode = params.search;
      delete params.search;
      delete params.searchType;
      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;
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // *************子组件相关方法***************
    // 编辑库存 前置
    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();
      });
    },
    // 禁用卡券
    stopData(val) {
      showConfirm('<div>禁用后卡券失效，确认禁止？</div>', () => {
        // this.deleteCard(val);
      });
    },
    // 删除卡券
    delData(val) {
      showConfirm('<div>删除后卡券不可找回，确认删除该卡券？</div>', () => {
        this.deleteCard([ val ]);
      });
    },
    // 批量删除
    mutiDel() {
      showConfirm('<div>已添加被删除卡券的活动将会失效，确认删除？</div>', () => {
        this.deleteCard(this.multipleSelection.map(v => v.couponId));
      });
    },
    // 删除卡券
    deleteCard(couponIds) {
      this.loading = true;
      deleteCard({ couponIds: couponIds.join(',') }).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>