<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" :disabled="isInfo"></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" :disabled="isInfo">
          <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" :disabled="isInfo"></el-date-picker>
      </el-form-item>
      <el-form-item label="数据对话">
        <!-- 只能新增不能改 -->
        <template slot="label">
          <span>数据对话</span>
          <el-tooltip class="item" effect="dark" content="数据对话为原营销活动。可不选择，选择后会将该营销活动的数据置于选择的数据对话中一起分析" :open-delay="300">
            <i style="cursor:pointer;color:#c0c4cc;font-size:14px;" class="el-icon-question"></i>
          </el-tooltip>
        </template>
        <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" :disabled="isInfo">添加卡券</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 == 1">领取后{{ (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>
              <span v-if="scope.row.cardEffectiveMode == 2">投放后当月</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)" :disabled="isInfo">删除</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" :disabled="isInfo">{{ 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',
      isInfo: this.$route.meta.type === 'info'
    };
  },
  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.isInfo) {
      this.getInfo();
    }
  }
};
</script>
