<template>
  <div class="p20" v-loading="loading">
    <div class="clearfix flex-center pb20">
      <el-input prefix-icon="el-icon-search" placeholder="请输入卡券名称/备注名" class="w300 mr10" v-model="listParams.search" clearable @change="refresh" />
      <el-select v-model="listParams.useStatus" class="w160 mr10" 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 type="text" @click="isOpen = !isOpen">{{ isOpen ? '收起' : '展开' }}<i :class="`${isOpen ? 'el-icon-arrow-up' : 'el-icon-arrow-down'} el-icon--right ml5`"></i></el-button>
      <dm-perm-button :disabled="$itemPerm($itemCode.gicAddPackage)" type="primary" class="mlAuto" @click="$router.push('/card-package/add')">新建卡券包</dm-perm-button>
      <el-button class="specter" :disabled="!multipleSelection.length" type="danger" @click="mutiDel">批量删除</el-button>
    </div>
    <div v-show="isOpen" class="filter-block">
      <div class="mb20">
        <label class="mr8">福利成本：</label>
        <!-- listParams.costPriceBegin -->
        <el-input-number :controls="false" class="prefix-amount w140" @change="refresh" v-model="listParams.costPriceBegin" controls-position="right" :precision="2" :max="listParams.costPriceEnd" :min="0" placeholder="请输入" />
        <span>至</span>
        <el-input-number :controls="false" class="prefix-amount w140" @change="refresh" v-model="listParams.costPriceEnd" controls-position="right" :precision="2" :min="listParams.costPriceBegin" :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.remainedStockBegin" :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"></el-table-column>
      <el-table-column label="卡券包信息" min-width="200" fixed="left" show-overflow-tooltip>
        <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.name }}</p>
            <p :title="scope.row.remarkName" class="fz12 gray-lighter ellipsis-100" style="line-height:17px;">
              <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.couponPackageId }}</p>
                  <p>更新时间：{{ formatDateTimeByType(scope.row.updateTime, 'yyyy-MM-dd HH:mm:ss') }}</p>
                </div>
                <i class="el-icon-question cursor fz12 gray-lighter" 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">
          <p>{{ formatDateTimeByType(scope.row.beginDate, 'yyyy-MM-dd') }}~</p>
          <p>{{ formatDateTimeByType(scope.row.endDate, 'yyyy-MM-dd') }}</p>
        </template>
      </el-table-column>
      <el-table-column label="卡券数量" min-width="120">
        <template slot-scope="scope">
          <span :class="{ 'danger-color': (scope.row.totalCouponSize > scope.row.useCouponSize || scope.row.totalCouponSize == 0) }">{{scope.row.useCouponSize==scope.row.totalCouponSize?scope.row.totalCouponSize:(scope.row.useCouponSize+'/'+scope.row.totalCouponSize)}}</span>
          <el-popover placement="top-start" width="200" trigger="hover" open-delay="200" :content="scope.row.totalCouponSize > scope.row.useCouponSize?'存在已过期或已删除的卡券':'卡券包中未添加卡券'" v-if="(scope.row.totalCouponSize > scope.row.useCouponSize || scope.row.totalCouponSize == 0)">
            <i class="el-icon-question ml5 cursor gray-lighter" slot="reference"></i>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="卡券成本(元)" min-width="120">
        <template slot-scope="scope">{{ scope.row.costPrice != null && scope.row.costPrice != '' && scope.row.costPrice != -1 ? scope.row.costPrice : '--' }}</template>
      </el-table-column>
      <el-table-column label="卡券包库存" min-width="180">
        <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 fz12 gray-lighter" slot="reference" style="position:relative;"></i>
          </el-popover>
          {{ scope.row.remainedStock || 0 }}
          <el-button @click="preAdjustStock(scope.row)" class="hover-btn" icon="el-icon-edit-outline ml5" type="text" v-if="scope.row.useStatus == 1"></el-button>
        </template>
      </el-table-column>
      <el-table-column label="卡券包状态" min-width="120">
        <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">
          <span class="state-point state-point-success" v-if="scope.row.useStatus == 1">已生效</span>
          <span class="state-point state-point-default" v-if="scope.row.useStatus == 2">已过期</span>
          <span class="state-point state-point-default" v-if="scope.row.useStatus == 3">未生效</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="180px" fixed="right">
        <template slot-scope="scope">
          <dm-perm-button type="text" v-if="scope.row.useStatus != 2" @click="$router.push(`/card-package/edit?id=${scope.row.couponPackageId}`)">编辑</dm-perm-button>
          <!-- statusFlag 1正常（生效状态），0卡券张数不正常(失效状态) -->
          <el-button v-if="!(scope.row.useStatus == 2 && scope.row.statusFlag == 0)" type="text" @click="$router.push(`/card-package/send-list?id=${scope.row.couponPackageId}`)">发放记录</el-button>
          <el-popover popper-class="option-dropdown" trigger="hover">
            <ul>
              <li>
                <el-button @click="$router.push(`/card-package/stock-list?id=${scope.row.couponPackageId}`)" type="text">库存记录</el-button>
              </li>
              <li :class="{ disabled: $itemPerm($itemCode.gicDeletePackage) }">
                <dm-perm-button @click="delOne(scope.row)" :disabld="$itemPerm($itemCode.gicDeletePackage)" type="text">删除</dm-perm-button>
              </li>
            </ul>
            <el-button :class="{'ml20': !(scope.row.useStatus == 2 && scope.row.statusFlag == 0)}" 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="调整卡券包库存" width="660px" :show.sync="adjust.stock" :total-count="adjust.remainedStock" @handleSubmit="adjustStockBack">
      <!-- 调整库存 -->
      <p class="mt20 mb15 gray01">卡券明细</p>
      <el-table v-loading="tableCardPackageLoading" :data="tableCardPackage" style="width: 100%">
        <el-table-column prop="cardName" label="卡券名称"></el-table-column>
        <el-table-column prop="date" label="使用有效期">
          <template slot-scope="scope">
            <span v-html="effectiveDateFormate(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="领取限制">
          <template slot-scope="scope">{{ scope.row.getLimit }} 张/人</template>
        </el-table-column>
        <el-table-column prop="date" label="卡券类型">
          <template slot-scope="scope">{{ cardType[scope.row.cardType].label || '--' }}</template>
        </el-table-column>
        <el-table-column prop="remainedStock" label="当前可占库存"></el-table-column>
      </el-table>
    </adjust-stock>
  </div>
