import { reRreshRoute, formatDateTimeByType, deepClone } from '@/utils';
import api, { downloadCouponCSV } from '@/api/gic-card';
import { isEmpty } from '@/utils/index';
import { showConfirm } from '@/utils/common';
import { predefineColors, startDayOptionsDay, startDayOptionsMonth  } from '@/config/mapping/gic-card';
import { marketPrefix as prefix } from '@/config';
import resultDialog from './module/result-dialog';
import sendPreview from './module/send-preview';
import commomApi, { uploadUrl } from '@/api/common.js';
const { getRelationId } = commomApi;
const { addCard, copyCard, checkDemoCode, getMallShopList, importCode } = api;

// 禁止回车
const preventEnter = function(e) {
  let et = e || window.event;
  let keycode = et.charCode || et.keyCode;
  if (keycode == 13) {
    if (window.event) {
      window.event.returnValue = false;
    } else {
      e.preventDefault(); // for firefox
    }
  }
};

// 线下门店适用
const defaultXxsy = {
  switch: 1,
  feeLimit: 0,
  onlyFlag: 0,
  storeFilterId: '',
  goodsFilterId: '',
};
// GIC微商城适用
const defaultGicmall = {
  switch: 0,
  feeLimit: 0,
  onlyFlag: 0,
  goodsFilterId: '',
  maxDiscountAmount: undefined,
  maxDiscountGoodsCount: undefined,
  shopFilter: [] // 店铺
};
// 微盟微商城适用
const defaultWmmall = {
  switch: 0,
  feeLimit: 0,
  onlyFlag: 0,
  goodsFilterId: '',
  maxDiscountAmount: undefined,
  maxDiscountGoodsCount: undefined
};

// 切换cardType会重置表单值
const _ruleForm1 = {
  cardType: 0, // 1.卡券类型: 抵金券: 0; 折扣券: 1; 兑换券: 2
  cardName: '', // 卡券名称
  remarkName: '', // 备注名
  subTitle: '', // 副标题
  color: '#3970b5', // 卡券颜色
  denomination: '', // 优惠金额 抵金券0时存在
  costPrice: '', // 成本费用 折扣券1、兑换券2存在
  // manualGetFlag: 0,
  // code类型↓
  customCodeFlag: 0,
  couponStock: 100000,
  codeBegin: undefined,
  codeEnd: undefined,
  codePrefix: '',
  codeSuffix: '',
  codePrefixFlag: 0, // 是否固定开头
  codeSuffixFlag: 0, // 是否固定结尾
  // code类型↑
  // 有效期↓
  cardEffectiveMode: 0,
  effectTimeMode: 0,
  dateTime: [],
  effectTimeCount: 1,
  expireTimeCount: 1,
  // 有效期上
  getLimit: 1, // 领取限制
  verificationType: 0, // 核销方式 兑换券3时存在
  // 转赠 start
  giveFlag: 0,
  giveContent: '',
  giveWxImage: '', // 貌似没用
  giveImage: '',
  giveImageField: '', // 貌似没用
  giveBannerImage: '',
  giveBannerImageField: '',
  giveBannerJumpFlag: '',
  giveBannerJumpUrl: '',
  giveRule: '1.卡券新老用户同享。\n2.用户使用卡券下单，订单取消后，卡券将自动失效',
  // 转赠 end
  goodsSearchId: '', // 兑换券 兑换商品 - 选择器id
  goodsSearchIdWaiting: true, // 兑换券 兑换商品 - 等待状态
  // 跳转配置
  cardJumpFlag: 0,
  cardJumpLink: '',
  stockUseType: 0, // （0:占用,1:动态 , 2占用+动态）
  operAuthType: 1, // 1所有账号2部分账号3仅创建人
  operAuth: [],
  miniprogramname: '',
  useExplain: '', // 使用说明
  adaptGoodsExplain: '', // 适用商品说明
  adaptStoreExplain: '', // 适用门店说明
};


const defaultUseCondition = {
  goods_adapt_number_min_limit: undefined, // eslint-disable-line
  goods_adapt_number_max_limit: undefined, // eslint-disable-line
  goodsDiscountCheck: 0, // 1限制 0不限
  goodsDiscountCheckLower: 0, // 1限制 0不限
};

