<template>
  <div class="p20" v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" label-width="140px" class="pt10 pb10" :rules="rules">
      <el-form-item prop="name" label="卡券包名称">
        <dm-input v-model="ruleForm.name" :disabled="packageStatus == 3" class="w400" placeholder="请输入卡券包名称" :byte-type="1" :maxlength="12"></dm-input>
      </el-form-item>
      <!-- <el-form-item label="数据对话">
        <activity-select :actId.sync="ruleForm.mktActivityId" width="400"></activity-select>
      </el-form-item> -->
      <el-form-item prop="effectiveMode" label="有效时间">
        <el-radio-group v-model="ruleForm.effectiveMode" :disabled="packageStatus != 1">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">选择时间段</el-radio>
        </el-radio-group>
        <br />
        <el-date-picker v-if="ruleForm.effectiveMode" :default-time="['00:00:00', '23:59:59']" :disabled="packageStatus != 1" class="w400 mt10" 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" :disabled="stockReady || packageStatus != 1" v-model="ruleForm.packageStock" controls-position="right" :min="1" :max="1000000"></el-input-number>
        <el-button type="text" v-if="packageStatus == 1" @click="handleStockChange" class="ml10">{{ stockReady ? '修改' : '保存' }}</el-button>
      </el-form-item>
      <el-form-item label="选择卡券" prop="cardIds" v-if="stockReady">
        <div style="max-height:700px;overflow-y: auto;width:500px;">
          <div v-for="(item, idx) in couponList" :key="idx">
            <div class="w400 inline-block" style="min-height:177px;">
              <dm-card-select v-if="item" :coupon-id="item" :read-only="packageStatus != 1" class="card-select" style="width:400px;display:inline-block;margin-bottom:10px;" :min-stock="ruleForm.packageStock" :member-card-id="currentAreaId" fix-member-card :unuse-list="couponList" />
            </div>
            <i class="el-icon-delete ml10" @click="couponList.splice(idx, 1);$refs.ruleForm.validateField('cardIds')" v-if="item && packageStatus == 1"></i>
          </div>
        </div>
        <el-button class="dashed w400" icon="el-icon-plus" @click="addCouponList" v-if="couponList.length < 10 && packageStatus == 1">添加卡券</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="packageStatus != 3" @click="submitForm">{{ isAdd ? '确认新建' : '保存' }}</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </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, easyUnique } from '@/utils/index.js';
import commonApi from '@/api/common.js';
import fetch from '@/api/gic-card.js';
const { getRelationId } = commonApi;
const { savePackages, getPackageDetail } = fetch;


export default {
  name: 'MergeForm',
  data() {
    const validateSendType = (rule, value, callback) => {
      if (this.ruleForm.effectiveMode) {
        if ((this.dateTime && !this.dateTime[0]) || !this.dateTime) {
          callback(new Error('请选择有效时间'));
        }
        if (this.packageStatus == 1 && this.dateTime[0] < getTimesByReq('', 1)) {
          callback(new Error('有效时间不能小于当前时间'));
        }
      }
      callback();
    };
    const validateCardIds = (rule, value, callback) => {
      if (!this.couponList.length) {
        callback(new Error(rule.message));
      }
      callback();
    };
    return {
      loading: false,
      ruleForm: {
        couponPackageId: '',
        cardIds: '', // 卡券ids,多个id用逗号隔开
        name: '',
        effectiveMode: 0,
        packageStock: undefined,
      },
      info: {}, // 备份详情
      couponList: [],
      dateTime: [],
      stockReady: false, // 库存是否确定
      rules: {
        name: [ { 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'
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券' }, { breadName: '卡券包', breadPath: '/gic-card/merge/list' }, { breadName: this.isAdd ? '新建卡券包' : '编辑卡券包', breadPath: '' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      if(this.isAdd) {
        this.getRelationId();
      }
      if(!this.isAdd) {
        this.getInfo();
      }
    }
  },
  methods: {
    // 获取主键
    getRelationId() {
      getRelationId().then(res => {
        this.ruleForm.couponPackageId = res.result || '';
      });
    },
    // 库存改变时 清空所有卡券
    handleStockChange() {
      if(!this.stockReady && !this.ruleForm.packageStock) {
        this.$tips({ message: '请保存卡券库存', type: 'error' });
        return;
      }
      this.stockReady = !this.stockReady;
      this.couponList = [];
    },
    getInfo() {
      this.loading = true;
      getPackageDetail({ couponPackageId: this.$route.query.id }).then(res => {
        this.loading = false;
        const info = res.result || {};
        this.info = info;
        Object.keys(this.ruleForm).map(v => {
          this.ruleForm[v] = info[v];
        });
        if(info.effectiveMode) {
          this.dateTime = [ info.beginDate, info.endDate ];
        }
        this.couponList = info.couponIds.split(',');
        this.stockReady = true;
      }).finally(() => {
        this.loading = false;
      });
    },
    submitForm() {
      if(this.loading) {
        return;
      }
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          PublicMethods.jumpToFormError(); // eslint-disable-line
          return;
        } else {
          if(!this.stockReady) {
            this.$tips({ message: '请保存卡券库存', type: 'error' });
            return;
          }
          if(!this.couponList.filter(v => { return v !== ''; }).length) {
            this.$tips({ message: '至少选择一张卡券', type: 'error' });
            return;
          }
          if(easyUnique(this.couponList).length !== this.couponList.length) {
            this.$tips({ message: '卡券不能重复', type: 'error' });
            return;
          }
          this.ruleForm.couponIds = this.couponList.join(','); // 卡券ids用，分割
          let params = { ...this.ruleForm, memberCardId: this.currentAreaId };
          if (this.ruleForm.effectiveMode) {
            params.beginDate = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd-HH-mm-ss');
            params.endDate = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd-HH-mm-ss');
          }
          const type = this.isAdd ? 'save' : 'edit';
          this.loading = true;
          savePackages(params, { type }).then(res => {
            this.loading = false;
            this.$tips({ message: `${ this.isAdd ? '新建' : '编辑' }成功`, type: 'success' });
            this.$router.push('/gic-card/merge/list');
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
    // *****卡券选择器****
    addCouponList() {
      this.$refs.cardSelect.handleShowDialog();
    },
    beforeSubmit(id) {
      if(this.couponList.includes(id)) {
        this.$tips({ message: '该卡券已存在', type: 'error' });
        return false;
      }
      return true;
    },
    selectData(data, idx, flag = false) {
      this.couponList.push(data.couponId);
      this.$refs.ruleForm.validateField('cardIds');
    },
  },
  computed: {
    /**
     * 1.过期卡券包无法修改
     * 2.有效期未开始,全都可以改,除了开始时间不能早于当前时间
     * 3.有效期使用中, 只能更改名称
     */
    // 返回值： 1：未开始   2：使用中   3已过期
    packageStatus() {
      if(this.isAdd) {
        return 1;
      }
      const { effectiveMode, beginDate, endDate } = this.info;
      if(effectiveMode == 0) {
        // 不限
        return 2;
      } else {
        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>