<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 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 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 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="库存消耗方式" prop="stockType">
        <el-checkbox-group 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" @click="submitForm">{{ isAdd ? '确认新建' : '保存' }}</el-button>
        <el-button @click="$router.go(-1)">返回</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 v-for="(item, idx) in couponList" :key="idx" class="mb10">
            卡券id：<el-input v-model="item.couponId" style="width:200px" class="mr10" />
            库存值：<el-input v-model="item.stock" style="width:100px" />
            <el-button type="text" @click="addCard(item)">保存</el-button>
            <el-button type="text" @click="delCard(item)">删除</el-button>
          </div>
          <el-button type="primary" @click="couponList.push({ couponId:'', stock: 0 })">添加卡券</el-button>
        </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 { formatDateTimeByType } from '@/utils/index.js';
import fetch from '@/api/card-package.js';
const { savePackages, getPackageDetail, addPackageItem, deletePackage } = 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: [],
      couponPackageId: '',
      cardIds: '', // 卡券ids,多个id用逗号隔开
      ruleForm: {
        name: '',
        remarkName: '',
        beginDate: '',
        endDate: '',
        packageStock: undefined,
        stockUseType: '', // 库存使用类型（0:占用,1:动态 , 2占用+动态）
      },
      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({ couponId, stock }) {
      const params = {
        couponPackageId: this.couponPackageId,
        couponId,
        stock
      };
      this.cardLoading = true;
      addPackageItem(params).then(res=> {
        this.cardLoading = false;
        this.refreshCouponList();
      }).catch(() => {
        this.cardLoading = false;
      });
    },
    delCard({ couponId, stock, packageItemId }) {
      const params = {
        couponPackageId: this.couponPackageId,
        couponId,
        stock,
        packageItemId
      };
      this.cardLoading = false;
      deletePackage(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];
        });
        this.dateTime = [ info.beginDate, info.endDate ];
        this.couponList = res.result.couponList || [];
      }).finally(() => {
        this.loading = false;
      });
    },
    submitForm() {
      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');
          const type = this.isAdd ? 'save' : 'edit';
          this.loading = true;
          savePackages(params, { type }).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;
          });
        }
      });
    },
  },
  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;
    }
  }
};
</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>