<template>
  <div class="p20" v-loading="loading">
    <el-row :gutter="20" class="mb20">
      <el-col :span="24 / cardTypeList.length" v-for="(item, idx) in cardTypeList" :key="idx">
        <div class="ct-block">
          <p>{{ item.name }}</p>
          <div v-html="item.text"></div>
          <el-button type="primary" @click="$router.push(`/gic-card/add?type=${item.type}`)">立即新建</el-button>
        </div>
      </el-col>
    </el-row>
    <div class="clearfix flex-center pb20">
      <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 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>
      <!-- ui没要这个字段 -->
      <el-select v-model="listParams.couponStatus" class="w160" 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>
      <el-button class="ml10" type="text" @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}<i :class="`${isOpen ? 'el-icon-arrow-up' : 'el-icon-arrow-down'} el-icon--right ml5`"></i></el-button>
      <el-select class="more-select mr10 mlAuto" @change="mutiOption" placeholder="批量操作">
        <el-option :value="0">批量禁用</el-option>
        <el-option :value="1">批量删除</el-option>
      </el-select>
    </div>
    <div v-show="isOpen" class="filter-block">
      <div class="mb20">
        <label class="mr8">福利成本：</label>
        <dm-input-amount :controls="false" class="prefix-amount w140" @change="refresh" v-model="listParams.costPriceBegin" controls-position="right" :precision="2" :max="listParams.costPriceBegin" :min="0" placeholder="请输入" />
        <span>至</span>
        <dm-input-amount :controls="false" class="prefix-amount w140" @change="refresh" v-model="listParams.costPriceEnd" controls-position="right" :precision="2" :min="1" :max="100000" placeholder="请输入" />
        <label class="mr8 ml40 w100 inline-block">更新时间：</label>
        <el-select v-model="listParams.sortOrder" @change="refresh" placeholder="默认筛选">
          <el-option label="由近及远" value="desc"></el-option>
          <el-option label="由远及近" value="asc"></el-option>
        </el-select>
      </div>
      <div>
        <label class="mr8">可占库存：</label>
        <el-input-number class="w140" @change="refresh" v-model="listParams.remainedStockBegin" controls-position="right" :precision="0" :min="1" :max="10000" placeholder="请输入" />
        <span>至</span>
        <el-input-number class="w140 mrAuto" @change="refresh" v-model="listParams.remainedStockEnd" controls-position="right" :precision="0" :min="listParams.remainedStockEnd" :max="100000" placeholder="请输入" />
        <label class="mr8 ml40 w100 inline-block">更新时间范围：</label>
        <el-date-picker v-model="dateTime" type="daterange" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="refresh" />
      </div>
    </div>
    <el-table tooltip-effect="dark" :data="tableList" style="width:100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left"> </el-table-column>
      <el-table-column label="卡券信息" min-width="280">
        <template slot-scope="scope">
        <div class="card">
          <img :src="scope.row.imgUrl" draggable="false" />
          <p class="name ellipsis-100" :title="scope.row.cardName">{{ scope.row.cardName }}</p>
          <p :title="scope.row.remarkName" class="fz12 ellipsis-100" style="line-height:17px;color:#909399">
            <el-popover placement="top-start" width="300" trigger="hover" open-delay="200" :offset="-8">
              <div class="gray01 fz14">
                <p style="margin-bottom:5px;">福利ID：{{ scope.row.couponId }}</p>
                <p>更新时间：{{ formatDateTimeByType(scope.row.updateTime, 'yyyy-MM-dd HH:mm:ss') }}</p>
              </div>
              <i class="el-icon-question cursor fz14" slot="reference"></i>
            </el-popover>
            {{ scope.row.remarkName }}
          </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="130">
        <template slot-scope="scope">{{ scope.row.cardType == 0 || scope.row.cardType == 2 ? scope.row.costPrice.toFixed(2) : '--' }}</template>
      </el-table-column>
      <el-table-column label="可占用库存" min-width="180">
        <template slot="header">
          <el-tooltip placement="top" open-delay="200"><div slot="content">可占库存：福利可以被直接使用和被应用占用的数量；<br/>已占用：福利已经被应用通过”固定库存“方式占用的数量；<br/>总库存：福利实际未产生履约单，还可以被出库的数量；</div>
            <span class="tooltip-icon">可占用库存</span>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <el-popover placement="top-end" width="200" trigger="hover" open-delay="200" :offset="-8">
            <div class="gray01 fz14">
              <p style="margin-bottom:5px;">已占用：{{ scope.row.occupyStock || 0 }}</p>
              <p>总库存：{{ scope.row.totalStock || 0 }}</p>
            </div>
            <i class="el-icon-question cursor fz14" slot="reference" style="position:relative;color:#909399"></i>
          </el-popover>
          {{ scope.row.remainedStock || 0 }}
          <el-tooltip :open-delay="100" content="调整库存">
            <el-button v-if="[1, 2].includes(scope.row._status) && scope.row.customCodeFlag == 0" @click="preAdjustStock(scope.row) && scope.row.customCodeFlag == 0" class="hover-btn" icon="el-icon-edit-outline ml5" type="text"></el-button>
          </el-tooltip>
          <el-tooltip :open-delay="100" content="批量导入券码">
            <el-button v-if="[1, 2].includes(scope.row._status) && scope.row.customCodeFlag == 2" class="hover-btn ml5" @click="uploadCode(scope.row)" icon="iconfont-market4 icon-shangchuan" type="text"></el-button>
          </el-tooltip>
        </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="180px" fixed="right">
        <template slot-scope="scope">
          <mk-button :option="{ perm: $itemPerm($itemCode.gicCardFormCopy), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }" type="text" @click="handler(6, scope.row)">复制</mk-button>
          <mk-button :option="{ perm: $itemPerm($itemCode.gicCardGroupBtn), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }" type="text" @click="handler(8, scope.row)" class="mr20">领取记录</mk-button>
          <el-popover popper-class="option-dropdown" trigger="hover">
            <ul>
              <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="[1,2].includes(scope.row._status) && scope.row.edit == 1" :class="{ disabled: $itemPerm($itemCode.gicCardFormEdit) || scope.row.deleteFlag }">
                <mk-button type="text" @click="handler(3, scope.row)" :option="{ perm: $itemPerm($itemCode.gicCardFormEdit), deleteFlag: scope.row.deleteFlag, deleteRemark: scope.row.remark }">编辑</mk-button>
              </li>
              <li v-else :class="{ disabled: $itemPerm($itemCode.gicCardFormInfo) }">
                <dm-perm-button @click="handler(5, scope.row)" :disabled="$itemPerm($itemCode.gicCardFormInfo)" type="text">详情</dm-perm-button>
              </li>
              <li v-if="scope.row._status == 2 && scope.row.edit == 1">
                <dm-perm-button @click="handler(10, scope.row)" type="text">禁用</dm-perm-button>
              </li>
              <li :class="{ disabled: $itemPerm($itemCode.gicCardFormDel) }" v-if="scope.row.edit == 1">
                <dm-perm-button @click="handler(4, scope.row)" :disabld="$itemPerm($itemCode.gicCardFormDel)" type="text">删除</dm-perm-button>
              </li>
            </ul>
            <el-button type="text" slot="reference"><i class="el-icon-more"></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" title="调整可占用库存" :show.sync="adjustStock" :total-count="currentCard.remainedStock" @handleSubmit="adjustStockBack" /><!-- 调整库存 -->
    <import-code :coupon-id="codeDialog.couponId" ref="importCode" :visible.sync="codeDialog.visible" @success="getTableList" @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 adjustStock from '@/components/libs/adjust-stock';
