/**
 * e袋洗卡券新增编辑
 */
import dmUploadImg from '@/components/upload/img';
// import imgTextDrag from '@/views/card/partials/imgtext-drag';
import { formatDateTimeByType, getTimesByReq } from '@/utils/index.js';
import goodCategory from './partials/ewash-good-category.vue';
// import xxSysp_mix from '@/mixins/selector.js'; // 商品选择器方法
import { getCardDetail, saveUpdateCard, getCategoryList, getPropertyList, getPropertyValueList } from '@/service/api/cardApi.js';
import dmGoodsInput from '@/components/goods-input/index.vue';
const initForm = {
  gicCouponType: 1, // （0微信券 1edaixi 页面固定传1）
  auditingStatus: '',
  cardType: 2, // e袋洗为兑换券 写死2
  giftCouponDiscountType: 1, // 1.卡券类型: 1洗衣券 2免单券
  cardName: '', // 2.卡券名称
  // cardApplyChannel: [], // 卡券适用渠道
  subName: '', // 3.备注名
  subTitle: '', // 4.卡券副标题
  erpDemoCode: '', // demo券号
  cardColor: '#1890ff', //5.卡券颜色
  useCondition: null, // 6. 抵金券 减免金额; 折扣券 折扣额度
  cardLimit: 1,
  useCustomCode: 0,
  cardCodeCount: '',
  customCodeBegin: '',
  customCodeEnd: '',
  customCodePrefix: '',
  customCodeSuffix: '',
  useCodePrefix: 0,
  useCodeSuffix: 0,
  cardEffectiveMode: 0,
  giftCouponValue: 0, // 优惠内容
  dateTime: [], // 用户使用有效期
  sendDateTime: [], // 卡券模板投放期限
  putEffectiveMode: 1, // 卡券模板投放期限模式（0：固定日期，1：长期）
  manualGetFlag: 1, // 是否需要手动领取(0: 否, 1: 是)
  costValue: 0, //成本费用
  startDay: 0,
  limitDay: null,
  cardExplain: '',
  useDescript: '',
  // shelfIds: [],
  // verificationType: 0,
  cardDenomination: 0,
  proNoList: [],
  discount_amount_upper_limit: 0,
  goods_discounts_number_upper_limit: 0,
  products_exchange_number: 0,
  edxGoodsList: [], // e袋洗适用类目
  jumpFlag: 0, // 跳转配置开关(0: 关, 1: 开)
  jumpLink: {} // 卡券跳转链接json
};
const sale_limit = { fee: 0, goods: '', flag: false, type: 0 }; //最低消费
const goods = { ok: '', no: '', edx: false };
export default {
  // mixins: [xxSysp_mix],
  data() {
    const checkSendDateTime = (rule, value, callback) => {
      const { sendDateTime, cardEffectiveMode, dateTime, putEffectiveMode } = this.form;
      const isFixedMode = cardEffectiveMode == 0 || (cardEffectiveMode == 1 && putEffectiveMode == 0); // 是否是固定日期
      if (isFixedMode) {
        if (cardEffectiveMode == 0 && !(dateTime && dateTime[0])) {
          callback(new Error('请选择用户使用有效期'));
          return;
        }
        if (!(sendDateTime && sendDateTime[0])) {
          callback(new Error('请选择卡券模板投放期限'));
          return;
        }
        if (new Date(sendDateTime[1]).getTime() < getTimesByReq(new Date(), 1) && (this.isAdd || this.isCopy)) {
          callback(new Error('卡券模板投放期限开始时间不能大于当前时间'));
          return;
        }
        if (cardEffectiveMode == 0 && getTimesByReq(dateTime[1]) < getTimesByReq(sendDateTime[1])) {
          callback(new Error('卡券模板投放期限结束日期不能超出卡券使用有效期结束日期'));
          return;
        }
      }
      callback();
    };
    const that = this;
    return {
      requestProject: 'marketing',
      creatorId: '',
      canEdit: false,
      uuid: '',
      loading: false,
      submitLoading: false,
      // cardShelfsLoading: false, //卡券展架loading
      form: JSON.parse(JSON.stringify(initForm)),
      sale_limit: JSON.parse(JSON.stringify(sale_limit)),
      goods: JSON.parse(JSON.stringify(goods)),
      only: false,
      // e袋洗适用类目
      ableCategoryVisible: false,
      cardLimitRadio: 1,
      rules: {
        // cardApplyChannel: { required: true, type: 'array', message: '请选择卡券渠道', trigger: 'change' },
        cardName: { required: true, message: '请输入卡券名称', trigger: 'blur' },
        subName: { required: true, message: '请输入备注名称', trigger: 'blur' },
        subTitle: { required: true, message: '请输入卡券副标题', trigger: 'blur' },
        cardColor: { required: true, message: '请设置卡券颜色', trigger: 'change' },
        cardCodeCount: { required: true, type: 'number', min: 1, message: '请输入库存', trigger: 'blur' }, // 库存
        giftCouponValue: { required: true, type: 'number', min: 1, message: '请输入优惠内容', trigger: 'blur' },
        // costValue: [{ required: true, message: '请输入成本费用', trigger: 'blur' }],
        cardDenomination: [
          { required: true, message: '请输入减免金额', trigger: 'blur' },
          { type: 'number', min: 1, message: '请输入大于0的整数', trigger: 'blur' }
        ],
        cardExplain: { required: true, message: '适用门店说明不能为空', trigger: 'blur' },
        useDescript: { required: true, message: '使用说明不能为空', trigger: 'blur' },
        sendDateTime: { required: true, validator: checkSendDateTime, trigger: 'change' }
      },
      startDayOptions: [],
      // cardApplyChannelOptions: [],
      imgTextList: [],
      cardShelfsList: [],
      sendChildData: {
        storeType: 0,
        storeGroupIds: '',
        storeIds: []
      },
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      pickerOptions2: {
        disabledDate(val) {
          const min = Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
          if (that.form.cardEffectiveMode == 0 && that.form.dateTime && that.form.dateTime[1]) {
            // 卡券有效期-固定日期    ---> 最大时间不能超出该结束时间
            const max = val.getTime() > new Date(that.form.dateTime[1]).getTime();
            return max || min;
          }
          return min;
        }
      },
      isEdit: this.$route.meta.type === 'edit',
      isInfo: this.$route.meta.type === 'info',
      isCopy: this.$route.meta.type === 'copy',
      isAdd: this.$route.meta.type === 'add',
      storeMode: 0,
      // 兑换商品货号是否展示
      products_exchange_number_show: false,
      goodsDiscountCheck: true,
      discountAmountCheck: true
    };
  },
  watch: {
    'goods.edx'(val) {
      if (!val) {
        this.form.edxGoodsList = [];
        if (this.$refs.category) {
          this.$refs.category.value = [];
        }
      }
    },
    'sale_limit.flag'(val) {
      if (!val) {
        this.sale_limit.type = 0;
        this.sale_limit.goods = null;
        this.sale_limit.fee = null;
      }
    },
    'form.proNoList'(val) {
      this.products_exchange_number_show = !!val.length;
      this.form.products_exchange_number = val.length ? 1 : 0;
    },
    discountAmountCheck(val) {
      if (val) {
        this.form.discount_amount_upper_limit = 0;
      } else if (this.form.discount_amount_upper_limit <= 0) {
        this.form.discount_amount_upper_limit = 1;
      }
    },
    goodsDiscountCheck(val) {
      if (val) {
        this.form.goods_discounts_number_upper_limit = 0;
      } else if (this.form.goods_discounts_number_upper_limit <= 0) {
        this.form.goods_discounts_number_upper_limit = 1;
      }
    },
    'form.discount_amount_upper_limit': {
      handler(val) {
        this.discountAmountCheck = val <= 0;
      },
      immediate: true
    },
    'form.goods_discounts_number_upper_limit': {
      handler(val) {
        this.goodsDiscountCheck = val <= 0;
      },
      immediate: true
    }
  },
  components: {
    'dm-upload-img': dmUploadImg,
    // 'img-text-drag': imgTextDrag,
    'dm-goods-input': dmGoodsInput,
    'good-category': goodCategory
  },
  computed: {
    asideShow() {
      return this.$store.state.marketing.asideShow;
    },
    storeParams() {
      return !this.isAdd ? { creatorId: this.creatorId } : {};
    },
    // 是否展示模板投放有效期
    showSendDateTime() {
      // 当输入完整用户使用有效期后，出现卡券模板投放期限
      const { cardEffectiveMode, limitDay, dateTime } = this.form;
      if (cardEffectiveMode == 0) {
        return !!(dateTime && dateTime[0] && dateTime[1]);
      }
      if (cardEffectiveMode == 1) {
        return !!limitDay;
      }
      return false;
    }
  },
  methods: {
    // 下载明细
    downloadMX() {
      const prev = process.env['NODE_ENV'] === 'development' ? '' : '/marketing'; // eslint-disable-line
      window.open(`${prev}/static/file/e袋洗运费标准.xlsx`, '_blank');
    },
    /** e袋洗 */
    saveAbleCategory() {
      const edxGoodsList = this.$refs.category.getCategory();
      if (edxGoodsList.length === 0) {
        this.$tips({ message: '请先选择适用类目', type: 'error' });
        return;
      }
      this.form.edxGoodsList = edxGoodsList;
      this.ableCategoryVisible = false;
    },
    // changeDateTime
    setSendDateTime(dateTime) {
      if (dateTime && dateTime[0]) {
        this.form.sendDateTime = [...dateTime];
      }
    },
    // 重新校验时间
    reCheckSendDateTime() {
      this.$nextTick(() => {
        this.$refs.form.validateField('sendDateTime');
      });
    },
    // 改变用户使用有效期类型
    changeCardEffectiveMode(val, cover = true) {
      this.reCheckSendDateTime();
      const { dateTime, sendDateTime } = this.form;
      if (!cover && sendDateTime && sendDateTime[0]) {
        return;
      }
      // cover: true直接覆盖  false sendDateTime有值就不覆盖
      if (val == 0) {
        // 卡券模板投放期限
        // 用户使用有效期=固定日期，则默认卡券模板投放期限开始时间=今天，结束日期=用户使用有效期结束日期
        if (dateTime && dateTime[0]) {
          this.setSendDateTime([new Date(), dateTime[1]]);
          return;
        }
      }
      if (val == 1) {
        this.form.putEffectiveMode = 1;
      }
      this.form.sendDateTime = [,];
    },
    /** e袋洗 */
    //切换卡券类型  表单置为默认值
    reset(e) {
      this.form = JSON.parse(JSON.stringify(initForm));
      this.sale_limit = JSON.parse(JSON.stringify(sale_limit));
      this.goods = JSON.parse(JSON.stringify(goods));
      this.form.cardType = e;
      this.$nextTick(_ => {
        this.$refs.storeCard.initLeftList();
      });
      this.goodsList = [{ v1: '', f2: [], v2: '', f3: [], v3: [], list: [] }];
      // 新增情况下，如果配置了线下门店，默认选中线下门店
      // if (this.isAdd && this.cardApplyChannelOptions.some(v => v.value === 'offlineStore')) {
      //   this.form.cardApplyChannel = ['offlineStore'];
      // }
    },
    //卡券营销--卡券库--新建/编辑卡券/卡券记录-领取记录-点击卡券查看详情
    async getCardDetail() {
      this.loading = true;
      let res = await getCardDetail({ coupCardId: this.$route.params.id });
      if (this.isEdit) {
        this.creatorId = res.result.card.creatorId;
      }
      // 是否是本人
      this.canEdit = res.result.canEdit !== false;
      // if (this.isCopy) {
      //   res = await copyCardDetailService({ coupCardId: this.$route.params.id });
      // } else {
      // res = await getCardDetail({ coupCardId: this.$route.params.id });
      // }
      if (res.errorCode === 0) {
        //处理有效期下拉选项
        const dicMap = res.result.dicMap;
        this.startDayOptions = Object.keys(dicMap).map(key => ({ label: dicMap[key].dictName == '0' ? '当天' : '第' + dicMap[key].dictName + '天', value: parseInt(dicMap[key].dictName) }));
        if (res.result.card) {
          const card = res.result.card;
          this.storeMode = card.storeMode === 0 ? 0 : 1;
          // this.form.cardApplyChannel = card.cardApplyChannel ? card.cardApplyChannel.split(',') : [];
          // ****卡券多的字段******
          this.form.gicCouponType = card.gicCouponType;
          this.form.giftCouponDiscountType = card.giftCouponDiscountType;
          this.form.giftCouponValue = card.giftCouponValue;
          // ****卡券多的字段******
          this.form.auditingStatus = card.auditingStatus || '';
          this.form.coupCardId = this.isCopy ? '' : card.coupCardId;
          this.form.cardType = card.cardType;
          this.form.cardName = card.cardName || '';
          this.form.subName = card.subName || '';
          this.form.subTitle = card.subTitle || '';
          this.form.erpDemoCode = card.erpDemoCode || '';
          this.form.cardColor = card.cardColor;
          this.form.cardDenomination = card.cardDenomination || 0;
          this.form.giftCouponValue = card.giftCouponValue || 0;

          if (card.edxGoodsList) {
            this.goods.edx = true;
            this.form.edxGoodsList = JSON.parse(card.edxGoodsList) || []; // e袋洗适用商品
          }
          if (card.useCondition) {
            const useCondition = (this.form.useCondition = JSON.parse(card.useCondition));
            this.sale_limit.fee = useCondition.sale_limit ? useCondition.sale_limit.fee || 0 : 0;
            this.sale_limit.goods = useCondition.sale_limit ? useCondition.sale_limit.goods || '' : '';
            this.sale_limit.flag = this.sale_limit.fee || this.sale_limit.goods;
            if (this.sale_limit.fee) {
              this.sale_limit.type = 1;
              this.sale_limit.flag = true;
            } else if (this.sale_limit.goods) {
              this.sale_limit.type = 2;
            } else {
              this.sale_limit.type = 0;
            }
            this.goods.ok = useCondition.goods ? useCondition.goods.ok || '' : '';
            this.goods.no = useCondition.goods ? useCondition.goods.no || '' : '';
            this.form.goods_discounts_number_upper_limit = useCondition.goods_discounts_number_upper_limit || 0;
            this.form.discount_amount_upper_limit = useCondition.discount_amount_upper_limit || 0;
            this.form.products_exchange_number = useCondition.products_exchange_number || 0;
            if (this.goods.ok || this.goods.no) {
              // this.goods.flag = true;
            }
            this.only = !!useCondition.only || false;
            this.form.proNoList = useCondition.proNo ? [{ name: useCondition.proNo, id: useCondition.proNo }] : [];
          }

          this.form.cardLimit = card.cardLimit;
          if (this.form.cardLimit === 1) {
            this.cardLimitRadio = 1;
          } else if (this.form.cardLimit === 100) {
            this.cardLimitRadio = 100;
          } else {
            this.cardLimitRadio = 0;
          }
          this.form.useCustomCode = card.useCustomCode;
          if (this.isCopy && this.form.useCustomCode === 1) {
            this.form.customCodeBegin = '';
            this.form.customCodeEnd = '';
            this.form.customCodePrefix = '';
            this.form.customCodeSuffix = '';
            this.form.useCodePrefix = 0;
            this.form.useCodeSuffix = 0;
          } else {
            this.form.customCodeBegin = card.customCodeBegin;
            this.form.customCodeEnd = card.customCodeEnd;
            this.form.customCodePrefix = card.customCodePrefix;
            this.form.customCodeSuffix = card.customCodeSuffix;
            this.form.useCodePrefix = card.useCodePrefix || 0;
            this.form.useCodeSuffix = card.useCodeSuffix || 0;
          }
          this.form.cardCodeCount = card.cardCodeCount;
          this.form.costValue = card.costValue || 0;
          this.form.cardExplain = card.cardExplain || '';
          this.form.useDescript = card.useDescript || '';
          // this.form.coverDescript = card.coverDescript || '';
          if (!this.isCopy) {
            // 非复制才赋值有效期，跳转链接
            this.form.cardEffectiveMode = card.cardEffectiveMode;
            this.form.putEffectiveMode = card.putEffectiveMode;
            this.form.jumpFlag = card.jumpFlag || 0;
            try {
              this.form.jumpLink = card.jumpFlag ? JSON.parse(card.jumpLink) : {};
              // 处理jumpLink错误的情况
            } catch (error) {
              console.log('jumpLink解析错误');
            }
            this.form.dateTime = [card.beginDate || '', card.endDate || ''];
            this.form.sendDateTime = [card.putBeginDate || '', card.putEndDate || ''];
            this.form.startDay = card.startDay || 0;
            this.form.limitDay = card.limitDay || 0;
          }

          this.form.manualGetFlag = card.manualGetFlag || 1;
          this.uuid = card.storeWidgetKey || '';
          this.$nextTick(_ => {
            // console.log(this.$refs.storeCard);
            this.$refs.form.clearValidate();
          });
          // this.form.coverDescript = card.coverDescript || '';
          this.uuid = card.storeWidgetKey || '';
          this.$nextTick(_ => {
            this.$refs.storeCard.init();
          });
        }
      } else {
        this.$tips({ type: 'error', message: '初始化数据失败' });
      }
      this.loading = false;
    },
    //提交保存
    async submitForm(formName) {
      if (!this.$store.state.marketing.appletEnable) {
        return;
      }

      const { sendDateTime, cardEffectiveMode, dateTime, putEffectiveMode } = this.form;
      if (cardEffectiveMode == 0 || (cardEffectiveMode == 1 && putEffectiveMode == 0)) {
        if (cardEffectiveMode == 0 && !(dateTime && dateTime[0])) {
          this.$tips({ type: 'warning', message: '请选择用户使用有效期' });
          return;
        }
        if (!(sendDateTime && sendDateTime[0])) {
          this.$tips({ type: 'warning', message: '请选择卡券模板投放期限' });
          return;
        }
        if (new Date(sendDateTime[1]).getTime() < getTimesByReq(new Date(), 1) && (this.isAdd || this.isCopy)) {
          this.$tips({ type: 'warning', message: '卡券模板投放期限开始时间不能大于当前时间' });
          return;
        }
        if (cardEffectiveMode == 0 && getTimesByReq(dateTime[1]) < getTimesByReq(sendDateTime[1])) {
          this.$tips({ type: 'warning', message: '卡券模板投放期限结束日期不能超出卡券使用有效期结束日期' });
          return;
        }
      }

      // add e袋洗使用类目
      if (this.goods.edx && this.form.edxGoodsList.length === 0) {
        this.$tips({ type: 'warning', message: '选择适用类目' });
        return;
      }

      //验证有效期
      if (this.form.cardEffectiveMode) {
        if (!this.form.limitDay) {
          this.$tips({ type: 'warning', message: '有效期必填' });
          return;
        }
      } else {
        if (!this.form.dateTime || !this.form.dateTime[0]) {
          this.$tips({ type: 'warning', message: '用户使用有效期必填' });
          return;
        }
      }

      // if (this.form.jumpFlag && JSON.stringify(this.form.jumpLink) == '{}') {
      //   this.$tips({ type: 'warning', message: '请配置跳转链接' });
      //   return;
      // }

      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveUpdateCard();
        } else {
          this.$tips({ type: 'warning', message: '表单提交错误，请检查表单是否填写完整' });
          return false;
        }
      });
    },
    //卡券营销--卡券库--保存卡券
    async saveUpdateCard() {
      if (this.submitLoading) {
        return;
      }

      let card = {};
      let params = {};
      // card.cardApplyChannel = this.form.cardApplyChannel.join(',');
      // *****e袋洗多的字段*****
      card.gicCouponType = this.form.gicCouponType;
      card.giftCouponDiscountType = this.form.giftCouponDiscountType;
      card.giftCouponValue = this.form.giftCouponValue;
      // *****e袋洗多的字段*****

      card.coupCardId = this.form.coupCardId;
      card.cardType = this.form.cardType;
      card.cardName = this.form.cardName;
      card.subName = this.form.subName;
      card.subTitle = this.form.subTitle;
      card.erpDemoCode = this.form.erpDemoCode;
      card.cardColor = this.form.cardColor;
      card.cardDenomination = this.form.cardDenomination;
      // card.coverDescript = this.form.coverDescript;
      card.useCodePrefix = this.form.useCodePrefix;
      card.useCodeSuffix = this.form.useCodeSuffix;
      // 写死  e袋洗没有使用条件
      card.useCondition = {
        sale_limit: {
          fee: 0,
          goods: ''
        },
        goods: {
          ok: '',
          no: ''
        },
        only: 0,
        proNo: '',
        products_exchange_number: 0
      };
      if (this.only) {
        card.useCondition.only = Number(this.only);
      }

      // e袋洗适用商品
      if (this.goods.edx) {
        card.edxGoodsList = JSON.stringify(this.form.edxGoodsList);
      }
      //卡券限制
      if (this.cardLimitRadio === 1) {
        card.cardLimit = 1;
      } else if (this.cardLimitRadio === 100) {
        card.cardLimit = 100;
      } else {
        card.cardLimit = this.form.cardLimit;
      }

      card.useCustomCode = this.form.useCustomCode;
      card.costValue = this.form.costValue || 0;
      card.cardCodeCount = this.form.cardCodeCount;
      // 用户使用有效期
      card.cardEffectiveMode = this.form.cardEffectiveMode;
      if (card.cardEffectiveMode === 0) {
        if (!this.form.dateTime) {
          card.beginDate = card.endDate = '';
        } else {
          card.beginDate = formatDateTimeByType(this.form.dateTime[0], 'yyyy-MM-dd');
          card.endDate = formatDateTimeByType(this.form.dateTime[1], 'yyyy-MM-dd');
        }
      } else {
        card.startDay = this.form.startDay || 0;
        card.limitDay = this.form.limitDay || 0;
      }

      // 卡券模板投放期限  putEffectiveMode（0：固定日期，1：长期）
      const { cardEffectiveMode, putEffectiveMode, sendDateTime } = this.form;
      card.putEffectiveMode = cardEffectiveMode == 0 || (cardEffectiveMode == 1 && putEffectiveMode == 0) ? 0 : 1;
      if (card.putEffectiveMode == 0) {
        // 固定日期
        card.putBeginDate = formatDateTimeByType(sendDateTime[0], 'yyyy-MM-dd');
        card.putEndDate = formatDateTimeByType(sendDateTime[1], 'yyyy-MM-dd');
      }

      card.jumpFlag = this.form.jumpFlag;
      card.jumpLink = card.jumpFlag ? this.form.jumpLink : {};

      card.cardExplain = this.form.cardExplain;
      card.useDescript = this.form.useDescript;

      card.isDisable = true;
      card.notApplicableMode = 0;
      card.notApplicableProMode = 0;
      card.notApplicableStoreProMode = 0;
      card.proMode = 0;
      card.customCodeSync = 0;
      card.changeStock = 0;
      card.channelType = 1;
      card.checkSource = 0;
      card.applicableMode = 0;
      card.storeProMode = 0;
      card.storeMode = this.storeMode;
      card.storeWidgetKey = this.uuid;
      card.manualGetFlag = 1; // 永远都设置为 手动开启
      // 这里判断部分门店是否为空
      if (card.storeMode) {
        let data = await this.$refs.storeCard.getRightList();
        // console.log(this.$refs.storeCard.newUuid);
        // console.log(this.uuid);
        if (!data.length) {
          this.$tips({ type: 'warning', message: '部分门店不能为空' });
          return;
        }
      }
      console.log('======');
      console.log(card);
      console.log('======');
      params.card = JSON.stringify(card);
      this.submitLoading = true;
      saveUpdateCard(params)
        .then(res => {
          this.submitLoading = false;
          if (res.errorCode === 0) {
            if (this.isEdit) {
              this.$confirm('保存成功, 是否返回列表?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  this.$router.push('/ewash/list');
                })
                .catch(err => {
                  this.getCardDetail();
                });
            } else {
              this.$tips({ type: 'success', message: '新建卡券成功' });
              this.$router.push('/ewash/list');
            }
          } else {
            this.$tips({ type: 'error', message: res.message || '保存卡券失败' });
          }
        })
        .catch(err => {
          this.submitLoading = false;
          this.$tips({ type: 'error', message: '保存卡券失败' });
        });
    },
    //门店分组回执方法
    getSelectGroupData(val) {
      this.sendChildData.storeType = val.storeType || 0;
      this.sendChildData.storeGroupIds = val.storeGroupIds || '';
      this.sendChildData.storeIds = val.storeIds || [];
    },
    //检查是否为数字
    checkInputNumber(val, name) {
      this.form[name] = (val.replace(/[^0-9]*/g, '') + '').substr(0, 16);
      if (parseInt(this.form.customCodeEnd) - parseInt(this.form.customCodeBegin) < 0) {
        this.form.customCodeEnd = this.form.customCodeBegin;
        this.$tips({ type: 'warning', message: '自定义结尾号段不能小于初始号段' });
      }
      if (parseInt(this.form.customCodeEnd) - parseInt(this.form.customCodeBegin) + 1 > 100000) {
        this.$tips({ type: 'warning', message: '创建数量不能大于100,000张' });
        // this.form.customCodeEnd  = this.form.customCodeBegin  = 0;
        return;
      }
    },
    //检查是否为字符串
    checkInputString(val, name) {
      this.form[name] = val.replace(/[^a-zA-Z0-9]*/g, '') + '';
    },
    // ------微盟适用商品开始-------
    // 获取第一层数据
    getCategoryList() {
      getCategoryList({
        requestProject: this.requestProject
      }).then(res => {
        // console.log(res);
        this.f1 = res.result.map(v => {
          return {
            title: v.parentName + ' > ' + v.categoryName,
            id: v.categoryId
          };
        });
      });
    },
    // 增加一行
    addLine() {
      if (this.wmloading) {
        return;
      }
      this.goodsList.push({ v1: '', f2: [], v2: '', f3: [], v3: [], list: [] });
    },
    // 删除一行
    delLine(idx) {
      if (this.wmloading) {
        return;
      }
      this.goodsList.splice(idx, 1);
      if (this.goodsList.length === 0) {
        this.goodsList.push({ v1: '', f2: [], v2: '', f3: [], v3: [], list: [] });
      }
    },
    // 获取isCopy状态下的一行数据
    async getLine(idx) {
      if (this.wmloading) {
        return;
      }
      // 锁定不允许增加删除行影响index
      this.wmloading = true;
      // 获取第二层数据
      const res_f2 = await getPropertyList({
        requestProject: this.requestProject,
        categoryId: this.goodsList[idx].v1
      });
      this.goodsList[idx].f2 = res_f2.result.map(v => {
        return {
          title: v.propertyName,
          id: v.propertyId,
          outPropertyId: v.outPropertyId
        };
      });
      // 获取第三层数据
      const res_f3 = await getPropertyValueList({
        requestProject: this.requestProject,
        propertyId: this.goodsList[idx].v2
      });
      this.goodsList[idx].f3 = res_f3.result.map(v => {
        return {
          title: v.valueName,
          id: v.valueId,
          outValueId: v.outValueId
        };
      });
      // 去除isCopy，loading
      this.wmloading = false;
      this.goodsList[idx].isCopy = undefined;
    },
    // 第一层改变 获取第二层数据
    handleF1Change(v, idx) {
      if (this.wmloading) {
        return;
      }
      // 把isCopy属性去除
      if (this.isCopy && this.goodsList[idx].isCopy) {
        this.goodsList[idx].isCopy = undefined;
      }
      this.goodsList[idx].v2 = '';
      this.goodsList[idx].f2 = [];
      this.goodsList[idx].v3 = [];
      this.goodsList[idx].f3 = [];
      this.goodsList[idx].v3name = [];
      if (v) {
        this.goodsList[idx].v1name = this.f1.find((value, index, array) => value.id === v).title;
        getPropertyList({
          requestProject: this.requestProject,
          categoryId: this.goodsList[idx].v1
        }).then(res => {
          this.goodsList[idx].f2 = res.result.map(v => {
            return {
              title: v.propertyName,
              id: v.propertyId,
              outPropertyId: v.outPropertyId
            };
          });
        });
      } else {
        this.goodsList[idx].v1name = '';
      }
    },
    // 第二层改变 获取第三层数据
    handleF2Change(v, idx) {
      if (this.wmloading) {
        return;
      }
      this.goodsList[idx].v3 = [];
      this.goodsList[idx].f3 = [];
      this.goodsList[idx].v3name = [];
      if (v) {
        this.goodsList[idx].v2name = this.goodsList[idx].f2.find((value, index, array) => value.id === v).title;
        getPropertyValueList({
          requestProject: this.requestProject,
          propertyId: this.goodsList[idx].v2
        }).then(res => {
          this.goodsList[idx].f3 = res.result.map(v => {
            return {
              title: v.valueName,
              id: v.valueId,
              outValueId: v.outValueId
            };
          });
        });
      } else {
        this.goodsList[idx].v2name = '';
      }
    },
    // 校验&&组合数据
    handleCombine() {
      if (this.wmloading) {
        return;
      }
      return new Promise((resolve, reject) => {
        let arr_f2 = [];
        const goodsList = this.goodsList;
        if (goodsList.length === 1 && goodsList[0].v1 === '' && goodsList[0].v2 === '' && goodsList[0].v3.length === 0) {
          resolve('empty');
        }
        // 判断是否未填满
        for (let i = 0, len = goodsList.length; i < len; i++) {
          if (goodsList[i].v1 === '' || (goodsList[i].f2.length && goodsList[i].v2 === '') || (goodsList[i].f3.length && goodsList[i].v3.length === 0)) {
            reject(new Error('微盟适用商品填写不完整'));
          }
          arr_f2.push(goodsList[i].v2);
        }
        // 判断第二层是否有重复
        if (arr_f2.length !== [...new Set(arr_f2)].length) {
          reject(new Error('微盟适用商品参数重复'));
        }
        resolve();
      })
        .then(res => {
          if (res === 'empty') return 1;
          return this.goodsList.map(v => {
            let outPropertyId = ''; // 寻找 outPropertyId_outValueId
            for (let ii = 0, lenn = v.f2.length; ii < lenn; ii++) {
              if (v.f2[ii].id === v.v2) {
                outPropertyId += v.f2[ii].outPropertyId + '_';
                break;
              }
            }

            // 第三层映射 push键值对
            const propValues = v.v3.map(y => {
              let idx = -1;
              for (let i = 0, len = v.f3.length; i < len; i++) {
                if (v.f3[i].id === y) {
                  idx = i;
                  break;
                }
              }
              return {
                valueId: v.f3[idx].id,
                valueName: v.f3[idx].title,
                relationIds: outPropertyId + v.f3[idx].outValueId
              };
            });
            v.v3name = propValues;
            return {
              categoryId: v.v1,
              categoryName: v.v1name,
              propId: v.v2,
              propName: v.v2name,
              propValues
            };
          });
        })
        .catch(err => {
          this.$tips({ type: 'warning', message: err.message });
          return false;
        });
    },
    // ------微盟适用商品结束-------
    // ---------链接小工具---------
    linkSelect(val) {
      if (!this.isInfo) {
        this.form.jumpLink = val;
      }
    }
  },
  mounted() {
    // this.cardGetShelfs();
    this.getCardDetail();
    this.getCategoryList(); // 获取适用商品第一层数据
    if (this.isAdd) {
      this.$refs.storeCard.init();
    }
  },
  created() {
    this.$store.commit('mutations_breadcrumb', [{ name: 'e袋洗服务', path: '' }, { name: '服务列表', path: '/ewash/list' }, { name: `${this.isAdd ? '新增' : '编辑'}卡券`, path: '' }]); // eslint-disable-line
  }
};