</template>

<script>
import { cardType } from '@/config/mapping/gic-card';
import adjustStock from '@/components/libs/adjust-stock';
import { page, formate } from '@/mixins/table.js';
import { showConfirm } from '@/utils/common';
import api from '@/api/card-package.js';
import { formatDateTimeByType } from '@/utils/index.js';
const { pageCouponPackage, deletePackage, updatePackageStock, getPackageDetail } = api;
export default {
  name: 'CardPackageList',
  components: {
    adjustStock
  },
  mixins: [ page, formate ],
  data() {
    return {
      loading: false,
      dateTime: [ , ],
      multipleSelection: [], // 多选的数据
      listParams: {
        useStatus: '',
        search: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20,
        sortOrder: 'desc', // asc:升序; desc:倒序
        // orderType: '', // createTime  updateTime
        costPriceBegin: undefined,
        costPriceEnd: undefined,
        remainedStockBegin: undefined,
        remainedStockEnd: undefined,
      },
      tableList: [],
      total: 0,
      // 导入库存
      adjust: {
        remainedStock: 0,
        couponPackageId: '',
        stock: false,
      },
      tableCardPackageLoading: false,
      tableCardPackage: [], // 调整卡券包库存展示的slot table list
      isOpen: false,
      cardType,
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券包' }, { breadName: '卡券包列表' } ]);
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    formatDateTimeByType,
    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 '--';
    },
    changeSort() {
      this.sortType1 = this.sortType1 === '' ? 'desc' : this.sortType1 === 'desc'  ? 'asc' : '';
      this.listParams.sortOrder = this.sortType1;
      this.refresh();
    },
    // 删除
    del(couponPackageIds) {
      this.loading = true;
      deletePackage({ couponPackageIds: couponPackageIds.join(',')  }).then(res => {
        this.loading = false;
        this.getTableList();
      }).finally(() => {
        this.loading = false;
      });
    },
    // 删除卡券
    delOne({ couponPackageId }) {
      showConfirm('<div>删除卡券包后不可找回，确认删除该卡券包？</div>', () => {
        this.del([ couponPackageId ]);
      });
    },
    // 批量删除
    mutiDel() {
      showConfirm('<div>删除卡券包后不可找回，确认批量删除？</div>', () => {
        this.del(this.multipleSelection.map(v => v.couponPackageId));
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getTableList() {
      if(this.loading) {
        return;
      }
      this.loading = true;
      this.formatterTimeFunc('beginTime', 'endTime', 'yyyy-MM-dd', 'dateTime');
      let params = { ...this.listParams, memberCardId: this.currentAreaId };
      pageCouponPackage(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;
      });
    },
    // *************子组件相关方法***************
    // 编辑库存 前置
    preAdjustStock({ couponPackageId, remainedStock }) {
      this.adjust.stock = true;
      this.adjust.remainedStock = remainedStock;
      this.adjust.couponPackageId = couponPackageId;
      this.tableCardPackageLoading = true;
      getPackageDetail({ couponPackageId: couponPackageId }).then(res => {
        this.tableCardPackage = res.result.couponList || [];
        console.log(this.tableCardPackage);
        this.tableCardPackageLoading = false;
      }).catch(() => {
        this.tableCardPackageLoading = false;
      });
    },
    // 请求修改库存
    adjustStockBack(params) {
      if(params.optType == 1 && (this.adjust.remainedStock + params.count >  1000000)) {
        // 增加后目标值不能大于100w
        this.$tips({ message: '库存不能大于100w', type: 'warning' });
        return;
      }
      this.$refs.adjust.loading = true;
      params.couponPackageId = this.adjust.couponPackageId;
      updatePackageStock(params).then(res => {
        this.$tips({ message: '调整库存成功', type: 'success' });
        this.$refs.adjust.close();
        this.getTableList();
      }).catch(() => {
        this.$refs.adjust.close();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.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;
  }
}
.card {
  padding-left: 70px;
  min-height: 70px;
  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;
  }
}
</style>
