<template>
  <div class="p20" v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" label-width="140px" class="pt10 pb10" :rules="rules">
      <el-form-item>
        <el-tooltip open-delay="200" slot="label" content="请在应用左上角切换会员卡" placement="top">
          <span class="tooltip-icon">适用会员卡</span>
        </el-tooltip>
        {{ $store.state.currentAreaName || '--' }}
      </el-form-item>
      <el-form-item prop="name" label="卡券包名称">
        <dm-input :disabled="canEdit" v-model="ruleForm.name" class="w400" placeholder="请输入卡券包名称" :byte-type="1" :maxlength="9"></dm-input>
      </el-form-item>
      <el-form-item prop="remarkName" label="备注名">
        <dm-input :disabled="canEdit" v-model="ruleForm.remarkName" class="w400" placeholder="请输入备注名" :byte-type="1" :maxlength="10"></dm-input>
      </el-form-item>
      <el-form-item prop="effectiveMode" label="有效期限">
        <el-date-picker :disabled="canEdit" class="w400" v-model="dateTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
      <el-form-item label="卡券包库存" prop="packageStock">
        <el-input-number class="w400" v-model="ruleForm.packageStock" controls-position="right" :min="1" :max="1000000"></el-input-number>
      </el-form-item>
      <el-form-item label="库存消耗方式" class="is-required" prop="stockType">
        <el-checkbox-group :disabled="canEdit" v-model="stockType">
          <!-- （0:占用,1:动态 , 2占用+动态） -->
          <el-checkbox :label="0">固定库存</el-checkbox>
          <el-checkbox :label="1">实时库存</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="isAdd" @click="addForm">确认新建</el-button>
        <el-button type="primary" :disabled="ruleForm.packageStock == info.packageStock" v-else @click="editForm">保存</el-button>
      </el-form-item>
      <el-form-item v-if="!isAdd" class="is-required">
        <el-tooltip content="若添加的卡券为固定有效期，仅允许添加和有效期限时间重合的卡券" placement="bottom" slot="label" open-delay="200">
          <span class="tooltip-icon">添加卡券</span>
        </el-tooltip>
        <div v-loading="cardLoading">
          <div class="mb10">
            卡券id：<el-input v-model="couponForm.couponId" style="width:200px" class="mr10" />
            库存值：<el-input v-model="couponForm.stock" style="width:100px" />
            <el-button type="text" @click="addCard" class="ml5">保存</el-button>
          </div>
        </div>
        <div class="imitation-table" v-if="couponList.length" style="width:100%;" v-loading="cardLoading">
          <el-row class="thead">
            <el-col :span="5">卡券信息</el-col>
            <el-col :span="5">有效期</el-col>
            <el-col :span="4">卡券包内剩余库存</el-col>
            <el-col :span="4">福利可占库存</el-col>
            <el-col :span="3">福利状态</el-col>
            <el-col :span="3">操作</el-col>
          </el-row>
          <div class="tbody">
            <div class="td" v-for="(item, idx) in couponList" :key="idx">
              <el-row>
                <el-col :span="5">
                  <el-tag class="mr5">{{ cardType[item.cardType].label }}</el-tag>
                  <router-link target="_blank" :to="{path:'/gic-card/info',query:{ id: item.couponId }}">{{ item.cardName }}</router-link>
                </el-col>
                <el-col :span="5"><span v-html="effectiveDateFormate(item)"></span></el-col>
                <el-col :span="4">{{ item.activityRemainedStock }}</el-col>
                <el-col :span="4">{{ item.remainedStock }}</el-col>
                <el-col :span="3">
                  <!-- 1:已生效,2:已删除,3:已过期 -->
                  <span v-if="item.welfareStatus == 1" class="state-point state-point-success">已生效</span>
                  <span v-else class="state-point state-point-success">{{ item.welfareStatus == 2 ? '已删除' : '已过期' }}</span>
                </el-col>
                <el-col :span="3">
                  <dm-delete @confirm="delCard(item)" tips="删除后已占用库存将被释放，确认删除？">
                    <el-button type="text">删除</el-button>
                  </dm-delete>
                </el-col>
              </el-row>
              <div v-if="item.remainedStock < ruleForm.packageStock" class="gray03"><i class="el-icon-warning mr5 danger-color"></i>卡券包库存大于福利库存，请调整福利占用库存</div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="hidden">
      <dm-card-select :before-submit="beforeSubmit" ref="cardSelect" read-only :member-card-id="currentAreaId" @selectData="(val) => { selectData(val, idx) }" :min-stock="ruleForm.packageStock" fix-member-card :unuse-list="couponList" />
    </div>
  </div>
</template>

<script>
import { getTimesByReq } from '@/utils/common.js';
import { cardType } from '@/config/mapping/gic-card';
import { formatDateTimeByType } from '@/utils/index.js';
import fetch from '@/api/card-package.js';
const { addPackages, editPackages, getPackageDetail, addPackageItem, delPackageItem } = fetch;


