<template>
  <div class="dm-wrap" v-loading="loading">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="140px">
      <el-form-item label="兑换码名称" prop="cdkeyName">
        <dm-input class="w400" v-model="ruleForm.cdkeyName" placeholder="请输入兑换码名称" :byteType="1" :maxlength="24"></dm-input>
      </el-form-item>
      <el-form-item prop="marketing_activity_id">
        <activity-select style="margin-left:-68px" class="activity" :actId.sync="ruleForm.marketing_activity_id" :readOnly="!isAdd"></activity-select>
      </el-form-item>
      <el-form-item prop="dateTime" label="有效期">
        <el-date-picker class="w400" v-model="dateTime" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="兑换码类型" prop="cdkey_value">
        <el-radio-group v-model="ruleForm.cdkey_type">
          <el-radio :label="1" style="margin-right:44px;">专属码</el-radio>
          <el-radio :label="2">通用码</el-radio>
        </el-radio-group>
        <div v-if="ruleForm.cdkey_type == 2">
          <div class="code1">码值：<el-input style="width:180px;" clearable v-model="ruleForm.cdkey_value" maxlength="12" palceholder="请输入码值"></el-input></div>
        </div>
      </el-form-item>
      <el-form-item label="券码生成方式" prop="fileId">
        <el-radio-group v-model="ruleForm.cdkey_mode">
          <el-radio :label="1">系统生成</el-radio>
          <el-radio :label="2">手工导入</el-radio>
        </el-radio-group>
        <div v-if="ruleForm.cdkey_mode == 2">
          <div class="code2">
            <div>
              <file needAxiosDataBack @dataBack="dataBack" ref="fileUpload" class="inline-block" label="点击上传" @backImg="backImg" acceptType=".csv, .xlsx" tips="" :url="uploadUrl" iconClass="el-icon-upload2" /><!-- 上传 -->
              <!-- <el-button type="primary" icon="iconfont icon-shangchuan fz14 mr5">上传</el-button> -->
              <el-button class="ml20" type="text">下载模板</el-button>
            </div>
            <div class="success-file" v-if="importRes.fileId">
              <span class="fl" style="inline-block;max-width:300px;overflow:hidden;"><i class="iconfont mr5 icon-excel" style="color:#23B08D"></i>{{ importRes.fileName }}({{ importRes.size }}kb)</span>
              <i class="el-icon-success fr success-color ml5" style="line-height:37px;"></i>
            </div>
            <!-- eslint-disable-next-line -->
            <div v-if="importRes.fileId" style="line-height:1;">导入成功{{ importRes.success }}条，导入失败<span class="warning-span">{{ importRes.fail }}</span>条，<el-button type="text">下载导入失败记录</el-button></div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="兑换码数量" v-if="ruleForm.cdkey_mode == 1" prop="cdkey_count">
        <el-input-number style="width:140px;" v-model="ruleForm.cdkey_count" controls-position="right" :min="1" :max="1000"></el-input-number>
        <span class="gray ml10">券码数量请控制在10000以内</span>
      </el-form-item>
      <el-form-item label="兑换内容" prop="cardId">
        <el-button v-show="!ruleForm.cardId" @click="showCardDialog = true">选择卡券</el-button>
        <div v-show="ruleForm.cardId">
          {{ ruleForm.cardName }}
          <el-button v-if="isAdd" type="text" @click="cleanCard" class="ml10">删除</el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">确认新建</el-button>
      </el-form-item>
    </el-form>
    <vue-gic-card appendToBody :showCardDialog="showCardDialog" @selectCard="selectCard" :cardLimit="-1" :cardType="null"></vue-gic-card>
  </div>
</template>

