<template>
  <div class="dm-wrap" v-loading="loading">
    <el-form ref="form" :model="ruleForm" label-width="140px" :rules="rules">
      <el-form-item prop="name" label="卡券包名称">
        <dm-input v-model="ruleForm.name" class="w250" placeholder="请输入卡券包名称" :byteType="1" :maxlength="10"></dm-input>
      </el-form-item>
      <el-form-item prop="effectiveMode" label="有效时间">
        <!-- <el-select class="w300" v-model="ruleForm.effectiveMode">
          <el-option v-for="(v, i) in sendTypeOptions" :key="i" :value="v.value" :label="v.label"></el-option>
        </el-select> -->
        <el-radio-group v-model="ruleForm.effectiveMode">
          <el-radio :label="0">不限</el-radio>
          <el-radio :label="1">选择时间段</el-radio>
        </el-radio-group>
        <br />
        <el-date-picker v-if="ruleForm.effectiveMode" class="w250 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="数据对话">
        <!-- 只能新增不能改 -->
        <dm-activity-select :actId.sync="ruleForm.marketingActivityId" :readOnly="isInfo || isEdit"></dm-activity-select>
      </el-form-item>
      <el-form-item prop="cardIds" label="新增卡券">
        <div><el-button @click="showCardDialog = true">添加卡券</el-button></div>
        <el-table v-if="ruleForm.cardIds" class="mt20" :data="tableData" style="width: 100%">
          <el-table-column min-width="120" align="left" prop="cardName" label="卡券名称">
            <template slot-scope="scope">
              <p style="line-height:22px;">{{ scope.row.cardName }}</p>
              <p class="fz13 gray" style="line-height:20px;">{{ scope.row.subName }}</p>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="false" min-width="140" align="left" prop="createTime" label="卡券模板投放期限">
            <template slot-scope="scope">
              <span v-if="scope.row.putEffectiveMode == 0"> 固定日期：{{ formatDateTimeByType(scope.row.putBeginDate, 'yyyy-MM-dd') }} 至 {{ formatDateTimeByType(scope.row.putEndDate, 'yyyy-MM-dd') }} </span>
              <span v-else>长期有效</span>
            </template>
          </el-table-column>
          <el-table-column min-width="120" align="left" label="用户使用有效期">
            <template slot-scope="scope">
              <span v-if="scope.row.cardEffectiveMode !== 0">领取后{{ (scope.row.startDay === 0 ? '当' : '第' + scope.row.startDay) + '天，有效天数' + scope.row.limitDay }}天</span>
              <span v-if="scope.row.cardEffectiveMode === 0">{{ formatDateTimeByType(scope.row.beginDate, 'yyyy-MM-dd') }} 至 {{ formatDateTimeByType(scope.row.endDate, 'yyyy-MM-dd') }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="120" align="left" label="领取限制">
            <template slot-scope="scope">
              <span>每人限制{{ scope.row.cardLimit }}张</span>
            </template>
          </el-table-column>
          <el-table-column min-width="120" align="left" label="适用门店">
            <template slot-scope="scope">
              <span>{{ scope.row.storeMode === 0 ? '所有门店' : scope.row.storeMode === 1 ? '部分门店' : '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="120" align="left" label="库存">
            <template slot-scope="scope">
              <span v-if="scope.row.auditingStatus !== -1">{{ scope.row.couponStock }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="80px" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="del(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <ul class="gray fz12 mt10" style="line-height:18px;">
            <li>未到卡券模板投放期限 —— 不显示</li>
            <li>超过卡券模板投放期限 —— 不显示</li>
            <li>超过用户领取限制 —— 已领取</li>
            <li>卡券库存为0 —— 已领完</li>
          </ul>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveForm">{{ isAdd ? '新增' : '保存' }}</el-button>
      </el-form-item>
    </el-form>
    <vue-gic-card :type="1" :showCardDialog.sync="showCardDialog" @selectCard="selectCard" :cardLimit="-1" :cardType="null"></vue-gic-card>
  </div>
</template>

<script>
import { saveCoupPackage, coupPackageDetail, getCoupListInfo } from '@/service/api/cardApi.js';
import { sceneSettingList } from '@/service/api/wechatApi.js';
import { formatDateTimeByType } from '@/utils/index.js';
export default {
  name: 'merge-form',
  data() {
    const validateSendType = (rule, value, callback) => {
      if (this.ruleForm.effectiveMode) {
        if ((this.dateTime && !this.dateTime[0]) || !this.dateTime) {
          callback(new Error('请选择发送时间'));
        }
      }
      callback();
    };
    return {
      loading: false,
      showCardDialog: false,
      ruleForm: {
        cardPackageId: '',
        cardIds: '', // 卡券ids,多个id用逗号隔开
        name: '',
        effectiveMode: 0,
        marketingActivityId: '',
        sceneSettingId: ''
      },
      dateTime: [],
      rules: {
        name: [{ required: true, message: '请输入卡券包名称', trigger: 'change' }],
        effectiveMode: [{ required: true, validator: validateSendType, trigger: 'change' }],
        cardIds: [{ required: true, message: '请选择卡券', trigger: 'change' }]
      },
      pickerOptions: {
        disabledDate(now) {
          return now.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      tableData: [],
      sceneSettingIdOptions: [],
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit'
    };
  },
  methods: {
    formatDateTimeByType,
    del({ coupCardId }) {
      let arr = this.ruleForm.cardIds.split(',');
      const idx = arr.findIndex(v => {
        return v === coupCardId;
      });
      arr.splice(idx, 1);
      this.ruleForm.cardIds = arr.join();
      if (this.ruleForm.cardIds) {
        this.getCoupListInfo();
      } else {
        this.tableData = [];
      }
    },
    async sceneSettingList() {
      let res = await sceneSettingList();
      this.sceneSettingIdOptions = res.result || [];
    },
    // 获取卡券list
    async getCoupListInfo() {
      this.loading = true;
      getCoupListInfo({ cardIds: this.ruleForm.cardIds })
        .then(res => {
          this.loading = false;
          this.tableData = res.result || [];
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //选择卡券后置
    selectCard(val) {
      let arr = this.ruleForm.cardIds ? this.ruleForm.cardIds.split(',') : [];
      if (val) {
        if (!arr.includes(val.coupCardId)) {
          arr.push(val.coupCardId);
          this.ruleForm.cardIds = arr.join();
          this.$refs.form.validateField('cardIds');
          this.getCoupListInfo();
          this.showCardDialog = false;
        } else {
          this.$tips({ type: 'warning', message: '卡券已存在' });
        }
      } else {
        this.showCardDialog = false;
      }
    },
    saveForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return;
        }
        this.loading = true;
        let params = { ...this.ruleForm };
        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');
        }
        if (this.isAdd) {
          delete params.cardPackageId;
        }
        saveCoupPackage(params)
          .then(res => {
            this.$tips({ type: 'success', message: '操作成功' });
            this.$router.push('/card/merge/list');
            this.loading = false;
          })
          .catch(err => {
            this.$tips({ type: 'error', message: err.message || '操作失败' });
            this.loading = false;
          });
      });
    },
    getInfo() {
      this.loading = true;
      coupPackageDetail({ cardPackageId: this.$route.params.id })
        .then(res => {
          this.ruleForm = { ...res.result };
          if (this.ruleForm.effectiveMode) {
            this.dateTime = [res.result.beginDate, res.result.endDate];
          }
          this.getCoupListInfo();
          this.loading = false;
          if (res.result.marketingActivityId) {
            this.$nextTick(() => {
              this.$refs.actSelect.setInfo(res.result.marketingActivityId);
              this.$refs.actSelect.disabled = true;
            });
          }
        })
        .catch(err => {
          this.$tips({ type: 'error', message: err.message || '获取详情失败' });
          this.loading = false;
        });
    }
  },
  mounted() {
    this.sceneSettingList();
    if (this.isEdit) {
      this.getInfo();
    }
  },
  created() {
    this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '卡券营销', path: '' }, { name: '卡券包', path: '' }, { name: this.isAdd ? '新建卡券包' : '编辑卡券包', path: '' }]); // eslint-disable-line
  }
};
</script>
