<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 :disabled="!canEdit" class="w400" v-model="ruleForm.cdkeyName" placeholder="请输入兑换码名称" :byteType="1" :maxlength="24"></dm-input>
      </el-form-item>
      <el-form-item label="数据对话" prop="marketingActivityId">
        <dm-activity-select class="activity" :actId.sync="ruleForm.marketingActivityId" :readOnly="!canEdit"></dm-activity-select>
      </el-form-item>
      <el-form-item prop="dateTime" label="有效期">
        <el-date-picker :default-time="['00:00:00', '23:59:59']" :disabled="!canEdit" 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="cdkeyValue">
        <el-radio-group :disabled="!isAdd" v-model="ruleForm.cdkeyType" @change="changeCdkeyValue">
          <el-radio :label="1" style="margin-right:44px;">专属码</el-radio>
          <el-radio :label="2">通用码</el-radio>
        </el-radio-group>
        <div v-if="ruleForm.cdkeyType == 2">
          <div class="code1">码值：<el-input :disabled="!isAdd" style="width:180px;" clearable v-model.trim="ruleForm.cdkeyValue" maxlength="12" palceholder="请输入码值"></el-input></div>
        </div>
      </el-form-item>
      <el-form-item label="券码生成方式" prop="fileId" v-if="ruleForm.cdkeyType == 1">
        <el-radio-group :disabled="!isAdd" v-model="ruleForm.cdkeyMode" @change="changeCdKeyMode">
          <el-radio :label="1">系统生成</el-radio>
          <el-radio :label="2">手工导入</el-radio>
        </el-radio-group>
        <el-button v-if="ruleForm.cdkeyMode == 2 && !isAdd" class="ml20" type="text" @click="cdkeyExport">导出兑换码列表</el-button>
        <div v-if="ruleForm.cdkeyMode == 2">
          <div class="code2" v-if="isAdd">
            <div>
              <file needAxiosDataBack @dataBack="dataBack" ref="fileUpload" class="inline-block" label="点击上传" @backImg="backImg" acceptType=".xlsx, .csv" 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" @click="downloadMX">下载模板</el-button>
            </div>
            <div class="gray">仅支持xlsx\csv格式</div>
            <div class="success-file" v-if="importRes.fileId">
              <span class="fl" style="inline-block;max-width:500px;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:40px;margin-right:2px;"></i>
            </div>
            <!-- eslint-disable-next-line -->
            <div v-if="importRes.fileId" style="line-height:1;">导入成功{{ importRes.success }}条，导入失败<span class="warning-span">{{ importRes.fail }}</span>条
              <template v-if="importRes.fail > 0">，<el-button type="text" @click="cdkeyFailExport">下载导入失败记录</el-button></template>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="`${ruleForm.cdkeyType == 2 ? '兑换次数上限' : '兑换码数量'}`" prop="cdkeyCount" class="is-required">
        <el-input-number :disabled="!isAdd || ruleForm.cdkeyMode == 2" style="width:140px;" v-model="ruleForm.cdkeyCount" controls-position="right" :min="0" :max="10000"></el-input-number>
        <span class="gray ml10" v-if="ruleForm.cdkeyType != 2">券码数量请控制在10000以内</span>
      </el-form-item>
      <el-form-item label="兑换内容" prop="cdkeyContentRelated">
        <el-button type="plain" style="border-style:dashed;width:105px;" v-show="!ruleForm.cdkeyContentRelated" @click="showCardDialog = true">选择卡券</el-button>
        <div v-show="ruleForm.cdkeyContentRelated">
          <el-tooltip open-delay="300" effect="dark" :content="ruleForm.cdkeyContentRelated" placement="top-start">
            <span>{{ ruleForm.cdkeyContentDescribe }}</span>
          </el-tooltip>
          <el-button v-if="canEdit" type="text" @click="cleanCard" class="ml10">删除</el-button>
          <template v-if="!isAdd">
            <span v-if="relatedInfo.status == 0" class="ml10 fz12" style="color:#f56c6c"><i class="el-icon-warning fz12 mr5"></i>已删除</span>
            <span v-else-if="relatedInfo.stock <= 0" class="ml10 fz12" style="color:#f56c6c"><i class="el-icon-warning fz12 mr5"></i>库存不足</span>
          </template>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit" v-if="canEdit">确认{{ isAdd ? '新建' : '保存' }}</el-button>
      </el-form-item>
    </el-form>
    <vue-gic-card appendToBody :showCardDialog.sync="showCardDialog" @selectCard="selectCard" :cardLimit="-1" :cardType="null"></vue-gic-card>
    <vue-gic-export-excel :dialogVisible.sync="dialogVisible" :dataArr="[1, 2, 3]" :type="2" :excelUrl="excelUrl" :params="params" :projectName="projectName"></vue-gic-export-excel>
    <!-- <form action="http://gicdev.demogic.com/api-marketing/cdkey-fail-export" target="_blank" enctype="multipart/form-data">
      <input type="text" name="requestProject" value="gic-web" />
      <input type="file"/>
      <button type="submit">submit</button>
    </form> -->
  </div>
