<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="卡券包名称">
         <el-input show-word-limit :disabled="canEdit" v-model="ruleForm.name" class="w400" placeholder="如：双十一优惠券"   :maxlength="9" />
      </el-form-item>
      <el-form-item prop="remarkName" label="备注名">
         <el-input show-word-limit :disabled="canEdit" v-model="ruleForm.remarkName" class="w400" placeholder="仅内部可见"   :maxlength="10" />
      </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 style="width:115px" 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-tooltip open-delay="200" content="通过占用的方式获得固定可用库存，不会被其他应用/活动所消耗" placement="top"><span class="tooltip-icon">固定库存</span></el-tooltip></el-checkbox>
          <el-checkbox :label="1"><el-tooltip open-delay="200" content="不占用库存，使用福利中心“可占库存”，与其他应用使用同个库存" placement="top"><span class="tooltip-icon">实时库存</span></el-tooltip></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="操作人权限" prop="operAuthType" required>
        <!-- <dm-acc-group-select :etype.sync="ruleForm.operAuthType" :group-ids.sync="ruleForm.operAuth" /> -->
        <dm-acc-group-select ref="accg" input-width="250px" :scene-type="sceneType" :relation-id="relationId" :is-echo="isEcho" />
      </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>
        <el-button class="dashed" :disabled="couponList.length >= 10" @click="showSelector = true">添加卡券 {{ couponList.length }}/{{ 10 }}</el-button>
        <div class="imitation-table mt20" 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 }}" :title="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-if="item.welfareStatus == 2" class="state-point state-point-error">已删除</span>
                  <span v-else class="state-point state-point-default">已过期</span>
                </el-col>
                <el-col :span="3">
                  <el-button @click="delCard(item)" type="text">删除</el-button>
                </el-col>
              </el-row>
              <div v-if="item.activityRemainedStock < ruleForm.packageStock" class="gray03"><i class="el-icon-warning mr5 danger-color"></i>卡券包库存大于福利库存，请调整福利占用库存</div>
            </div>
          </div>
        </div>
      </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>
    <div class="hidden">
      <!-- 20210302 产品要求 卡券包中添加卡券只能选择固定库存 -->
      <dm-welfare-selector
      :show-type-select="false"
      :visible.sync="showSelector"
      model="coupon"
      type="coupon"
      :params="params"
      :disable-ids="couponList.map(v => v.couponId)"
      :disable-filters="['memberCardId', 'stockType']"
      stock-type="0"
      @change="saveWelfare"/>
    </div>
  </div>
</template>

