<template>
  <div class="p20" v-loading="loading">
    <div class="pb20 clearfix flex-center">
      <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-date-picker class="w350 mrAuto" v-model="dateTime" type="daterange" range-separator="~" start-placeholder="创建开始日期" end-placeholder="创建结束日期" @change="refresh"></el-date-picker>
      <dm-perm-button :disabled="$itemPerm($itemCode.gicAddPackage)" type="primary" @click="$router.push('/gic-card/merge/add')">新建卡券包</dm-perm-button>
    </div>
    <el-table tooltip-effect="dark" :data="tableList" style="width:100%">
      <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>{{ scope.row[v.prop] || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总库存/剩余库存" align="left" width="180px">
        <template slot-scope="scope">
          {{ scope.row.packageStock }}/{{ scope.row.remainedStock }}
          <dm-perm-button :disabled="$itemPerm($itemCode.gicAdjustStockPack)" type="text" @click="preAdjustStock(scope.row)" class="ml5">调整</dm-perm-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" width="130px" fixed="right">
        <template slot-scope="scope">
          <!-- <dm-perm-button type="text" :disabled="$itemPerm($itemCode.gicSyncStockPack)" @click="showSyncStock(scope.row)">同步</dm-perm-button> -->
          <dm-perm-button type="text" :disabled="$itemPerm($itemCode.gicEditPackage)" @click="$router.push(`/gic-card/merge/edit?id=${scope.row.couponPackageId}`)">编辑</dm-perm-button>
          <dm-delete @confirm="delOne(scope.row)">
            <dm-perm-button type="text" :disabled="$itemPerm($itemCode.gicDeletePackage)">删除</dm-perm-button>
          </dm-delete>
        </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>
    <sync-stock :visible.sync="syncStock.visible" :coupon-package-id="syncStock.couponPackageId" :type="1" @syncSuccess="getTableList" /><!-- 同步库存 -->
    <adjust-stock ref="adjust" :show.sync="adjust.stock" :total-count="adjust.remainedStock" @handleSubmit="adjustStockBack" /><!-- 调整库存 -->
  </div>
</template>

<script>
import adjustStock from '@/components/libs/adjust-stock';
import syncStock from './module/sync-stock-package';
import { page, formate } from '@/mixins/table.js';
import { formatDateTimeByType, listTime } from '@/utils/index.js';
import api from '@/api/gic-card.js';
const { pageCouponPackage, deletePackage, optPackageStock } = api;
export default {
  name: 'MergeList',
  components: {
    adjustStock,
    syncStock
  },
  mixins: [ page, formate ],
  data() {
    return {
      loading: false,
      dateTime: [ , ],
      listParams: {
        search: '',
        beginTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      },
      tableList: [],
      total: 0,
      tableHeader: [
        {
          label: '卡券包名称',
          minWidth: '120',
          align: 'left',
          fixed: 'left',
          formatter: function(row) {
            return `<span p-key="couponPackageId" title="${row.couponPackageId}">${ row.name }</span>`;
          }
        },
        {
          label: '创建时间',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            return listTime(row.createTime);
          }
        },
        {
          label: '有效期',
          minWidth: '120',
          align: 'left',
          formatter: function(row) {
            if (row.effectiveMode) {
              return `<p class="cell-time">${ formatDateTimeByType(row.beginDate, 'yyyy-MM-dd') }</p>
                      <p class="cell-time">${ formatDateTimeByType(row.endDate, 'yyyy-MM-dd') }</p>`;
            } else {
              return '不限';
            }
          }
        },
        { label: '卡券数量', prop: 'couponSize', align: 'left', minWidth: '100' },
      ],
      // 导入库存
      adjust: {
        remainedStock: 0,
        couponPackageId: '',
        stock: false,
      },
      syncStock: { //  同步dialog
        visible: false,
        couponPackageId: '',
      },
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券包' }, { breadName: '卡券包列表', breadPath: '/gic-card/merge/list' } ]);
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    // 删除
    delOne({ couponPackageId }) {
      this.loading = true;
      deletePackage({ couponPackageId }).then(res => {
        this.loading = false;
        this.getTableList();
      }).finally(() => {
        this.loading = false;
      });
    },
    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;
      });
    },
    // *************子组件相关方法***************
    // 同步
    showSyncStock({ couponPackageId }) {
      this.syncStock.visible = true;
      this.syncStock.couponPackageId = couponPackageId;
    },
    // 编辑库存 前置
    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>