</template>

<script>
import axios from 'axios';
import file from '@/components/upload/file';
import { formatDateTimeByType } from '@/utils/index.js';
import { cdkeyCheck, cdkeyPlanSave, cdkeyPlanEdit, cdkeyFailExport, cdkeyExport } from '@/service/api/cdKeyApi.js';
import { getCardDetail } from '@/service/api/cardApi.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 && this.canEdit) {
          callback(new Error(rule.message || '时间跨度不能超过三个月'));
        }
        callback();
      } else {
        callback(new Error('有效期不能为空'));
      }
    };
    const checkFileId = (rule, value, callback) => {
      if (this.ruleForm.cdkeyMode == 2 && !this.importRes.fileId && this.isAdd) {
        return callback(new Error(rule.message));
      }
      callback();
    };

    const checkCdkeyCount = (rule, value, callback) => {
      if (!value) {
        let message = '请输入' + (this.ruleForm.cdkeyType == 2 ? '兑换次数上限' : '兑换码数量');
        if (this.ruleForm.cdkeyMode == 2) {
          message = this.importRes.fileName ? '手工导入数据无可用码' : '请上传文件';
        }
        return callback(new Error(`${message}`));
      }
      callback();
    };

    // 验证码值
    const validateCdkeyValue = (rule, value, callback) => {
      if (this.ruleForm.cdkeyType == 2) {
        if (!this.ruleForm.cdkeyValue) {
          callback(new Error('请输入码值'));
        }
        // 码值限定8位，包含数字及字母
        if (!/^[0-9A-Za-z]{8}$/.test(this.ruleForm.cdkeyValue)) {
          callback(new Error('码值限定8位，包含数字及字母'));
        }
        return callback();
      } else {
        callback();
      }
    };
    return {
      loading: false,
      cdkeyPlanId: this.$route.params.id,
      cdkeyFailExportUrl: cdkeyFailExport,
      ruleForm: {
        cdkeyContentType: '', // 1卡券
        cdkeyContentRelated: '', // 1是cardId
        cdkeyContentDescribe: '', // 1是cardName
        cdkeyMode: 1,
        cdkeyCount: undefined,
        cdkeyType: 1,
        cdkeyValue: '',
        cdkeyEffectTime: '',
        cdkeyLimitTime: '',
        cdkeyName: '',
        marketingActivityId: ''
      },
      importRes: {
        // 导入文件的信息
        file: null,
        fileId: '',
        fileName: '',
        size: '',
        fail: 0,
        success: 0,
        failData: [],
        total: 0
      },
      rules: {
        cdkeyName: [{ required: true, message: '请输入兑换码名称', trigger: 'change' }],
        cdkeyCount: [{ validator: checkCdkeyCount, trigger: 'change' }],
        cdkeyContentRelated: [{ required: true, message: '请选择卡券', trigger: 'change' }],
        fileId: [{ validator: checkFileId, message: '请上传文件', trigger: 'change' }],
        dateTime: [{ required: true, validator: validateDate, trigger: 'change' }],
        cdkeyValue: [{ required: true, validator: validateCdkeyValue, trigger: 'change' }]
      },
      info: {},
      uploadUrl: cdkeyCheck,
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      dateTime: [],
      // 兑换内容的详情，一般是库存什么的，详情和编辑需要提示库存不足的情况
      relatedInfo: {
        stock: 100,
        status: 1
      },
      // 导出
      projectName: 'marketing', // 当前项目名
      dialogVisible: false,
      excelUrl: '', // 下载数据的地址
      params: {}, // 传递的参数
      showCardDialog: false,
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      isInfo: this.$route.meta.type === 'info'
    };
  },
  components: {
    file
  },
  computed: {
    canEdit() {
      // 是新增或编辑未生效
      return this.isAdd || (this.isEdit && new Date() < this.info.cdkeyEffectTime);
    }
  },
  methods: {
    changeCdkeyValue(val) {
      if (val == 2) {
        this.ruleForm.cdkeyMode = 1;
      }
      this.$refs.ruleForm.validateField('cdkeyCount');
    },
    changeCdKeyMode(val) {
      if (val == 2) {
        this.ruleForm.cdkeyCount = this.importRes.success || 0;
        const cdkeyCount = this.$refs.ruleForm.fields.find(v => v.prop == 'cdkeyCount');
        const fileId = this.$refs.ruleForm.fields.find(v => v.prop == 'fileId');
        cdkeyCount.resetField();
        fileId.resetField();
      } else {
        this.$refs.ruleForm.validateField('cdkeyCount');
      }
    },
    // 下载模板
    downloadMX() {
      const prev = process.env['NODE_ENV'] === 'development' ? '' : '/marketing'; // eslint-disable-line
      window.open(`${prev}/static/file/兑换码模板示例.xlsx`, '_blank');
    },
    // 获取详情
    getInfo() {
      this.loading = true;
      cdkeyPlanEdit({ cdkeyPlanId: this.cdkeyPlanId })
        .then(res => {
          Object.keys(this.ruleForm).map(v => {
            this.ruleForm[v] = res.result[v];
          });
          this.info = res.result || {};
          this.dateTime = [res.result.cdkeyEffectTime, res.result.cdkeyLimitTime];
          // 卡券
          if (res.result.cdkeyContentType == 1) {
            this.getCardInfo(res.result.cdkeyContentRelated);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取卡券详情
    getCardInfo(coupCardId) {
      getCardDetail({ coupCardId }).then(res => {
        if (res.result.card) {
          this.relatedInfo.stock = res.result.card.couponStock;
          this.relatedInfo.status = res.result.card.status;
        }
      });
    },
    submit: _debounce(function() {
      if (this.loading) {
        return;
      }
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {
          return;
        }
        this.loading = true;
        let params = { ...this.ruleForm };
        params.cdkeyEffectTime = formatDateTimeByType(this.dateTime[0], 'yyyy-MM-dd HH:mm:ss');
        params.cdkeyLimitTime = formatDateTimeByType(this.dateTime[1], 'yyyy-MM-dd HH:mm:ss');
        delete params.fileId;
        let formData = new FormData();
        formData.append('requestProject', 'gic-web');
        if (params.cdkeyMode == 2) {
          // 手工导入
          formData.append('file', this.importRes.file);
        }
        Object.keys(params).forEach(key => {
          formData.append(key, params[key]);
        });
        if (this.isEdit) {
          formData.append('cdkeyPlanId', this.cdkeyPlanId);
          // 编辑不要cdkeyMode cdkeyType cdkeyValue cdkeyCount
          formData.delete('cdkeyMode');
          formData.delete('cdkeyType');
          formData.delete('cdkeyValue');
          formData.delete('cdkeyCount');
        }
        axios
          .post(cdkeyPlanSave, formData)
          .then(res => {
            if (res.data.errorCode === 0) {
              this.$tips({ message: '操作成功！' });
              this.$router.push('/cdKey/list');
            } else {
              // throw new Error(res.data); // eslint-disable-line
              this.$tips({ type: 'error', message: res.data.message });
            }
          })
          .catch(err => {
            this.$tips({ type: 'error', message: err.message });
          })
          .finally(() => {
            this.loading = false;
          });
      });
    }),
    // 下载失败记录
    cdkeyFailExport() {
      let formData = new FormData();
      formData.append('requestProject', 'gic-web');
      formData.append('file', this.importRes.file);
      const xhr = new XMLHttpRequest();
      xhr.withCredentials = true;
      xhr.responseType = 'blob'; // 返回类型blob  blob 存储着大量的二进制数据
      xhr.onload = function() {
        if (xhr.status === 200 && xhr.readyState == 4) {
          const blob = xhr.response;
          const a = document.createElement('a');
          const url = window.URL.createObjectURL(blob);
          a.href = url;
          //设置文件名称
          a.download = `兑换码导入失败记录${new Date().getTime()}.xlsx`;
          a.click();
        }
      };
      xhr.open('post', cdkeyFailExport, true);
      xhr.send(formData);
    },
    // *********卡券选择器******
    cleanCard() {
      this.ruleForm.cdkeyContentRelated = '';
      this.ruleForm.cdkeyContentDescribe = '';
      this.ruleForm.cdkeyContentType = '';
      this.$refs.ruleForm.validateField('cdkeyContentRelated');
    },
    //选择卡券后置
    selectCard(val) {
      if (val) {
        this.ruleForm.cdkeyContentType = 1;
        this.ruleForm.cdkeyContentRelated = val.coupCardId;
        this.ruleForm.cdkeyContentDescribe = val.cardName;
        this.$refs.ruleForm.validateField('cdkeyContentRelated');
      }
      this.showCardDialog = false;
    },
    // 上传数据返回
    dataBack(file, result) {
      this.importRes.file = file;
      this.importRes.fileName = file.name.length > 15 ? file.name.substring(0, 15) + '...' : file.name;
      this.importRes.fileId = new Date();
      this.importRes.size = (file.size / 1024).toFixed(2);
      this.importRes.success = result.success;
      this.ruleForm.cdkeyCount = result.success;
      this.importRes.fail = result.fail || undefined;
      this.importRes.total = result.total;
      this.importRes.failData = result.failData;
      this.$refs.ruleForm.validateField('fileId');
      this.$refs.ruleForm.validateField('cdkeyCount');
    },
    // 导出记录
    cdkeyExport() {
      this.dialogVisible = true;
      this.excelUrl = cdkeyExport;
      this.params = {
        cdkeyPlanId: this.cdkeyExport,
        requestProject: 'marketing'
      };
    }
  },
  mounted() {
    if (!this.isAdd) {
      this.getInfo();
    }
  },
  created() {
    const name = this.isAdd ? '新建兑换码' : this.isEdit ? '编辑兑换码' : '兑换码详情';
    this.$store.commit('mutations_breadcrumb', [{ name: '营销管理', path: '' }, { name: '兑换码', path: '/cdKey/list' }, { 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 11px 23px;
  color: #606266;
  display: inline-block;
  margin-top: 7px;
  min-width: 300px;
  max-width: 700px;
}
.success-file {
  color: #606266;
  overflow: hidden;
  font-size: 14px;
  padding: 10px 0 16px;
  height: 37px;
  line-height: 37px;
}
.warning-span {
  color: #f5222d;
}
</style>