import api from '@/api/gic-card';
const { cardList, deleteCard, updateCardStock, disableCard } = api;

export default {
  name: 'CardList',
  components: {
    adjustStock,
    importCode
  },
  mixins: [ page, formate, mixBeforeRouteLeave, getMainHeight ],
  data() {
    return {
      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,
        couponId: this.$route.query.couponId, // 卡id
      },
      multipleSelection: [], // 多选的数据
      cardType: Object.keys(cardType).map(v => { return cardType[v]; }),
      total: 0,
      tableList: [],
      adjustStock: false,
      codeDialog: { // 导入券码dialog
        visible: false,
        couponId: '',
      },
      isOpen: false,
      currentCard: {},
      cardTypeList: [
        { name: '抵金券', text: '例：满100元减20元<br/>便于合理控制活动成本', type: 0 },
        { name: '折扣券', text: '例：满100元打9折<br/>提高店铺销量和客单价', type: 1 },
        { name: '兑换券', text: '用于兑换指定商品<br/>吸引顾客消费', type: 2 },
      ]
    };
  },
  created() {
    this.$emit('updateBread', [ { breadName: '卡券列表' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      this.getTableList();
    }
  },
  methods: {
    formatDateTimeByType,
    changeSort() {
      this.sortType1 = this.sortType1 === '' ? 'desc' : this.sortType1 === 'desc'  ? 'asc' : '';
      this.listParams.sortOrder = this.sortType1;
      this.refresh();
    },
    effectiveDateFormate({ cardEffectiveMode, startDate, expireDate, effectTimeMode, expireTimeCount, effectTimeCount }) {
      if (cardEffectiveMode === 0) {
        return `<p>${formatDateTimeByType(startDate, 'yyyy-MM-dd')} ~ </p><p>${ formatDateTimeByType(expireDate, 'yyyy-MM-dd') }</p>`;
      }
      if (cardEffectiveMode === 1) {
        const unit = effectTimeMode ? '月' : '天';
        return `<p>领取后${effectTimeCount == 1 ? '当' : effectTimeCount == 2 ? '次' : effectTimeCount}${unit}生效，</p><p>有效天数${expireTimeCount}${unit}</p>`;
      }
      return '--';
    },
    // val： 1投放 2报表  3编辑  4删除 5详情 6复制 7同步 8领取详情 9库存记录 10禁用
    // 已无效的功能  1投放  2报表  7同步
    handler(val, { couponId, edit }) {
      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/member-get?id=' + couponId + '&edit=' + edit);
          break;
        case 9: // 库存记录
          this.$router.push('/gic-card/stock-list?id=' + couponId);
          break;
        case 10: // 禁用
          this.stopData(couponId);
          break;
      }
    },
    renderStatus({ _status }) {
      let _cl = '';
      // 1未生效、2使用中、3已过期、4已禁用
      switch (_status) {
        case 1:
          _cl = 'state-point-loading-scale'; // 未生效 转换成使用中
          _status = 2;
          break;
        case 2:
          _cl = 'state-point-loading-scale'; // 使用中
          break;
        case 3:
          _cl = 'state-point-default';
          break;
        case 4:
          _cl = 'state-point-error'; // 已禁用已过期
          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.remarkName = params.search;
      // if(params.searchType == 3) params.subTitle = 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 => {
          return mappingCardStatus(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;
      console.log(params);
      params.couponId = this.currentCard.couponId;
      updateCardStock(params).then(res => {
        this.$refs.adjust.close();
        this.getTableList();
      }).catch(() => {
        this.$refs.adjust.close();
      });
    },
    // 批量操作
    mutiOption(val) {
      if(this.multipleSelection.length == 0) {
        return this.$message.warning('请勾选卡券');
      }
      const ids = this.multipleSelection.map(v => v.couponId).join(',');
      if(val == 0) { // 批量禁用
        this.stopData(ids, true);
      }
      if(val == 1) { // 批量删除
        this.delData(ids, true);
      }
    },
    // 批量禁用
    stopData(ids, isMuti = false) {
      const warnTitle = isMuti ? '确认批量禁用选中的卡券吗？' : '确认禁用卡券?';
      const warnTxt = '禁用卡券将在福利组件不展示，并且该卡券参加的活动将全部失效';
      showConfirm(`<div>${warnTitle}</div><div>${warnTxt}</div>`, () => {
        this.loading = true;
        disableCard({ couponIds: ids }).then(res => {
          this.$tips({ type: 'success', message: '禁用成功!' });
          this.loading = false;
          this.getTableList();
        }).finally(() => {
          this.loading = false;
        });
      }, undefined, undefined, { confirmButtonText: isMuti ? '批量禁用' : '禁用' });
    },
    // 批量删除
    delData(ids, isMuti = false) {
      const warnTitle = isMuti ? '确认批量删除选中的卡券吗？' : '确认删除卡券?';
      const warnTxt = '删除后卡券不可找回，已添加被删除卡券的活动将会失效';
      showConfirm(`<div>${warnTitle}</div><div>${warnTxt}</div>`, () => {
        this.loading = true;
        deleteCard({ couponIds: ids }).then(res => {
          this.$tips({ type: 'success', message: '删除成功!' });
          this.loading = false;
          this.getTableList();
        }).finally(() => {
          this.loading = false;
        });
      }, undefined, undefined, { confirmButtonText: isMuti ? '批量删除' : '删除' });
    },
    // 上传券码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;
  }
}
.card {
  padding-left: 70px;
  min-height: 60px;
  position: relative;
  img {
    position: absolute;
    left: 0;
    top: 0;
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }
  .name {
    color: $gray01;
    padding-top: 8px;
    margin-bottom: 7px;
    line-height: 22px;
  }
}
.ct-block {
  background: rgba(47, 84, 235, 0.07);
  text-align: center;
  padding: 20px 0 16px;
  p {
    font-size: 16px;
    color: $gray01;
    line-height: 22px;
  }
  div{
    margin: 10px 0 15px;
    color: $gray02;
    line-height: 17px;
  }
}
.ml40 {
  margin-left: 40px;
}
.filter-block {
  color: $gray01;
  background: $gray-disable;
  padding: 20px;
  margin-bottom: 20px;
  span {
    margin-left: 10px;
    margin-right: 10px;
    line-height: 20px;
  }
}
</style>