<script>
import { showConfirm } from '@/utils/common';
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;
import commomApi from '@/api/common.js';
const { getRelationId } = commomApi;

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();
    };
    // const validateOperAuth = (rule, value, callback) => {
    //   if (this.ruleForm.operAuthType == 2 && !this.ruleForm.operAuth.length) {
    //     callback(new Error('请选择部分分组账号'));
    //     return;
    //   }
    //   callback();
    // };
    return {
      loading: false,
      cardLoading: false,
      stockType: [],
      cardType,
      couponPackageId: '',
      cardIds: '', // 卡券ids,多个id用逗号隔开
      ruleForm: {
        name: '',
        remarkName: '',
        beginDate: '',
        endDate: '',
        packageStock: 0,
        stockUseType: '', // 库存使用类型（0:占用,1:动态 , 2占用+动态）
        operAuthType: 1, // 1所有账号2部分账号3仅创建人
        operAuth: []
      },
      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' } ],
        // operAuthType: [ { required: true, validator: validateOperAuth, trigger: 'change' } ],
      },
      pickerOptions: {
        disabledDate(now) {
          return now.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      showSelector: false, // 是否展示福利选择器
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      isInfo: this.$route.meta.type === 'info',
      relationId: '', // 账号分组relationId
      isEcho: false, // 控制操作人权限是否回显数据
      sceneType: 10, // 场景值，现在测试使用，后期提供确定的
    };
  },
  created() {
    this.$emit('updateBread', [ { breadName: '卡券包列表', breadPath: '/card-package/list' }, { breadName: this.isAdd ? '新建卡券包' : '编辑卡券包', breadPath: '' } ]);
  },
  mounted() {
    if(this.currentAreaId) {
      if(!this.isAdd) {
        this.couponPackageId = this.$route.query.id;
        this.relationId = this.$route.query.id;
        this.isEcho = true;
        this.getInfo();
      }else{
        this.getRelationId();
      }
    }
  },
  methods: {
    getRelationId() {
      getRelationId().then(res => {
        this.couponPackageId = res.result;
        this.relationId = res.result;
      });
    },
    // 添加卡券
    saveWelfare(welfare) {
      const { welfareId, customStock } = welfare;
      if(customStock < this.ruleForm.packageStock) {
        this.$tips({ message: '卡券库存不能小于当前库存', type: 'warning' });
        return;
      }
      const params = {
        couponPackageId: this.couponPackageId,
        couponId: welfareId,
        stock: customStock
      };
      this.cardLoading = true;
      addPackageItem(params).then(res=> {
        this.cardLoading = false;
        this.refreshCouponList();
      }).catch(() => {
        this.cardLoading = false;
      });

    },
    // 删除卡券
    delCard({ couponId }) {
      showConfirm('<div>确认删除该卡券吗？</div><div>删除后已占用库存将被释放</div>', () => {
        const params = {
          couponPackageId: this.couponPackageId,
          couponId
        };
        this.cardLoading = false;
        delPackageItem(params).then(res => {
          this.cardLoading = false;
          this.refreshCouponList();
          let callbackId = this.$route.query.callbackId;
          if(callbackId) {
            let obj = JSON.parse(localStorage.getItem('welfareCreateCallback') || '{}');
            obj[callbackId] = false;
            localStorage.setItem('welfareCreateCallback', JSON.stringify(obj));
            obj[callbackId] = true;
            localStorage.setItem('welfareCreateCallback', JSON.stringify(obj));
          }
        }).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(showTip = false) {
      this.loading = true;
      getPackageDetail({ couponPackageId: this.couponPackageId }).then(res => {
        this.loading = false;
        const info = res.result.couponDetail || {}; // 卡券详情的库存
        this.info = info;
        const exclude = [ 'operAuth' ]; // 不需要赋值的字段
        Object.keys(this.ruleForm).map(v => {
          if (v in info && !exclude.includes(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 || [];
        if(showTip && this.couponList.map(v => v.welfareStatus == 1).length < 2) {
          this.$tips({ message: '卡券包中至少包含2张状态为已生效的卡券', type: 'warning' });
        }
        if (info.operAuthType == 2) {
          this.ruleForm.operAuth = info.operAuth.split(',');
        }
      }).finally(() => {
        this.loading = false;
      });
    },
    addForm() {
      if(this.loading) {
        return;
      }
      if(!this.$refs.accg.validate()) return;
      this.$refs.accg.save();
      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, couponPackageId: this.couponPackageId };
          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');
          if (params.operAuthType == 2) {
            params.operAuth = params.operAuth.join(',');
          }
          this.loading = true;
          addPackages(params).then(res => {
            this.loading = false;
            this.$tips({ message: `${ this.isAdd ? '新建' : '编辑' }成功`, type: 'success' });
            if(this.isAdd) {
              this.$store.commit('updateShowCornerCanUseApp', true);
              let callbackId = this.$route.query.callbackId;
              if(callbackId) {
                let obj = JSON.parse(localStorage.getItem('welfareCreateCallback') || '{}');
                obj[callbackId] = true;
                localStorage.setItem('welfareCreateCallback', JSON.stringify(obj));
              }
            }
            if(!this.isAdd) {
              this.$router.push('/card-package/list');
            } else {
              this.isEcho = true;
              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;
      }
      if(!this.$refs.accg.validate()) return;
      this.$refs.accg.save();
      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(true);
        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: {
    params() {
      return {
        memberCardId: this.currentAreaId,
        effectStartTime: formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd'),
        effectEndTime: formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd'),
        minRemainedStock: this.ruleForm.packageStock
      };
    },
    /**
     * 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>
