<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="w300" 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="w300 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="营销场景">
        <el-select class="w300" v-model="ruleForm.sceneSettingId" placeholder="选择营销场景">
          <el-option v-for="item in sceneSettingIdOptions" :key="item.sceneSettingId" :label="item.sceneName" :value="item.sceneSettingId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="cardIds" label="新增卡券">
        <el-button @click="showCardDialog = true">添加卡券</el-button>
        <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 min-width="120" align="left" label="有效期">
            <template slot-scope="scope">
              <span v-if="scope.row.cardEffectiveMode !== 0">领取后第{{ scope.row.startDay + 1 }}-{{ scope.row.limitDay + scope.row.startDay }}天</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>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveForm">{{ isAdd ? '新增' : '保存' }}</el-button>
      </el-form-item>
    </el-form>
    <vue-gic-card :showCardDialog="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,
        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;
        })
        .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>