<script>
import file from '@/components/upload/file';
import { formatDateTimeByType } from '@/utils/index.js';
import activitySelect from '@/components/activity-select';
import { cdkeyPlanSave, cdkeyCheck } from '@/service/api/cdKeyApi.js';
import { _debounce } from '@/utils/index';
export default {
  name: 'cdkey-form',
  data() {
    const validateDate = (rule, value, callback) => {
      if (this.isEdit) {
        callback();
      }
      if (this.dateTime && this.dateTime[0]) {
        const date1 = this.dateTime[0];
        const date2 = this.dateTime[1];
        // if ((new Date(date1).getTime() - 24 * 60 * 60 * 1000) < new Date()) {
        //   callback(new Error('开始时间不能小于当前时间'));
        // }
        if (new Date(date2).getTime() - new Date(date1).getTime() > 90 * 24 * 60 * 60 * 1000) {
          callback(new Error(rule.message || '时间跨度不能超过三个月'));
        }
        callback();
      } else {
        callback(new Error('有效期不能为空'));
      }
    };
    const checkFileId = (rule, value, callback) => {
      if (this.ruleForm.cdkey_mode == 2 && !this.files.fileId) {
        return callback(new Error(rule.message));
      }
      callback();
    };

    // 验证码值
    const validateCdkeyValue = (rule, value, callback) => {
      if (this.ruleForm.cdkey_type == 2) {
        if (!this.ruleForm.cdkey_value) {
          callback(new Error('请输入码值'));
        }
        // 码值限定8位，包含数字及字母
        if (!/^[0-9A-Za-z]{8}$/.test(this.ruleForm.cdkey_value)) {
          callback(new Error('码值限定8位，包含数字及字母'));
        }
        return callback();
      } else {
        callback();
      }
    };
    return {
      loading: false,
      ruleForm: {
        cardId: '',
        cardName: '',
        cdkey_mode: 2,
        cdkey_type: 1,
        cdkey_value: '',
        cdkey_effect_time: '',
        cdkey_limit_time: '',
        cdkeyName: '',
        marketing_activity_id: ''
      },
      importRes: {
        // 导入文件的信息
        fileId: '',
        fileName: '',
        size: '',
        fail: 0,
        success: 0,
        failData: [],
        total: 0
      },
      rules: {
        cdkeyName: [{ required: true, message: '请输入兑换码名称', trigger: 'change' }],
        cdkey_count: [{ required: true, message: '请输入兑换码数量', trigger: 'change' }],
        cardId: [{ required: true, message: '请选择卡券', trigger: 'change' }],
        fileId: [{ validator: checkFileId, message: '请上传文件', trigger: 'change' }],
        dateTime: [{ required: true, validator: validateDate, trigger: 'change' }],
        cdkey_value: [{ required: true, validator: validateCdkeyValue, trigger: 'change' }]
      },
      uploadUrl: cdkeyCheck,
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      dateTime: [],
      showCardDialog: false,
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      isInfo: this.$route.meta.type === 'info'
    };
  },
  components: {
    activitySelect,
    file
  },
  methods: {
    submit: _debounce(function() {
      if (this.loading) {
        return;
      }
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {
          return;
        }
        this.loading = true;
        let params = { ...this.ruleForm };
        params.cdkey_effect_time = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd HH:mm:ss');
        params.cdkey_limit_time = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd HH:mm:ss');
        delete params.fileId;
        cdkeyPlanSave(params)
          .then(res => {
            this.loading = false;
            this.$message({ message: '操作成功', type: 'success' });
            this.close();
            this.$emit('refresh');
          })
          .catch(() => {
            this.loading = false;
          });
      });
    }),
    // *********卡券选择器******
    cleanCard() {
      this.ruleForm.cardId = '';
      this.ruleForm.cardName = '';
      this.$refs.ruleForm.validateField('cardId');
    },
    //选择卡券后置
    selectCard(val) {
      if (val) {
        this.ruleForm.cardId = val.coupCardId;
        this.ruleForm.cardName = val.cardName;
        this.$refs.ruleForm.validateField('cardId');
      }
      this.showCardDialog = false;
    },
    // 上传数据返回
    dataBack(file, result) {
      this.importRes.fileName = file.name;
      this.importRes.fileId = new Date();
      this.importRes.size = (file.size / 1024).toFixed(2);
      this.importRes.success = result.success;
      this.importRes.fail = result.fail;
      this.importRes.total = result.total;
      this.importRes.failData = result.failData;
    }
  },
  created() {
    const name = this.isAdd ? '新建兑换码' : this.isInfo ? '编辑兑换码' : '兑换码详情';
    this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '兑换码', path: '' }, { name, path: '' }]); // eslint-disable-line
  }
};
</script>

<style lang="scss" scoped>
.activity /deep/ .el-select {
  width: 400px !important;
}
.code1 {
  background: #f5f7fa;
  padding: 11px 20px 11px 10px;
  color: #606266;
  display: inline-block;
  margin-top: 7px;
}
.code2 {
  background: #f5f7fa;
  padding: 11px 43px 16px 23px;
  color: #606266;
  display: inline-block;
  margin-top: 7px;
}
.success-file {
  color: #606266;
  overflow: hidden;
  font-size: 14px;
  padding: 10px 0 16px;
  height: 37px;
  line-height: 37px;
}
.warning-span {
  color: #f5222d;
}
</style>
