<template>
  <div class="p20" v-loading="loading">
    <div class="clearfix flex-center pb20">
      <span class="gray01 fz16 mr20">卡券包筛选</span>
      <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-input prefix-icon="el-icon-search" placeholder="请输入卡券名称/备注名" class="w300 mrAuto" v-model="listParams.search" clearable @change="refresh" />
      <dm-perm-button :disabled="$itemPerm($itemCode.gicAddPackage)" type="primary" @click="$router.push('/card-package/add')">新建卡券包</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>
    <el-table tooltip-effect="dark" :data="tableList" style="width:100%">
      <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.couponPackageId" open-delay="200" placement="bottom">
              <span>{{ scope.row.name }}</span>
            </el-tooltip>
          </p>
          <p>{{ scope.row.remarkName }}</p>
          <p class="fz12 gray03">更新时间：<span v-html="formatDateTimeByType(scope.row.updateTime)"></span></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">
          {{ scope.row.useCouponSize }}/{{ scope.row.totalCouponSize }}
          <el-tooltip content="存在已过期或已删除的卡券" placement="top" open-delay="200" v-if="scope.row.totalCouponSize > scope.row.useCouponSize">
            <i class="el-icon-warning ml5"></i>
          </el-tooltip>
        </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">
          <p>可占库存：{{ scope.row.remainedStock || 0 }}
            <el-button @click="preAdjustStock(scope.row)" class="hover-btn" icon="el-icon-edit-outline ml5" 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 placement="top" open-delay="200">
            <div slot="content">使用中：在福利组件中展示；<br/>已过期：在福利组件中不展示；</div>
            <span class="tooltip-icon">卡券包状态</span>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <template v-if="scope.row.totalCouponSize < 2">
            <span class="state-point state-point-warning">未生效</span>
          </template>
          <template v-else>
            <span class="state-point state-point-loading-scale" 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>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="210px" fixed="right">
        <template slot-scope="scope">
          <dm-perm-button type="text" @click="$router.push(`/card-package/edit?id=${scope.row.couponPackageId}`)">编辑</dm-perm-button>
          <dm-perm-button type="text" @click="$router.push(`/card-package/edit?id=${scope.row.couponPackageId}`)">发放记录</dm-perm-button>
          <el-popover popper-class="option-dropdown" trigger="hover">
            <ul>
              <li v-if="scope.row._status == 2">
                <dm-perm-button @click="$router.push(`/card-package/edit?id=${scope.row.couponPackageId}`)" type="text">库存记录</dm-perm-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 type="text" slot="reference" class="ml20">更多<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="adjust.stock" :total-count="adjust.remainedStock" @handleSubmit="adjustStockBack" /><!-- 调整库存 -->
  </div>
</template>

<script>
import sortBtn from '@/components/sort/btn.vue';
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, optPackageStock } = api;
export default {
  name: 'CardPackageList',
  components: {
    adjustStock,
    sortBtn
  },
  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,
      },
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券包', breadPath: '/card-package/list' }, { breadName: '卡券包列表' } ]);
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    formatDateTimeByType,
    changeSort() {
      this.sortType1 = this.sortType1 === '' ? 'desc' : this.sortType1 === 'desc'  ? 'asc' : '';
      this.listParams.sortOrder = this.sortType1;
      this.refresh();
    },
    // 删除
    del(couponPackageIds) {
      this.loading = true;
      deletePackage({ couponPackageId: 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));
      });
    },
    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;
    },
    // 请求修改库存
    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;
      optPackageStock(params).then(res => {
        this.$tips({ message: '调整库存成功', type: 'success' });
        this.$refs.adjust.close();
        this.getTableList();
      }).catch(() => {
        this.$refs.adjust.close();
      });
    },
  },
};
</script>