export default {
  name: 'MergeForm',
  data() {
    const validateSendType = (rule, value, callback) => {
      const { dateTime, packageStatus } = this;
      if ((dateTime && !dateTime[0]) || !dateTime) {
        callback(new Error('请选择有效期限'));
      }
      if (packageStatus == 1 && dateTime[0] < getTimesByReq('', 1)) {
        callback(new Error('有效期限不能小于当前时间'));
      }
      if (new Date(dateTime[1]).getTime() - new Date(dateTime[0]).getTime() > 1000 * 60 * 60 * 24 * 365) {
        callback(new Error('时间跨度不能大于一年'));
      }
      callback();
    };
    const validateCardIds = (rule, value, callback) => {
      if (!this.couponList.length) {
        callback(new Error(rule.message));
      }
      callback();
    };
    return {
      loading: false,
      cardLoading: false,
      stockType: [],
      cardType,
      couponPackageId: '',
      cardIds: '', // 卡券ids,多个id用逗号隔开
      ruleForm: {
        name: '',
        remarkName: '',
        beginDate: '',
        endDate: '',
        packageStock: undefined,
        stockUseType: '', // 库存使用类型（0:占用,1:动态 , 2占用+动态）
      },
      couponForm: {
        couponId: '',
        stock: 0
      },
      info: {}, // 备份详情
      couponList: [],
      dateTime: [],
      rules: {
        name: [ { required: true, message: '请输入卡券包名称', trigger: 'change' } ],
        remarkName: [ { required: true, message: '请输入备注名', trigger: 'change' } ],
        packageStock: [ { required: true, message: '请输入卡券包库存', trigger: 'change' } ],
        effectiveMode: [ { required: true, validator: validateSendType, trigger: 'change' } ],
        cardIds: [ { required: true, validator: validateCardIds, message: '请选择卡券', trigger: 'change' } ]
      },
      pickerOptions: {
        disabledDate(now) {
          return now.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      isInfo: this.$route.meta.type === 'info',
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券包', breadPath: '/card-package/list' }, { breadName: this.isAdd ? '新建卡券包' : '编辑卡券包', breadPath: '' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      if(!this.isAdd) {
        this.couponPackageId = this.$route.query.id;
        this.getInfo();
      }
    }
  },
  methods: {
    // 添加卡券
    addCard() {
      const params = {
        couponPackageId: this.couponPackageId,
        couponId: this.couponForm.couponId,
        stock: this.couponForm.stock
      };
      this.cardLoading = true;
      addPackageItem(params).then(res=> {
        this.cardLoading = false;
        this.refreshCouponList();
      }).catch(() => {
        this.cardLoading = false;
      });
    },
    // 删除卡券
    delCard({ couponId }) {
      const params = {
        couponPackageId: this.couponPackageId,
        couponId
      };
      this.cardLoading = false;
      delPackageItem(params).then(res => {
        this.cardLoading = false;
        this.refreshCouponList();
      }).catch(() => {
        this.cardLoading = false;
      });
    },
    refreshCouponList() {
      this.cardLoading = true;
      getPackageDetail({ couponPackageId: this.couponPackageId }).then(res => {
        this.cardLoading = false;
        this.couponList = res.result.couponList || [];
      }).catch(() => {
        this.cardLoading = false;
      });
    },
    getInfo() {
      this.loading = true;
      getPackageDetail({ couponPackageId: this.couponPackageId }).then(res => {
        this.loading = false;
        const info = res.result.couponDetail || {};
        this.info = info;
        Object.keys(this.ruleForm).map(v => {
          this.ruleForm[v] = info[v];
        });
        // 库存使用类型（0:占用,1:动态 , 2占用+动态）
        this.stockType = info.stockUseType == 2 ? [ 0, 1 ] : [ info.stockUseType ] ;
        this.dateTime = [ info.beginDate, info.endDate ];
        this.couponList = res.result.couponList || [];
      }).finally(() => {
        this.loading = false;
      });
    },
    addForm() {
      if(this.loading) {
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        } else {
          // this.ruleForm.couponIds = this.couponList.join(','); // 卡券ids用，分割
          let params = { ...this.ruleForm, memberCardId: this.currentAreaId };
          params.stockUseType = this.stockType.length == 2 ? 2 : this.stockType[0];
          params.beginDate = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd');
          params.endDate = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd');
          this.loading = true;
          addPackages(params).then(res => {
            this.loading = false;
            this.$tips({ message: `${ this.isAdd ? '新建' : '编辑' }成功`, type: 'success' });
            if(!this.isAdd) {
              this.$router.push('/card-package/list');
            } else {
              this.$router.push(`/card-package/edit?id=${res.result}`);
            }
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
    // 编辑卡券包
    editForm() {
      let flag = false;
      this.couponList.forEach(v => {
        if(v.remainedStock < this.ruleForm.packageStock && v.remainedStock) {
          flag = true;
        }
      });
      if(flag) {
        this.$tips({ message: '卡券包库存大于福利库存，请调整福利占用库存', type: 'error' });
        return;
      }
      const params = {
        couponPackageId: this.couponPackageId,
        count: Math.abs(this.info.packageStock - this.ruleForm.packageStock),
        optType: this.ruleForm.packageStock > this.info.packageStock ? 1 : 2, // 1增加，2减少
      };
      this.loading = true;
      editPackages(params).then(res => {
        this.getInfo();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    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 '--';
    },
  },
  computed: {
    /**
     * 1.过期卡券包无法修改
     * 2.有效期未开始,全都可以改,除了开始时间不能早于当前时间
     * 3.有效期使用中, 只能更改名称
     */
    // 返回值： 1：未开始   2：使用中   3已过期
    packageStatus() {
      if(this.isAdd) {
        return 1;
      }
      const { beginDate, endDate } = this.info;
      const d = getTimesByReq('', 1);
      if(new Date(beginDate) > d) {
        return 1;
      }
      return new Date(endDate) < d ? 3 : 2;
    },
    canEdit() {
      return !this.isAdd;
    }
  },
};
</script>

<style lang="scss" scoped>
.el-icon-delete {
  display: inline-block;
  font-size: 17px;
  padding: 9px;
  margin-right: 10px;
  color: #909399;
  border: 1px solid #e4e7ed;
  border-radius: 50%;
  vertical-align: middle;
  cursor: pointer;
  position: relative;
  top: -60px;
  &:hover {
    background:rgba(254,240,240,1);
    border:1px solid rgba(251,196,196,1);
    color: #F5222D;
  }
}
</style>