export default {
  name: 'card-form',
  components: {
    resultDialog,
    sendPreview
  },
  data() {
    // 校验优惠金额和折扣额度
    const validDenomination = (rule, value, callback) => {
      if (!value && value !== 0) {
        callback(new Error('请输入优惠金额'));
      }
      if (this.ruleForm1.cardType === 0 && Number(value) <= 0) {
        callback(new Error('优惠金额不能小于0'));
      }
      if (this.ruleForm1.cardType === 1 && Number(value) < 1) {
        callback(new Error('最低折扣不能小于1'));
      }
      callback();
    };

    // 起始号段
    const validCustomCode = (rule, value, callback) => {
      const { codeBegin, codeEnd, customCodeFlag } = this.ruleForm1;
      if (customCodeFlag == 1) {
        if (!codeBegin || !codeEnd) {
          callback(new Error('起始号段和结尾号段不能为空'));
          return;
        }
        if (isNaN(codeBegin) || isNaN(codeEnd)) {
          callback(new Error('起始号段和结尾号段为数值型'));
          return;
        }
        if (codeBegin.toString().length !== codeEnd.toString().length) {
          callback(new Error('code起始号段和结尾号段必须位数一致'));
        }
        if (parseInt(codeEnd) - parseInt(codeBegin) < 0) {
          // this.ruleForm1.codeEnd = this.ruleForm1.codeBegin;
          callback(new Error('自定义结尾号段不能小于初始号段'));
        }
        if (parseInt(codeEnd) - parseInt(codeBegin) + 1 > 1000000) {
          callback(new Error('创建数量不能大于1,000,000张'));
        }
      }
      callback();
    };

    // 验证固定号段 -- 固定开头和结尾
    const validCodeFixed = (rule, value, callback) => {
      const { codePrefixFlag, codePrefix, codeSuffixFlag, codeSuffix, customCodeFlag } = this.ruleForm1;
      if (customCodeFlag == 1) {
        if (codePrefixFlag && codePrefix === '' && codeSuffixFlag && codeSuffix === '') {
          callback(new Error('固定开头，固定结尾必填'));
        }
        if (codeSuffixFlag && codeSuffix === '') {
          callback(new Error('固定结尾必填'));
        }
        if (codePrefixFlag && codePrefix === '') {
          callback(new Error('固定开头必填'));
        }
      }
      callback();
    };

    // 验证首图 转赠链接
    const validBannerJumpUrl = (rule, value, callback) => {
      if (this.checked && !value) {
        callback(new Error('请选择首图跳转链接'));
      }
      callback();
    };


    const validGiveContent = (rule, value, callback) => {
      if (this.ruleForm1.giveFlag && !value) {
        callback(rule.message);
      }
      callback();
    };

    // 验证有效期0
    const validTime = (rule, value, callback) => {
      const dateTime = this.ruleForm1.dateTime;
      if (dateTime && dateTime[0] && dateTime[1]) {
        let nowDate = new Date();
        nowDate.setHours(0);
        nowDate.setMinutes(0);
        nowDate.setSeconds(0);
        nowDate.setMilliseconds(0);
        if (dateTime[0] < nowDate || dateTime[1] < nowDate) {
          callback(new Error('有效期范围必须大于当前时间'));
        }
        if (new Date(dateTime[1]).getTime() - new Date(dateTime[0]).getTime() > 1000 * 60 * 60 * 24 * 365) {
          callback(new Error('时间跨度不能大于一年'));
        }
        callback();
      } else {
        callback(new Error('请填写有效期'));
      }
    };

    // 校验有效期1
    const validEffectTimeMode = (rule, value, callback) => {
      const { cardEffectiveMode, effectTimeMode, effectTimeCount, expireTimeCount } = this.ruleForm1;
      if(isEmpty(effectTimeMode) || isEmpty(effectTimeCount) || isEmpty(cardEffectiveMode) || isEmpty(expireTimeCount)) {
        callback(new Error('有效期填写不完整'));
      }
      callback();
    };

    // 验证gic微商城店铺
    const validGicmallShopFilter = (rule, value, callback) => {
      if (!this.gicmall.shopFilter.length) {
        callback('请选择GIC微商城店铺');
      }
      callback();
    };

    // 校验demo code
    const validDemoCode = (rule, value, callback) => {
      if (value) {
        checkDemoCode({ erpDemoCode: value, memberCardId: this.currentAreaId }).then(res => {
          callback();
        }).catch(err => {
          callback(new Error(err.message));
        });
      } else {
        callback();
      }
    };

    const validMin0 = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error(rule.message || '输入值必须大于0'));
        return;
      } else {
        callback();
      }
    };


    const validStockType = (rule, value, callback) => {
      if (!this.stockType.length) {
        callback(new Error(rule.message));
        return;
      } else {
        callback();
      }
    };

    const validDiscount = (rule, value, callback) => {
      if (rule.type == 'min') {
        if (this.useConditionLimit.goodsDiscountCheckLower == 1 && isNaN(this.useConditionLimit.goods_adapt_number_min_limit)) {
          callback(new Error('请填写最低适用商品件数'));
          return;
        }
      } else {
        if (this.useConditionLimit.goodsDiscountCheck == 1 && isNaN(this.useConditionLimit.goods_adapt_number_max_limit)) {
          callback(new Error('请填写最高适用商品件数'));
          return;
        }
      }
      callback();
    };

    const validUploadFileList = (rule, value, callback) => {
      if (this.ruleForm1.customCodeFlag == 2 && this.fileList.length == 0) {
        callback(new Error('请导入券码文件'));
        return;
      }
      callback();
    };

    return {
      loading: false,
      active: 1,
      uploadUrl,
      zmImg: [ { url: 'https://pic01-10001430.image.myqcloud.com/13597/1622599355173_TAcQN.png', fileId: '13597/1622599355173_TAcQN.png' } ], // 转赠图片
      stImg: [ { url: 'https://pic01-10001430.image.myqcloud.com/13597/1622599673145_IeGHg.png', fileId: '13597/1622599673145_IeGHg.png' } ], // 首图图片
      stockType: [], // 库存使用类型（0:占用,1:动态 , 2占用+动态）
      prefix,
      couponId: '', // gic-card 新建时就生成couponId
      copyId: this.$route.query.copyId,
      coupon: {}, // 备份卡券数据 copy和edit时有用
      predefineColors, // 预设颜色
      subapp: {}, // 子应用信息
      miniProList: [], // 小程序列表
      ruleForm1: {
        ..._ruleForm1, // 需要重置的ruleform1内容
      },
      ruleForm2: {
        erpDemoCode: '', // demo券号
      },
      rules1: {
        cardName: { required: true, message: '请输入卡券名称', trigger: 'blur' },
        remarkName: { required: true, message: '请输入备注名称', trigger: 'blur' },
        // subTitle: { required: true, message: '请输入卡券副标题', trigger: 'blur' },
        denomination: { required: true, validator: validDenomination, trigger: 'blur' },
        goodsDiscountCheckLower: { validator: validDiscount, type: 'min', trigger: 'blur' },
        goodsDiscountCheck: { validator: validDiscount, type: 'max', trigger: 'blur' },
        couponStock: [
          { required: true, trigger: 'blur', message: '请输入库存' },
          { validator: validMin0, trigger: 'change', message: '库存必须大于0' }
        ],
        giveContent: { validator: validGiveContent, message: '请输入转赠对话框文字', trigger: 'blur' },
        giveRule: { required: true, message: '请输入卡券转赠规则', trigger: 'blur' },
        giveImage: { required: true, message: '请上传转赠封面', trigger: 'change' },
        giveBannerImage: { required: true, message: '请上传转赠页面首图', trigger: 'change' },
        costPrice: [
          { required: true, trigger: 'blur', message: '请输入成本' },
          { validator: validMin0, trigger: 'change', message: '成本必须大于0' }
        ],
        uploadFlag: { required: true, validator: validUploadFileList, trigger: 'change' },
        cardEffectiveMode0: [ { validator: validTime, trigger: 'change' } ],
        cardEffectiveMode1: [ { required: true, validator: validEffectTimeMode, trigger: 'change' } ],
        customCode: [
          { required: true, validator: validCustomCode, trigger: 'change' },
          { required: true, validator: validCodeFixed, trigger: 'blur' }
        ],
        giveBannerJumpUrl: { validator: validBannerJumpUrl, trigger: 'change' },
        stockType: { required: true, validator: validStockType, message: '请勾选库存消耗方式', trigger: 'change' },
        useExplain: { required: true, message: '使用说明不能为空', trigger: 'blur' },
        coverContent: { required: true, message: '封面简介不能为空', trigger: 'blur' },
      },
      rules2: {
        erpDemoCode: [ { validator: validDemoCode, trigger: 'blur' } ],
        gicmallShopFilter: [ { required: true, validator: validGicmallShopFilter, trigger: 'change' } ]
      },
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      // 预览
      preview: {
        visible: false,
        disabled: true
      },
      uploadFileloading: false,
      fileList: [], // 导入券码的的文件的列表
      // 线下门店适用
      xxsy: { ...defaultXxsy },
      xxsyGoodsWaiting: true, // xxsy 商品筛选器
      // GIC微商城适用
      gicmall: { ...defaultGicmall },
      gicmallGoodsWaiting: true, //  gic微商城 商品选择器
      gicMallShopList: [], // gic店铺列表
      // 微盟微商城适用
      wmmall: { ...defaultWmmall },
      imageList: [], // 封面
      teletextList: [], // 图文介绍
      result: { //
        visible: false,
        title: '',
        info: ''
      },
      // 适用商品件数
      useConditionLimit: { ...defaultUseCondition },
      // 转增 首图链接
      linkData: {},
      checked: false,
      linkData2: {}, // 跳转配置
      submitType: '', // 提交结果 1成功 失败
      isAdd: this.$route.meta.type === 'add',
      isEdit: this.$route.meta.type === 'edit',
      isCopy: this.$route.meta.type === 'copy',
      relationId: '', // 账号分组relationId
      isEcho: false, // 控制操作人权限是否回显数据
      sceneType: 10, // 场景值，现在测试使用，后期提供确定的
    };
  },
  created() {
    const breadName = this.isAdd || this.isCopy ? '新建卡券' : '编辑卡券';
    this.$emit('updateBread', [ { breadName: '福利中心', breadPath: '/index' }, { breadName: '卡券列表', breadPath: '/gic-card/list' }, { breadName } ]);
    this.ruleForm1.giveImage = this.zmImg[0].url;
    this.ruleForm1.giveImageField = this.zmImg[0].fileId;
    this.ruleForm1.giveBannerImage = this.stImg[0].url;
    this.ruleForm1.giveBannerImageField = this.stImg[0].fileId;
  },
  mounted() {
    if (this.currentAreaId) {
      this.ruleForm1.cardType = Number(this.$route.query.type) || 0;
      this.getRelationId(); // 生成主键
      this.getMallShopList();
      // this.handleGetSubAppByInfo();
      if (this.isCopy) {
        this.getInfo();
      }
    }
  },
  methods: {
    onSaveSearchId(id){
      console.log(id);
      this.ruleForm1.goodsSearchId = id;
    },
    getRelationId() {
      getRelationId().then(res => {
        this.couponId = res.result;
        this.relationId = res.result;
      });
    },
    getMallShopList() {
      getMallShopList().then(res => {
        this.gicMallShopList = res.result || [];
      });
    },
    changeCardEffcetMode() {
      this.$refs.ruleForm1.validateField('cardEffectiveMode0');
      this.$refs.ruleForm1.validateField('cardEffectiveMode1');
    },
    // 获取子应用信息 --服务号 会员卡 审核配置
    // async handleGetSubAppByInfo() {
    //   this.loading = true;
    //   let res1 = await getSubAppById({}, { memberCardId: this.currentAreaId, moduleCode: this.$store.getters.moduleCode });
    //   let res2 = await auditSettingInfo({ memberCardId: this.currentAreaId });
    //   if (res1.code === SUCCESS_CODE && res2.code === SUCCESS_CODE) {
    //     this.subapp = { ...res1.result, ...{ config: res2.result } };
    //     this.loading = false;
    //   }
    // },
    inputChange(key) {
      this.ruleForm1[key] = this.ruleForm1[key] ? this.ruleForm1[key].replace(/[^\d]/g, '') : '';
    },
    inputChange2(key) {
      this.ruleForm1[key] = this.ruleForm1[key] ? this.ruleForm1[key].replace(/[^a-zA-Z0-9]/g, '') : '';
    },
    // 检查是否为数字
    // checkInputNumber(val, name, formname) {
    //   if (isNaN(val)) {
    //     return;
    //   }
    //   this.ruleForm1[name] = (val.replace(/[^0-9]*/g, '') + '').substr(0, 16);
    //   if (parseInt(this.ruleForm1.codeEnd) - parseInt(this.ruleForm1.codeBegin) < 0) {
    //     this.ruleForm1.codeEnd = this.ruleForm1.codeBegin;
    //     this.$tips({ type: 'error', message: '自定义结尾号段不能小于初始号段' });
    //   }
    //   if (parseInt(this.ruleForm1.codeEnd) - parseInt(this.ruleForm1.codeBegin) + 1 > 1000000) {
    //     this.$tips({ type: 'error', message: '创建数量不能大于1,000,000张' });
    //     // this.ruleForm1.codeEnd  = this.ruleForm1.codeBegin  = 0;
    //     return;
    //   }
    // },
    // 检查是否为字符串
    checkInputString(val, name, formname) {
      this[formname][name] = val.replace(/[^a-zA-Z0-9]*/g, '') + '';
    },
    // 切换表单类型，重置表单未默认值
    reset(val) {
      this.ruleForm1 = { ...this.ruleForm1, ..._ruleForm1 };
      this.ruleForm1.cardType = val;
      setTimeout(() => {
        this.$refs.ruleForm1.resetFields();
      }, 0);
      this.useConditionLimit = { ...defaultUseCondition };
      // 清空第二步数据
      this.xxsy = { ...defaultXxsy };
      this.wmmall = { ...defaultWmmall };
      this.gicmall = { ...defaultGicmall };
      // !!! 清空图片数据
      this.zmImg = [];
      this.stImg = [];
    },
    // 去往第二步 校验ruleForm1
    changeStep(target, ruleFormName) {
      if (ruleFormName) {
        this.$refs[ruleFormName].validate((valid) => {
          if (!valid) {
            PublicMethods.jumpToFormError(`.${ruleFormName}`); // eslint-disable-line
            return;
          } else {
            new Promise((resolve, reject) => {
              if (target === 1) {
                // 回退至第一步
              }
              if (target === 2) {
                // 去往第二步 验证ruleForm1
                const { cardEffectiveMode, expireTimeCount, effectTimeMode, dateTime, customCodeFlag, operAuth, operAuthType } = this.ruleForm1;
                if(isEmpty(cardEffectiveMode)) {
                  reject({ message: '请选择有效期类型' });
                }
                // if (cardType == 2) {
                //   // 兑换券判断卡券优惠内容
                //   if(!this.ruleForm1.goodsSearchId) {
                //     reject({ message: '请保存卡券优惠内容' });
                //   } else if (this.goodsSearchIdWaiting) {
                //     reject({ message: '卡券优惠内容处于编辑状态请保存' });
                //   }
                // }
                // 验证有效期
                if (cardEffectiveMode) {
                  if (isEmpty(effectTimeMode)) { reject({ message: '有效期填写不完整' }); }
                  if (isEmpty(expireTimeCount)) { reject({ message: '有效期填写不完整' }); }
                } else {
                  if (!dateTime || !dateTime[0]) { reject({ message: '有效期必填' }); }
                }
                const { goodsDiscountCheckLower, goodsDiscountCheck, goods_adapt_number_min_limit, goods_adapt_number_max_limit } = this.useConditionLimit; // eslint-disable-line
                if (goodsDiscountCheckLower && !goods_adapt_number_min_limit) { // eslint-disable-line
                  reject({ message: '请填写最低适用商品件数' });
                }
                if (goodsDiscountCheck && !goods_adapt_number_max_limit) { // eslint-disable-line
                  reject({ message: '请填写最高适用商品件数' });
                }
                if (goodsDiscountCheckLower && goodsDiscountCheck && goods_adapt_number_min_limit && goods_adapt_number_max_limit && goods_adapt_number_min_limit >= goods_adapt_number_max_limit) { // eslint-disable-line
                  reject({ message: '最低商品件数不能必须小于最高商品件数' });
                }
                if (this.checked && !this.linkData.name && !this.linkData.url) {
                  reject({ message: '请设置首图链接' });
                }
                if (this.cardJumpLink && !this.linkData2.name && !this.linkData2.url) {
                  reject({ message: '请设置跳转配置' });
                }
                // 其他券 且选择导入券码 判断是否上传过csv
                if (customCodeFlag === 2 && this.fileList.length === 0) {
                  reject({ message: '请上传券码' });
                }
                if (operAuthType  == 2 && !operAuth.length) {
                  reject({ message: '请选择部分分组账号' });
                }
                if(!this.$refs.accg.validate()) return;
                this.$refs.accg.save().then((res) => {
                  if (res.code == '0000') {
                    resolve(target);
                  } else {
                    reject({ message: res.message });
                  }
                });
              }
              if (target === 3) {
                const { xxsy, gicmall } = this;
                // 去往第二步
                const fn = () => {
                  // 判断线下适用
                  if (xxsy.switch) {
                    if (xxsy.feeLimit == null) {
                      reject({ message: '请填写线下门店适用消费金额门槛' });
                    }
                    if(!xxsy.storeFilterId) {
                      reject({ message: '请保存线下适用门店' });
                    } else if (this.xxsyStoreWaiting) {
                      reject({ message: '线下适用门店处于编辑状态请保存' });
                    }
                    // 判断线下适用商品  兑换券不需要校验
                    // if (!xxsy.goodsFilterId && ruleForm1.cardType !== 2) {
                    //   reject({ message: '请保存线下门店线下适用商品' })
                    // }
                    // 判断线下适用商品
                    // if (this.ruleForm1.cardType !== 2) {
                    //   if (!xxsy.goodsFilterId) {
                    //     reject({ message: '请保存线下门店线下适用商品' });
                    //   } else if (this.xxsyGoodsWaiting) {
                    //     reject({ message: '线下适用商品处于编辑状态，请保存' });
                    //   }
                    // }
                  }
                  // 判断GIC微商城适用
                  if (gicmall.switch) {
                    if (gicmall.feeLimit == null) {
                      reject({ message: '请填写GIC微商城适用消费金额门槛' });
                    }
                    if (!gicmall.shopFilter.length) {
                      reject({ message: '请选择GIC微商城店铺' });
                    }
                    // 判断线下适用商品  兑换券不需要校验
                    if (this.ruleForm1.cardType !== 2) {
                      // 判断线下适用商品
                      if (!gicmall.goodsFilterId) {
                        reject({ message: '请保存GIC微商城适用商品' });
                      } else if (this.gicmallGoodsWaiting) {
                        reject({ message: 'GIC微商城适用商品处于编辑状态，请保存' });
                      }
                    }
                  }
                  // 判断微盟微商城适用
                  // if (wmmall.switch) {
                  //   if (wmmall.feeLimit == null) {
                  //     reject({ message: '请填写微盟微商城适用消费金额门槛' });
                  //   }
                  //   // 判断线下适用商品  兑换券不需要校验
                  //   if (!wmmall.goodsFilterId && ruleForm1.cardType !== 2) {
                  //     reject({ message: '请选择微盟微商城线下适用商品' })
                  //   }
                  // }
                };

                if (!xxsy.switch && !gicmall.switch) {
                  showConfirm('<div>当前卡券未开启任何适用渠道，确认新建？</div>', () => {
                    fn();
                    resolve(undefined);
                  }, {}, () => {
                    reject({});
                  });
                } else {
                  fn();
                  resolve(undefined);
                }
              }
            }).then(target => {
              if (target !== undefined) {
                this.active = target;
              } else {
                this.subFrom();
              }
            }).catch(({ message }) => {
              if (message) {
                this.$tips({ message, type: 'error' });
              }
            });
          }
        });
      } else {
        this.active = target;
      }

    },
    checkErpDemoCode() {
      this.ruleForm2.erpDemoCode = this.ruleForm2.erpDemoCode.replace(/[^\w\.\/]/gi, '');
    },
    // 获取卡券详情  复制编辑时用
    getInfo() {
      if (this.loading) {
        return;
      }
      this.loading = true;
      copyCard({ couponId: this.copyId }).then(res => {
        this.loading = false;
        const coupon = res.result;
        this.coupon = deepClone(coupon) || {}; // 备份数据
        // ruleForm1赋值
        const exclude = [ 'customCodeFlag', 'couponStock', 'codeBegin', 'codeEnd', 'codePrefix', 'codeSuffix', 'codePrefixFlag', 'codeSuffixFlag', 'operAuth' ]; // 不需要赋值的字段
        Object.keys(this.ruleForm1).map(key => {
          if (key in coupon && !exclude.includes(key)) {
            this.ruleForm1[key] = coupon[key];
          }
        });
        this.stockType = coupon.stockUseType == 2 ? [ 0, 1 ] : [ coupon.stockUseType * 1 ];
        this.ruleForm1.effectTimeMode = Number(coupon.effectTimeMode); // null的时候可以强转为0
        // 处理useConditionLimit
        const _useConditionLimit = JSON.parse(coupon.useConditionLimit) || {};
        this.useConditionLimit.goods_adapt_number_min_limit = _useConditionLimit.goods_adapt_number_min_limit || undefined; // eslint-disable-line
        this.useConditionLimit.goods_adapt_number_max_limit = _useConditionLimit.goods_adapt_number_max_limit || undefined; // eslint-disable-line
        this.useConditionLimit.goodsDiscountCheckLower = !_useConditionLimit.goods_adapt_number_min_limit ? 0 : 1;
        this.useConditionLimit.goodsDiscountCheck = !_useConditionLimit.goods_adapt_number_max_limit ? 0 : 1;
        this.ruleForm1.getLimit = 1; // 领取限制由于和输入框的冲突，选择不赋值
        if (this.ruleForm1.giveFlag && this.ruleForm1.giveBannerJumpUrl) {
          this.onSave(this.ruleForm1.giveBannerJumpUrl);
        }
        if (coupon.operAuthType == 2) {
          this.ruleForm1.operAuth = coupon.operAuth.split(',');
        }
        if (this.ruleForm1.cardJumpFlag) {
          this.onSave2(this.ruleForm1.cardJumpLink);
        }
        if (!coupon.cardEffectiveMode) {
          if (coupon.startDate > new Date()) {
            // 开始时间未到当前时间才赋值
            this.ruleForm1.dateTime = [ coupon.startDate || '', coupon.expireDate || '' ];
          }
          // 会把有效期生效时间覆盖了，设置默认1
          this.ruleForm1.effectTimeCount = 1;
          this.ruleForm1.expireTimeCount = 1;
        }
        if (coupon.giveFlag === 1) {
          this.zmImg = [ { url: coupon.giveImage, fileId: coupon.giveImageField } ];
          this.stImg = [ { url: coupon.giveBannerImage, fileId: coupon.giveBannerImageField } ];
        }
        // ruleForm2赋值
        this.ruleForm2.erpDemoCode = coupon.erpDemoCode || '';
        coupon.applyList.forEach(v => {
          const { applyType, feeLimit, onlyFlag, maxDiscountAmount, maxDiscountGoodsCount } = v;
          if (applyType === 1) {
            // 线下适用
            this.xxsy = {
              switch: 1,
              feeLimit,
              onlyFlag,
              storeFilterId: '',
              goodsFilterId: ''
            };
          }
          if (applyType === 2) {
            // 处理shopFilter gic店铺
            // GIC微商城适用
            this.gicmall = {
              switch: 1,
              feeLimit,
              onlyFlag,
              goodsFilterId: '',
              maxDiscountAmount,
              maxDiscountGoodsCount,
              shopFilter: [] // 不复制
            };
          }
          // if (applyType === 3) {
          //   // 微盟微商城适用
          //   this.wmmall = {
          //     switch: 1,
          //     feeLimit,
          //     onlyFlag,
          //     goodsFilterId: '',
          //     maxDiscountAmount,
          //     maxDiscountGoodsCount
          //   }
          // }
        });
        this.ruleForm1.giveRule = this.ruleForm1.giveRule || '1.卡券新老用户同享。\n2.用户使用卡券下单，订单取消后，卡券将自动失效';
      }).catch(() => {
        this.loading = false;
      });
    },
    // 提交表单
    subFrom() {
      if (this.loading) {
        return;
      }
      // if(!this.$refs.accg.validate()) return;
      // this.$refs.accg.save();
      let params = { ...this.ruleForm1, ...this.ruleForm };
      try {
        params.couponId = this.couponId; // 主键在一进来页面的时候就已经确定
        params.memberCardId = this.currentAreaId;
        // 处理数据
        params.getLimit = params.getLimit || 1;
        // 处理useConditionLimit
        params.useConditionLimit = {};
        if (params.operAuthType == 2) {
          params.operAuth = params.operAuth.join(',');
        }
        // 1限制 0不限
        params.useConditionLimit.goods_adapt_number_min_limit = this.useConditionLimit.goodsDiscountCheckLower ? this.useConditionLimit.goods_adapt_number_min_limit : 0; // eslint-disable-line
        params.useConditionLimit.goods_adapt_number_max_limit = this.useConditionLimit.goodsDiscountCheck ? this.useConditionLimit.goods_adapt_number_max_limit : 0; // eslint-disable-line
        params.useConditionLimit = JSON.stringify(params.useConditionLimit);
        if (params.cardEffectiveMode === 0) {
          // 固定日期
          params.startDate = formatDateTimeByType(params.dateTime[0], 'yyyy-MM-dd');
          params.expireDate = formatDateTimeByType(params.dateTime[1], 'yyyy-MM-dd');
          delete params.effectTimeCount;
          delete params.expireTimeCount;
        }
        delete params.dateTime;
        // 库存使用类型（0:占用,1:动态 , 2占用+动态）
        params.stockUseType = this.stockType.length == 2 ? 2 : this.stockType[0];
        if (params.customCodeFlag === 1) {
          // 自定义号段
          params.couponStock = params.codeEnd - params.codeBegin + 1;
        }

        // 其他券&&上传券码 不需要传库存字段
        if (params.cardType === 3 && params.customCodeFlag === 2) {
          delete params.couponStock;
        }
        // 不是兑换券， 删除兑换券的商品选择器id
        if (params.cardType !== 2) {
          delete params.goodsSearchId;
        }

        // 转赠
        // if (params.cardType !== 0) {
        //   params.manualGetFlag = 0;
        //   params.giveFlag = 0;
        // }
        // 仅随机生成支持卡券转赠
        if (params.customCodeFlag != 0) {
          params.giveFlag = 0;
        }
        if (!params.giveFlag) {
          delete params.giveContent;
          delete params.giveWxImage;
          delete params.giveImage;
          delete params.giveImageField;
          delete params.giveBannerImage;
          delete params.giveBannerImageField;
          delete params.giveBannerJumpFlag;
          delete params.giveBannerJumpUrl;
          delete params.giveRule;
        } else {
          if (!this.checked) {
            delete params.giveBannerJumpUrl; // 不勾选则不跳转 不需要传
          }
        }

        // 适用门店
        params.offLineFlag = this.xxsy.switch;
        if (!params.offLineFlag) {
          delete params.erpDemoCode; // erp卡券demo券号,线下门店适用开启了才有
          delete params.verificationType; // 核销方式 线下门店适用开启了才有
        }
        // gic微商城
        params.gicMallFlag = this.gicmall.switch;

        // 微盟微商城
        params.wmMallFlag = this.wmmall.switch;


        // 处理步骤二数据 卡券适用信息(线下门店; gic微商城; 微盟微商城)
        params.applyList = [];
        // 有数据的push，applyType：线下门店1  gic微商城2  微盟微商城3
        if (this.xxsy.switch) { // 线下门店
          params.applyList.push({
            applyType: 1,
            ...this.xxsy
          });
        }
        if (this.gicmall.switch) { // gic微商城
          let _gicmall = { ...this.gicmall };
          const shop = this.gicMallShopList.filter(v => {
            return this.gicmall.shopFilter.includes(v.id);
          });
          if(params.cardType !== 1) {
            // 折扣券外不包含这个条件
            delete _gicmall.maxDiscountAmount;
            delete _gicmall.maxDiscountGoodsCount;
          }
          params.applyList.push({
            applyType: 2,
            ..._gicmall,
            shopFilter: shop
          });
        }
        if (this.wmmall.switch) { // 微盟微商城
          let _wmmall = { ...this.wmmall };
          if(params.cardType !== 1) {
            // 折扣券外不包含这个条件
            delete _wmmall.maxDiscountAmount;
            delete _wmmall.maxDiscountGoodsCount;
          }
          params.applyList.push({
            applyType: 3,
            ..._wmmall
          });
        }
        params.applyList = params.applyList.map(v => {
          delete v.switch;
          // !!!兑换券 删除applyList中的goodFilterId
          if (params.cardType === 2) {
            delete v.goodsFilterId;
          }
          return v;
        });
        params.applyList = JSON.stringify(params.applyList);
      } catch (error) {
        console.log(error);
      }
      this.loading = true;
      addCard(params).then(res => {
        this.result.info = this.needCheck ? '卡券已创建并提交审核，请尽快通知审核人员进行审核。' : '卡券创建完成';
        this.result.title = '操作成功';
        this.result.visible = true;
        this.submitType = 1;
        this.loading = false;
        this.$store.commit('updateShowCornerCanUseApp', true);
        let callbackId = this.$route.query.callbackId;
        if(callbackId) {
          // 有callbackId参数时，认为入口是福利选择器组件
          // 操作完成后需要修改localStorage中的welfareCreateCallback，以触发福利选择器内部数据更新
          let obj = JSON.parse(localStorage.getItem('welfareCreateCallback') || '{}');
          obj[callbackId] = true;
          localStorage.setItem('welfareCreateCallback', JSON.stringify(obj));
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    // 提示信息关闭
    handleResClose() {
      if (this.submitType) {
        this.result.visible = false;
        this.$router.push('/gic-card/list');
      } else {
        reRreshRoute();
      }
    },
    zmSuccess(obj) {
      console.log(11111);
      this.zmImg = [ { url: obj.res.result.url, fileId: obj.res.result.fileId } ];
      console.log(this.zmImg);
      this.ruleForm1.giveImage = obj.res.result.url;
      this.ruleForm1.giveImageField = obj.res.result.fileId;
    },
    stSuccess(obj) {
      this.stImg = [ { url: obj.res.result.url, fileId: obj.res.result.fileId } ];
      this.ruleForm1.giveBannerImage = obj.res.result.url;
      this.ruleForm1.giveBannerImageField = obj.res.result.fileId;
    },
    beforeUpload(file) {
      if (file.size > 1024 * 1024) {
        this.$tips({ message: '请上传大小不超过1MB', type: 'warning' });
        return false;
      }
      return true;
    },
    downloadCouponCSV() {
      window.open(downloadCouponCSV);
    },
    uploadCode() {
      this.uploadFileloading = true;
      const file = this.$refs.file.files[0];
      importCode({
        file,
        remark: this.remark,
        couponId: this.couponId,
        memberCardId: this.currentAreaId
      }).then(res => {
        this.uploadFileloading = false;
        this.fileList.push({ name: file.name });
        this.$tips({ message: '上传成功', type: 'success' });
        this.$refs.file.value = '';
        this.$refs.ruleForm1.validateField('uploadFlag');
      }).catch(() => {
        this.uploadFileloading = false;
      });
    },
    // **********商品选择器*************
    confirm(keyName, id) { // 点击确认返回数据
      this[keyName].goodsFilterId = id;
    },
    // 保存兑换券的商品选择器id
    saveExchangeGoodsSearchId() {
      this.$refs.selector4.submit(true).then(res => {
        // 获取商品选择器保存id
        try {
          if (res) {
            this.ruleForm1.goodsSearchId = res.goodsSelectorId;
            this.$refs.ruleForm1.validateField('goodsSearchId');
          } else {
            throw new Error('商品选择器没有数据');
          }
        } catch (error) {
          this.$tips({ message: '商品选择器保存失败', type: 'error' });
        }
      });
    },
    // ***********链接小工具***********
    // -----首图链接-----
    onShow(val) {
      this.checked = val;
      if(this.checked) {
        this.$refs.link.onShow();
      }
    },
    onSave(linkData) {
      // 链接回显
      this.linkData = JSON.parse(linkData);
      this.ruleForm1.giveBannerJumpUrl = linkData;
      this.checked = true;
      this.$refs.ruleForm1.validateField('giveBannerJumpUrl');
    },
    onHide() {
      if (!this.ruleForm1.giveBannerJumpUrl) {
        this.checked = false;
        this.$refs.ruleForm1.validateField('giveBannerJumpUrl');
      }
    },
    onHide2() {
      if (!this.ruleForm1.cardJumpLink) {
        this.ruleForm1.cardJumpFlag = 0;
      }
    },
    // ----首图链接-----
    // -----跳转配置-----
    onSave2(linkData) {
      // 链接回显
      this.linkData2 = JSON.parse(linkData);
      this.ruleForm1.cardJumpLink = linkData;
    }
    // -----跳转配置-----
  },
  computed: {
    // 有效期 - 领取x天生效下拉
    startDayOptions() {
      return this.ruleForm1.effectTimeMode === 0 ? startDayOptionsDay : startDayOptionsMonth;
    },
    needCheck() {
      if (this.subapp.config) {
        if (this.isAdd || this.isCopy) {
          return this.subapp.config.couponAdd && this.subapp.config.couponType.includes(this.ruleForm1.cardType);
        }
        if (this.isEdit) {
          return !!this.subapp.couponUpdate;
        }
      }
      return false;
    },
    customCodeNum() {
      const num = this.ruleForm1.codeEnd - this.ruleForm1.codeBegin + 1;
      return isNaN(num) ? 0 : num;
    }
  },
  watch: {
    ruleForm1: {
      handler(val) {
        const { giveFlag, giveContent, giveImage, giveBannerImage, giveRule } = val;
        this.preview.disabled = giveFlag && giveContent && giveImage && giveBannerImage && giveRule;
      },
      deep: true
    },
    'ruleForm1.customCodeFlag'(val) {
      this.$refs.ruleForm1.validateField('customCode');
      this.$refs.ruleForm1.validateField('uploadFlag');
    },
    'ruleForm1.giveFlag'(val) {
      if (val) {
        this.$nextTick(_ => {
          // 禁止卡券转赠规则textare回车
          this.$refs.ruleTextarea.$el.querySelector('textarea').addEventListener('keydown', preventEnter);
        });
      } else {
        this.$refs.ruleTextarea.$el.querySelector('textarea').removeEventListener('keydown', preventEnter);
      }
    },
    discountAmountCheck(val) {
      if (val) {
        this.form.discount_amount_upper_limit = 0; // eslint-disable-line
      } else if (this.form.discount_amount_upper_limit <= 0) {
        this.form.discount_amount_upper_limit = 1; // eslint-disable-line
      }
    },
    'useConditionLimit.goodsDiscountCheckLower'() {
      this.$refs.ruleForm1.validateField('goodsDiscountCheckLower');
    },
    'useConditionLimit.goodsDiscountCheck'() {
      this.$refs.ruleForm1.validateField('goodsDiscountCheck');
    },
    'xxsy.switch'(val) {
      if (!val) {
        // 清空选择器数据
        this.xxsy.storeFilterId = '';
        this.xxsy.goodsFilterId = '';
      }
    },
    'gicmall.switch'(val) {
      if (!val) {
        // 清空选择器数据
        this.gicmall.goodsFilterId = '';
      }
    },
    'wmmall.switch'(val) {
      if (!val) {
        // 清空选择器数据
        this.wmmall.goodsFilterId = '';
      }
    }
  },
};
