/**
 * 卡券新增编辑
 */
import { _debounce } from '@/utils/index';
import dmUploadImg from '@/components/upload/img';
import linktools from '@/components/linktools-fulls/index';
import dmUploadAvatar from '@/components/upload/avatar';
import sendPreview from './partials/send-preview';
import { formatDateTimeByType, deepClone, getTimesByReq } from '@/utils/index.js';
import xxSysp_mix from '@/mixins/selector.js'; // 商品选择器方法
import { listEntepriseWeimobShop, listEntepriseWeimobCoupon } from '@/service/api/commonApi.js';
import { getCardDetail, saveUpdateCard, copyCardDetailService, getCardManualSetting, getCategoryList, getPropertyList, getLatestReptileTime, getPropertyValueList, getWeimobCouponBindCount, getCardEffectiveMode, getStoreWidgetStore, importCostStore } from '@/service/api/cardApi.js';
import dmGoodsInput from '@/components/goods-input/index.vue';
import { getLinkResourceStatus } from '@/service/api/ecmApi.js';
import { RecycleScroller } from 'vue-virtual-scroller';
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css';
const initForm = {
  auditingStatus: '',
  cardType: 0, // 1.卡券类型: 抵金券: 0; 折扣券: 1; 兑换券: 2
  cardName: '', // 2.卡券名称
  cardApplyChannel: [], // 卡券适用渠道
  channelTip: '',
  subName: '', // 3.备注名
  subTitle: '', // 4.卡券副标题
  erpDemoCode: '', // demo券号
  cardColor: '#2f54eb', //5.卡券颜色
  useCondition: null, // 6. 抵金券 减免金额; 折扣券 折扣额度
  cardLimit: 1,
  useCustomCode: 0,
  cardCodeCount: 100000,
  customCodeBegin: '',
  customCodeEnd: '',
  customCodePrefix: '',
  customCodeSuffix: '',
  useCodePrefix: 0,
  useCodeSuffix: 0,
  cardEffectiveMode: 0,
  dateTime: [], // 用户使用有效期
  sendDateTime: [], // 卡券模板投放期限
  putEffectiveMode: 1, // 卡券模板投放期限模式（0：固定日期，1：长期）
  manualGetFlag: 1, // 是否需要手动领取(0: 否, 1: 是)
  costValue: 0, //成本费用
  startDay: 0,
  limitDay: null,
  cardExplain: '',
  // image: {
  //   imgUrl: '',
  //   code: ''
  // },
  // coverDescript: '',
  useDescript: '不可与其他卡券叠加使用，详询门店',
  // shelfIds: [],
  verificationType: 0,
  cardDenomination: 0,
  proNoList: [],
  discount_amount_upper_limit: 0,
  goods_discounts_number_upper_limit: 0,
  goods_discounts_number_lower_limit: 0,
  products_exchange_number: 0,
  onlyFlag: true, // 是否显示与优惠同享，默认true显示
  refundFlag: 0, // 开启退货 1开启
  jumpFlag: 0, // 跳转配置开关(0: 关, 1: 开)
  jumpLink: {}, // 卡券跳转链接json

  giveFlag: 0, // 开启转赠  1开启
  giveContent: '',
  giveImage: 'https://pic01-10001430.image.myqcloud.com/44d68224-d0a3-4f87-81d6-ad564f9d7bc8',
  giveImageField: '44d68224-d0a3-4f87-81d6-ad564f9d7bc8',
  bannerImage: 'https://pic01-10001430.image.myqcloud.com/015f1e5a-3b2f-42f5-b638-6a29c17e8f7e',
  bannerImageField: '015f1e5a-3b2f-42f5-b638-6a29c17e8f7e',
  useJumpFlag: 0, // (0: 不跳转, 1: 跳转)
  bannerJumpUrl: {},
  giveRule: '1.卡券新老用户同享。\n2.用户使用卡券下单，订单取消后，卡券将自动失效',
  wmCouponJson: {},
  wmCouponFlag: 0,
  useCardCodePrefix: 0, //code类型随机生时 前缀复选框的值
  cardCodePrefix: '', // code类型随机生成 前缀值
  costValueProportionFlag: 1, // 卡券成本比例 1：开 0：关
  costValueType: 0, // 成本费用 0：固定成本 1：门店成本
  costValueProportion: undefined, // 成本比例
  only: true // 默认优惠不共享 true
};
const sale_limit = { fee: 0, goods: '', flag: false, type: 0 }; //最低消费
const goods = { ok: '', no: '', flag: false };

// 禁止回车
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
    }
  }
};
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 validGiveContent = (rule, value, callback) => {
      if (this.form.giveFlag && !value) {
        callback(rule.message);
      }
      callback();
    };

    const validCardDenomion = (rule, value, callback) => {
      if ((this.isAdd || this.isCopy) && value < 1) {
        callback('请输入大于0的整数');
        return;
      }
      callback();
    };
    // 验证首图 转赠链接
    const validBannerJumpUrl = (rule, value, callback) => {
      if (this.form.useJumpFlag && JSON.stringify(this.form.bannerJumpUrl) == '{}') {
        callback(new Error('请选择首图跳转链接'));
      }
      callback();
    };
    const validCardCodePrefix = (rule, value, callback) => {
      if (this.form.useCardCodePrefix && !value) {
        callback(new Error('请输入卡券code前缀'));
      }
      callback();
    };
    const that = this;
    return {
      storeUuid: '',
      // 商场抵金券适用门店-部分门店列表数据
      originStoreList: [],
      // 商场抵金券适用门店-门店选择器选中的数据
      selectedStoreList: [],
      searchStore: '',
      sortType: undefined,
      importCost: {
        visible: false,
        loading: false,
        costStoreList: [],
        options: {
          desc: '文件条数单次不超过5000条，上传文件不可大于2M，支持XLSX、XLS',
          maxSize: 2097152,
          maxSizeDesc: '2M',
          accept: ['.xlsx', '.xls'],
          downloadTemplate: [
            {
              url: '/api-marketing/download-import-cost-store?requestProject=marketing',
              name: '下载模板'
            }
          ]
        }
      },
      isEffective: false,
      requestProject: 'marketing',
      gicCouponType: '', // gic定义的卡券类型(0:普通卡券, 1:e待洗, 2:好办卡券, 3:微盟外部券, 4:通用外部券
      creatorId: '',
      uuid: '',
      currentPage: 1,
      pageSize: 50,
      wmPid: '',
      idx: '',
      totalPage: 0,
      canEdit: false,
      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)),
      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' },
        // costValue: [{ message: '请输入成本费用', trigger: 'blur' }],
        cardDenomination: [
          { required: true, message: '请输入减免金额', trigger: 'blur' },
          { validator: validCardDenomion, trigger: 'change' }
        ],
        cardExplain: { required: true, message: '适用门店说明不能为空', trigger: 'blur' },
        useDescript: { required: true, message: '使用说明不能为空', trigger: 'blur' },
        sendDateTime: { required: true, validator: checkSendDateTime, trigger: 'change' },
        giveContent: { validator: validGiveContent, message: '请输入转赠对话框文字', trigger: 'blur' },
        // giveRule: { required: true, message: '请输入卡券转赠规则', trigger: 'blur' },
        // giveImage: { required: true, message: '请上传转赠封面', trigger: 'change' },
        // bannerImage: { required: true, message: '请上传转赠页面首图', trigger: 'change' },
        bannerJumpUrl: { validator: validBannerJumpUrl, trigger: 'change' },
        costValueProportion: { required: true, message: '请输入门店成本比例', trigger: 'blur' },
        cardCodePrefix: { validator: validCardCodePrefix, 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,
      goodsDiscountCheckLower: true,
      discountAmountCheck: true,
      // 自动领取设置
      couponAutoGetFlag: 0, // 1开启自动领取 0关闭
      couponAutoGetStock: 0, // 自动领取最大库存数
      // ----微盟适用商品----
      f1: [], // 一层的list
      wmloading: false,
      goodsList: [
        {
          v1: '', // id
          v1name: '',
          f2: [], // 二层的数据
          v2: '',
          v2name: '',
          f3: [], // 三层的数据
          v3: '',
          v3name: []
        }
      ],
      coupGoodsWeimobList: [],
      cardCodePrefixFlag: 0, // 是否 code类型随机生成时 展示 前缀
      // ----微盟适用商品结束----
      wmShopAddDisabled: true, // 添加店铺是否可用
      wmShopIds: [], // 保存过的店铺id不能重复选择
      countFlag: 0, // 微盟店铺  0不能使用  1只能添加1条  2能添加多条
      weimobShopList: [], // 微盟适用商品最新同步时间
      weimobDemoCodeList: [{ pid: '', card: '', loading: false, cardList: [], save: false, cardName: '', useCount: 0 }], // 保存的微盟店铺以及对应的微盟券号 {pid:xxxx,card:xxxx,loading:false, cardList: [], save: false, name: ''}
      latestReptileTime: '', // latestReptileTime
      // cardValidity: false, // 卡券有效期是否禁用
      nowWmShopData: {}, // 存储wm店铺数据
      giveEnable: false, // 支持转赠
      refundEnable: false, // 支持退货
      discount_limit: { type: 1, count: undefined, flag: false }, // 适用商品折扣
      linkToolsVisible: false, // 链接小工具 - 跳转链接
      linkToolsVisible2: false, // 链接小工具 - 转赠
      // 转赠预览
      preview: {
        visible: false,
        disabled: true
      },
      giveImg1: {
        // 转赠对话框图片
        code: '44d68224-d0a3-4f87-81d6-ad564f9d7bc8',
        imgUrl: 'https://pic01-10001430.image.myqcloud.com/44d68224-d0a3-4f87-81d6-ad564f9d7bc8'
      },
      giveImg2: {
        // 转赠页面首图
        code: '015f1e5a-3b2f-42f5-b638-6a29c17e8f7e',
        imgUrl: 'https://pic01-10001430.image.myqcloud.com/015f1e5a-3b2f-42f5-b638-6a29c17e8f7e'
      },
      showWeimobDemoSelector: false,
      statusText: ''
    };
  },
  // directives: {
  //   loadmore: {
  //     inserted(el, binding) {
  //       const SELECTDOWN_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
  //       SELECTDOWN_DOM.addEventListener('scroll', function() {
  //         const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
  //         if (CONDITION) {
  //           binding.value();
  //         }
  //       });
  //     }
  //   }
  // },
  watch: {
    'form.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);
      }
    },
    giveImg1: {
      handler(val) {
        this.form.giveImage = val.imgUrl;
        this.form.giveImageField = val.code;
      },
      deep: true
    },
    giveImg2: {
      handler(val) {
        this.form.bannerImage = val.imgUrl;
        this.form.bannerImageField = val.code;
      },
      deep: true
    },
    form: {
      handler(val) {
        const { giveFlag, giveContent, giveImage, bannerImage, giveRule } = val;
        this.preview.disabled = giveFlag && giveContent && giveImage && bannerImage && giveRule;
      },
      deep: true
    },
    '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;
      }
    },
    goodsDiscountCheckLower(val) {
      if (val) {
        this.form.goods_discounts_number_lower_limit = 0;
      } else if (this.form.goods_discounts_number_lower_limit <= 0) {
        this.form.goods_discounts_number_lower_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
    },
    'form.goods_discounts_number_lower_limit': {
      handler(val) {
        this.goodsDiscountCheckLower = val <= 0;
      },
      immediate: true
    },
    cardValidity(val) {
      const now = this.nowWmShopData;
      if (val && JSON.stringify(now) !== '{}') {
        if (now.expireDateType == 1) {
          this.form.cardEffectiveMode = 0;
          this.form.dateTime = [now.startDate, now.expireDate];
        }
        if (now.expireDateType == 2) {
          // if (now.expDayCount > 1200) {
          //   this.$message({ message: '有效期超出限制', type: 'warning' });
          //   return;
          // }
          this.form.cardEffectiveMode = 1;
          this.form.startDay = now.startDayCount;
          this.form.limitDay = now.expDayCount;
        }
      }
    }
  },
  components: {
    RecycleScroller,
    'dm-upload-img': dmUploadImg,
    'dm-goods-input': dmGoodsInput,
    'dm-send-preview': sendPreview,
    dmUploadAvatar,
    linktools
  },
  computed: {
    storeParams() {
      return !this.isAdd ? { creatorId: this.creatorId } : {};
    },
    storeList() {
      return this.originStoreList.filter(el => el.storeName.indexOf(this.searchStore) >= 0 || el.storeCode.indexOf(this.searchStore) >= 0);
    },
    cardValidity() {
      if (this.form.cardApplyChannel.includes('WMmicroMall') && JSON.stringify(this.nowWmShopData) !== '{}') {
        return true;
      } else {
        return false;
      }
    },
    // 是否展示模板投放有效期
    showSendDateTime() {
      // 当输入完整用户使用有效期后，出现卡券模板投放期限
      const { cardEffectiveMode, limitDay, dateTime } = this.form;
      if (cardEffectiveMode == 0) {
        return !!(dateTime && dateTime[0] && dateTime[1]);
      }
      if (cardEffectiveMode == 1) {
        return !!limitDay;
      }
      return false;
    }
  },

  methods: {
    onOptionsChange(value) {
      this.storeMode = value == 0 ? 0 : 1;
      this.originStoreList = [];
      if (this.isEdit) {
        this.originStoreList = [...this.form.costStoreList];
      }
    },
    onStoreChange(id) {
      getStoreWidgetStore({ key: id, pageSize: 99999, currentPage: 1 }).then(res => {
        const { result, errorCode } = res || {};
        if (errorCode == 0 && Array.isArray(result.result)) {
          this.selectedStoreList = result.result.map(el => {
            const { storeId, storeCode, storeName } = el;
            return { storeId, storeCode, storeName, costValueProportion: undefined, costValue: 0 };
          });
          if (this.isEdit) {
            // 编辑卡券通过门店选择器添加门店时，需要先过滤掉已经选中的门店，再与form.costStoreList合并
            this.selectedStoreList = this.selectedStoreList.filter(el => this.form.costStoreList.every(item => item.storeId != el.storeId));
            this.originStoreList = [...this.selectedStoreList, ...this.form.costStoreList];
          } else if (this.isAdd || this.isCopy) {
            // 新建卡券时直接覆盖
            this.originStoreList = this.selectedStoreList;
          }
        }
      });
    },
    onSortStore(sortType) {
      this.sortType = sortType;
      if (sortType == 0) {
        // 从小到大
        this.originStoreList.sort((a, b) => {
          const left = a.costValueProportion == undefined ? 0 : a.costValueProportion;
          const right = b.costValueProportion == undefined ? 0 : b.costValueProportion;
          return left - right;
        });
      } else if (sortType == 1) {
        // 从大到小
        this.originStoreList.sort((a, b) => {
          const left = a.costValueProportion == undefined ? 0 : a.costValueProportion;
          const right = b.costValueProportion == undefined ? 0 : b.costValueProportion;
          return right - left;
        });
      }
    },
    onCloseImportCost() {
      if (this.importCost.loading) {
        this.importCost.visible = true;
        return;
      }
      this.$refs.importFile.reset();
    },
    handleFileChange({ files }) {
      if (!Array.isArray(files) || files.length == 0) {
        return;
      }
      this.importCost.loading = true;
      const formData = new FormData();
      formData.append('file', files[0]);
      formData.append('requestProject', 'marketing');
      importCostStore(formData)
        .then(res => {
          const { importId, importCount, importSuccessCount, costStoreList } = res.result;
          this.importCost.costStoreList = costStoreList;
          this.$message.success(`上传${importCount}条数据，${importSuccessCount}条数据上传成功`);
          if (importCount - importSuccessCount > 0) {
            this.importCost.options.downloadTemplate.splice(1, 1, {
              url: `/api-marketing/download-cost-store-error?requestProject=marketing&importId=${importId}`,
              name: '下载错误数据'
            });
          }
        })
        .finally(() => {
          setTimeout(() => {
            this.importCost.loading = false;
          }, 500);
        });
    },
    onSaveImportCost() {
      if (this.isAdd || this.isCopy) {
        // 新建卡券导入的数据覆盖之前的数据
        this.originStoreList = this.importCost.costStoreList;
      }
      this.importCost.visible = false;
    },
    getLinkResourceStatus(v) {
      let result = JSON.parse(v);
      const params = {
        id: result.id,
        params: ''
      };
      switch (result.id) {
        case 'product_category_link':
        case 'mall_customize_page':
        case '28':
        case 28:
        case '17':
        case 17:
        case 'coup':
        case 'gift':
          result.params && (params.params = JSON.stringify(result.params));
          break;
        case 'yueshi-intergral_mall':
          params.params = '';
          break;
        case '35':
        case 35:
          params.params = result.appid;
          break;
        case 'GAME_LINK_DZP':
        case 'GAME_LINK_GGK':
        case 'GAME_LINK_PTYX':
        case 'GAME_LINK_KLFL':
        case 'GAME_LINK_ZNM':
          params.params = result.tagid;
          break;
        default:
          return;
      }
      const statusMap = { 1: '已删除', 2: '已失效' };
      getLinkResourceStatus(params).then(res => {
        this.statusText = statusMap[res.result] || '';
      });
    },
    onChangeNumber(val) {
      if (!val) {
        this.$nextTick(() => {
          this.form.cardCodeCount = 0;
        });
      }
    },
    changeOnly(val) {
      this.form.useDescript = val ? '不可与其他卡券叠加使用，详询门店' : '可与部分卡券叠加使用，详询门店';
    },
    // changeDateTime
    setSendDateTime(dateTime) {
      if (dateTime && dateTime[0]) {
        this.form.sendDateTime = [...dateTime];
      }
    },
    // 重新校验时间
    reCheckSendDateTime() {
      this.$nextTick(() => {
        this.$refs.form.validateField('sendDateTime');
      });
    },
    // 改变用户使用有效期类型
    changeCardEffectiveMode(val, cover = true) {
      this.form.sendDateTime = [];
      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 = [,];
    },
    // 切换自动领取
    changeManualGetFlag(val) {
      if (val == 0) {
        // 想要设置为自动领取
        this.$confirm(
          `<div class="fz16 mb10">是否关闭用户手动领取？</div><div class="regular-font-color fz13">用户在领取卡券后需要<b class="bold">同步至ERP</b>，如果关闭用户<b class="bold">手动领取</b>，卡券在<b class="bold">批量投放</b>时会需要将卡券信息批量同步至ERP。
        该过程可能需要持续一段时间（具体同步时间和同步卡券张数以及ERP性能有关，参考同步时间为1万张卡券1个小时）。
        当前支持不需要用户手动领取的卡券库存最大值为<b class="bold">${this.couponAutoGetStock}</b>张。</div>`,
          '提示',
          {
            customClass: 'w450',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        )
          .then(() => {
            this.form.manualGetFlag = val;
          })
          .catch(() => {});
      } else {
        this.form.manualGetFlag = val;
      }
    },
    //切换卡券类型  表单置为默认值
    reset(e) {
      initForm.useCardCodePrefix = this.form.useCardCodePrefix;
      initForm.cardCodePrefix = this.form.cardCodePrefix;

      this.uuid = '';
      this.storeUuid = '';
      this.originStoreList = [];
      this.storeMode = 0;
      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;
      if (this.form.cardType != 3) {
        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'];
      }
      this.$refs.form.clearValidate();
    },
    //卡券营销--卡券库--新建/编辑卡券/卡券记录-领取记录-点击卡券查看详情
    async getCardDetail() {
      this.loading = true;
      let manualGetFlagSettingRes = await getCardManualSetting(); // 获取商户卡券自动领取配置
      this.couponAutoGetFlag = manualGetFlagSettingRes.result.couponAutoGetFlag || 0;
      this.couponAutoGetStock = manualGetFlagSettingRes.result.couponAutoGetStock;
      this.wmCouponJson = JSON.parse(manualGetFlagSettingRes.result.wmCouponJson || '{}');
      this.wmCouponFlag = manualGetFlagSettingRes.result.wmCouponFlag;
      this.cardCodePrefixFlag = manualGetFlagSettingRes.result.cardCodePrefixFlag;
      if (this.isAdd && manualGetFlagSettingRes.result.cardCodePrefixDefault) {
        this.form.cardCodePrefix = manualGetFlagSettingRes.result.cardCodePrefixDefault;
        this.form.useCardCodePrefix = 1;
      }

      let res = null;
      if (this.isCopy) {
        res = await copyCardDetailService({ coupCardId: this.$route.params.id });
      } else {
        res = await getCardDetail({ coupCardId: this.$route.params.id });
        this.creatorId = res.result.card ? res.result.card.creatorId : '';
      }
      if (res.errorCode === 0) {
        // 是否是本人
        this.canEdit = res.result.canEdit !== false;
        // 拉取卡券适用渠道的列表
        if (this.isAdd || this.isCopy) {
          this.cardApplyChannelOptions = res.result.systemCoupChannelList;
        } else {
          this.cardApplyChannelOptions = res.result.allChannelList;
        }

        // 支持的品牌-转赠功能
        if (res.result.giveEnable) {
          this.giveEnable = res.result.giveEnable;
        }

        // 后台运维开关配置 退货退券
        if (res.result.refundEnable) {
          this.refundEnable = res.result.refundEnable;
        }

        // 支持的品牌-商品选择器
        if (res.result.goodsEnable) {
          this.xxSysp.goodsEnable = res.result.goodsEnable;
        }

        // 新增情况下，如果配置了线下门店，默认选中线下门店
        if (this.isAdd && this.cardApplyChannelOptions.some(v => v.value === 'offlineStore')) {
          this.form.cardApplyChannel = ['offlineStore'];
        }
        //处理有效期下拉选项
        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) }));
        this.form.onlyFlag = res.result.onlyFlag;
        if (res.result.card) {
          const card = res.result.card;
          // 3、4为外部券，不显示保存按钮
          this.storeMode = card.storeMode === 0 ? 0 : 1;
          this.gicCouponType = card.gicCouponType;
          this.form.cardApplyChannel = card.cardApplyChannel ? card.cardApplyChannel.split(',') : [];
          this.form.channelTip = card.channelTip == null ? '' : card.channelTip;
          this.form.auditingStatus = card.auditingStatus || '';
          this.form.giveFlag = card.giveFlag;
          this.form.refundFlag = card.refundFlag || 0;
          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;
          if (!this.isAdd) {
            this.form.cardCodePrefix = card.cardCodePrefix;
            this.form.useCardCodePrefix = card.useCardCodePrefix;
          }
          if (this.isCopy && !res.result.giveEnable) {
            this.form.giveFlag = 0;
          }

          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 = Boolean(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.goods_discounts_number_lower_limit = useCondition.goods_discounts_number_lower_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 (useCondition.discount_limit) {
              this.discount_limit.flag = true;
              this.discount_limit.type = useCondition.discount_limit.type;
              this.discount_limit.count = useCondition.discount_limit.count;
            }
            if (this.goods.ok || this.goods.no) {
              this.goods.flag = true;
            }
            this.form.only = Boolean(useCondition.only);
            this.form.proNoList = useCondition.proNo ? [{ name: useCondition.proNo, id: useCondition.proNo }] : [];
          }
          if ((this.isInfo || this.isEdit) && card.weimobDemoCode && JSON.parse(card.weimobDemoCode).length > 0) {
            this.showWeimobDemoSelector = true;
          }
          // 微盟券号 -- 复制不赋值
          if (card.cardApplyChannel.indexOf('WMmicroMall') !== -1 && card.weimobDemoCode && (this.isAdd || this.isInfo || this.isEdit)) {
            this.weimobDemoCodeList = JSON.parse(card.weimobDemoCode).map(v => {
              return { pid: v.pid, card: v.card, loading: false, cardList: [{ cardTemplateId: v.card, name: v.name }], save: true, name: v.name };
            });
            if (!this.weimobDemoCodeList.length) {
              // 如果可以保存微盟券号但是微盟券号为[]
              this.addWmShop();
            }
          }

          // 微盟适用商品
          // isCopy则第二三层不能编辑除非第一层变动;
          if ((card.cardType === 0 || card.cardType === 1) && this.form.cardApplyChannel.indexOf('WMmicroMall') !== -1 && card.coupGoodsWeimobList && card.coupGoodsWeimobList.length) {
            this.goodsList = card.coupGoodsWeimobList.map(v => {
              const f3Arr = JSON.parse(v.propValues); // 第三层的数据
              let f2 = [];
              if (v.propId) {
                // 有可能出现f2为空的下拉
                f2 = [
                  {
                    id: v.propId,
                    title: v.propName
                    // outPropertyId
                  }
                ];
              }
              const f3 =
                f3Arr.map(y => {
                  f2[0].outPropertyId = y.relationIds.split('_')[0];
                  return {
                    id: y.valueId,
                    title: y.valueName,
                    outValueId: y.relationIds.split('_')[1]
                  };
                }) || [];
              return {
                isCopy: this.isCopy,
                v1: v.categoryId,
                v1name: v.categoryName,
                f2,
                v2: v.propId,
                v2name: v.propName,
                f3,
                v3: f3Arr.map(y1 => y1.valueId) || [],
                v3name: f3Arr || []
              };
            });
            if (this.goodsList.length) {
              this.goods.flag = true;
            }
            this.coupGoodsWeimobList = card.coupGoodsWeimobList;
          }

          if (card.cardType == 3) {
            this.form.costValueProportionFlag = card.costValueProportionFlag || 0; // 卡券成本比例 1：开 0：关
            this.form.costValueType = card.costValueType || 0; //成本费用0固定成本1门店成本
            this.form.costValueProportion = card.costValueProportion; //成本比例
            this.form.costStoreList = (this.isEdit || this.isInfo) && Array.isArray(card.costStoreList) ? card.costStoreList : [];
            this.originStoreList = this.form.costStoreList;
          }

          // 线下适用商品
          if (card.goodsSearchDetail && card.goodsFilterId) {
            this.xxSysp.goodsFilterId = card.goodsFilterId;
            const goodsSearchDetail = JSON.parse(card.goodsSearchDetail || '{}');
            this.xxSysp.conditionList = this.xxSysp.conditionList_copy = goodsSearchDetail.conditionList; // ref selector此时放在modal里并没有渲染，之后赋值
            this.xxSysp.conditionList = goodsSearchDetail.conditionList; // ref selector此时放在modal里并没有渲染，之后赋值
            this.xxSysp.conditionList_copy = deepClone(goodsSearchDetail.conditionList || {}); // 备份数据
            this.xxSysp.filterLogicalOperator = goodsSearchDetail.filterLogicalOperator || [];
            if (card.gicCouponType == 3 || card.gicCouponType == 4) {
              const filterAbbrInfo = (goodsSearchDetail.filterAbbrInfo || []).map(el => {
                return el.map((item, index) => {
                  if (index == 0) {
                    item.optName = null;
                  }
                  // intersect 或者，union 并且，diff 剔除
                  switch (item.optName) {
                    case 'union':
                      item.optName = '或者';
                      break;
                    case 'intersect':
                      item.optName = '并且';
                      break;
                    case 'diff':
                      item.optName = '剔除';
                      break;
                  }
                  return item;
                });
              });
              this.xxSysp.filterAbbrInfo = this.xxSyspLabel(filterAbbrInfo);
            } else {
              this.xxSysp.filterAbbrInfo = goodsSearchDetail.filterAbbrInfo || [];
            }
          }

          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 || '';
          this.form.manualGetFlag = card.manualGetFlag;
          if (this.isCopy && this.couponAutoGetFlag == 0) {
            // 复制 && 商户配置不允许使用
            this.form.manualGetFlag = 1;
          }
          // 转赠
          const canCopyGive = card.giveFlag == 1 && ((this.isCopy && res.result.giveEnable) || !this.isCopy) && card.cardExtend; // 拷贝必须是开启开关的
          if (canCopyGive) {
            const { giveContent, giveImage, giveImageField, bannerImage, bannerImageField, useJumpFlag, bannerJumpUrl, giveRule } = card.cardExtend;
            this.form.giveContent = giveContent;
            this.form.giveImage = giveImage;
            this.form.giveImageField = giveImageField;
            this.form.bannerImage = bannerImage;
            this.form.bannerImageField = bannerImageField;
            this.form.useJumpFlag = useJumpFlag;
            this.form.bannerJumpUrl = useJumpFlag ? JSON.parse(bannerJumpUrl) : {};
            this.form.giveRule = giveRule;
            this.giveImg1 = {
              // 转赠对话框图片
              code: giveImageField,
              imgUrl: giveImage
            };
            this.giveImg2 = {
              // 转赠页面首图
              code: bannerImageField,
              imgUrl: bannerImage
            };
          }
          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;
          }
          if (this.form.cardType == 3) {
            this.storeUuid = card.storeWidgetKey || '';
          } else {
            this.uuid = card.storeWidgetKey || '';
            this.$nextTick(_ => {
              // console.log(this.$refs.storeCard);
              this.$refs.storeCard.init();
            });
          }
          this.form.verificationType = card.verificationType || 0;
          this.$nextTick(() => {
            this.$refs.form.clearValidate();
          });
          !this.isCopy && card.jumpFlag == 1 && this.getLinkResourceStatus(card.jumpLink);
        }
      } else {
        this.$tips({ type: 'error', message: '初始化数据失败' });
      }
      this.loading = false;
    },
    checkErpDemoCode() {
      this.form.erpDemoCode = this.form.erpDemoCode.replace(/[^\w\.\/]/gi, '');
    },
    //提交保存
    submitForm: _debounce(async function(formName) {
      function toTop(container, target) {
        if (container.scrollTop > target) {
          container.scrollTop = container.scrollTop - 26;
          setTimeout(() => toTop(container, target), 10);
        }
      }
      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;
        }
      }

      // 可以选微盟且渠道含微盟微商城  -- 微盟券号不能为空
      if (this.form.cardApplyChannel.indexOf('WMmicroMall') !== -1 && this.countFlag) {
        if (!this.weimobDemoCodeList.length) {
          this.$tips({ type: 'warning', message: '适用渠道包含微盟微商城，微盟券号不能为空' });
          return;
        }
        if (this.weimobDemoCodeList.some(v => !v.save && v.pid)) {
          this.$tips({ type: 'warning', message: '微盟券号含有未保存的数据' });
          return;
        }
      }
      // 验证微盟适用商品 勾选适用商品
      if ((this.form.cardType === 0 || this.form.cardType === 1) && this.form.cardApplyChannel.indexOf('WMmicroMall') !== -1) {
        let wmProduct = await this.handleCombine();
        if (wmProduct === 1) {
          this.coupGoodsWeimobList = [];
        } else if (wmProduct) {
          this.coupGoodsWeimobList = wmProduct;
        } else {
          return;
        }
      }

      // 验证适用商品折扣 discount_limit
      if (this.discount_limit.flag && isNaN(this.discount_limit.count)) {
        this.$tips({ type: 'warning', message: '适用商品折扣额度未填写' });
        return;
      }

      // 验证 减免金额 和 折扣额度
      if (this.form.cardType === 0) {
        if (Number(this.form.cardDenomination) <= 0) {
          this.$tips({ type: 'warning', message: '减免金额不能小于0' });
          return;
        }
      } else if (this.form.cardType === 1) {
        if (Number(this.form.cardDenomination) < 1) {
          this.$tips({ type: 'warning', message: '最低折扣不能小于1' });
          return;
        }
      }

      if (this.form.cardType == 3) {
        if (this.form.costValueProportionFlag == 1) {
          if (!Array.isArray(this.originStoreList) || this.originStoreList.length == 0) {
            this.$tips({ type: 'warning', message: '请选择卡券适用门店' });
            const body = document.getElementsByClassName('dm-layout-page')[0];
            toTop(body, this.$refs.useStore.$el.offsetTop - body.offsetTop);
            return;
          }
          if (this.form.costValueType == 1 && this.originStoreList.some(el => el.costValueProportion == undefined || el.costValueProportion == null)) {
            this.$tips({ type: 'warning', message: '请输入门店成本比例' });
            const body = document.getElementsByClassName('dm-layout-page')[0];
            toTop(body, this.$refs.useStore.$el.offsetTop - body.offsetTop);
            return;
          }
        }
      }

      // 验证号段  不能为空 起始号段和结尾号段必须位数一致
      if (this.form.useCustomCode) {
        if (!this.form.customCodeBegin || !this.form.customCodeEnd) {
          this.$tips({ type: 'warning', message: '起始号段和结尾号段不能为空' });
          return;
        }
        if (this.form.customCodeBegin.toString().length !== this.form.customCodeEnd.toString().length) {
          this.$tips({ type: 'warning', message: 'code起始号段和结尾号段必须位数一致' });
          return;
        }
        if (this.form.customCodeEnd - this.form.customCodeBegin + 1 > 100000) {
          this.$tips({ type: 'warning', message: '创建数量不能大于100,000张' });
          // this.form.customCodeEnd  = this.form.customCodeBegin  = 0;
          return;
        }
        // 自定义号段 ，转赠开关设置关闭
        this.form.giveFlag = 0;
      }
      if (!this.refundEnable) {
        this.form.refundFlag = 0;
      }
      //验证有效期
      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;
      }
      if (this.giveEnable && this.form.giveFlag) {
        // 转赠
        if (this.form.useJumpFlag && JSON.stringify(this.form.bannerJumpUrl) == '{}') {
          this.$tips({ type: 'warning', message: '请配置首图链接' });
          return;
        }
        if (!this.form.giveImage) {
          this.$tips({ type: 'warning', message: '请上传转赠对话框图片' });
          return;
        }
        if (!this.form.bannerImage) {
          this.$tips({ type: 'warning', message: '请上传转赠页面首图' });
          return;
        }
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveUpdateCard();
        } else {
          if (!this.form.useCustomCode && this.cardCodePrefixFlag && this.form.useCardCodePrefix && !this.form.cardCodePrefix) {
            this.$tips({ type: 'warning', message: '卡券code前缀不能为空' });
            return false;
          }
          this.$tips({ type: 'warning', message: '表单提交错误，请检查表单是否填写完整' });
          return false;
        }
      });
    }),
    //卡券营销--卡券库--保存卡券
    async saveUpdateCard() {
      if (this.submitLoading) {
        return;
      }

      let card = {};
      let params = {};
      card.channelTip = this.form.channelTip ? this.form.channelTip.slice(0, 18) : ''; // 有超过18字长的老数据
      card.cardApplyChannel = this.form.cardApplyChannel.join(',');
      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;
      card.giveFlag = this.form.giveFlag;
      card.refundFlag = this.form.refundFlag;
      //卡券条件
      //抵金券 sale_limit.fee 最低消费;  goods.ok 适用商品, goods.no 不适应商品, only: 1 不与其他优惠共享(不勾选only不传)
      if (this.form.cardType === 0) {
        card.useCondition = {
          sale_limit: {
            fee: this.sale_limit.fee
          },
          goods: {
            ok: this.goods.ok,
            no: this.goods.no
          }
        };
        if (this.form.only) {
          card.useCondition.only = Number(this.form.only);
        }
        //[折扣券]:  goods.ok 适用商品, goods.no 不适应商品, only: 1 不与其他优惠共享(不勾选only不传)
      } else if (this.form.cardType === 1) {
        card.useCondition = {
          goods: {
            ok: this.goods.ok,
            no: this.goods.no
          },
          only: Number(this.form.only),
          discount_amount_upper_limit: this.form.discount_amount_upper_limit
        };
        if (this.form.only) {
          card.useCondition.only = Number(this.form.only);
        }
        // sale_limit.fee 消费金额满,sale_limit.goods 消费指定商品;  goods.ok 适用商品, goods.no 不适应商品, only: 1 不与其他优惠共享(不勾选only不传)
      } else if (this.form.cardType === 2) {
        card.useCondition = {
          sale_limit: {},
          goods: {
            ok: this.goods.ok,
            no: this.goods.no
          },
          only: Number(this.form.only),
          proNo: this.form.proNoList.length ? this.form.proNoList[0].id : '',
          products_exchange_number: this.form.proNoList.length ? this.form.products_exchange_number : 0
        };
        // 兑换券的使用条件参数只能传一个，不能同时传
        if (this.sale_limit.type == 1) {
          card.useCondition.sale_limit = { fee: this.sale_limit.fee };
        } else if (this.sale_limit.type == 2) {
          card.useCondition.sale_limit = { goods: this.sale_limit.goods };
        }
        if (this.form.only) {
          card.useCondition.only = Number(this.form.only);
        }
      } else if (this.form.cardType == 3) {
        card.useCondition = {
          sale_limit: {
            fee: this.sale_limit.fee
          }
        };
        card.costValueType = this.form.costValueType; //成本费用0固定成本1门店成本
        card.costValueProportion = this.form.costValueProportion; //成本比例
        card.costValueProportionFlag = this.form.costValueProportionFlag;
        if (card.costValueType == 0) {
          card.costValue = typeof this.form.costValueProportion == 'number' && typeof this.form.cardDenomination == 'number' ? this.form.costValueProportion * this.form.cardDenomination : 0; //成本
          card.costStoreList = [];
        }
        if (card.costValueType == 1) {
          card.costValue = undefined;
          if (this.isEdit) {
            card.costStoreList = this.selectedStoreList.map(el => {
              el.costValue = typeof this.form.cardDenomination == 'number' && typeof el.costValueProportion == 'number' ? this.form.cardDenomination * el.costValueProportion : 0;
              return el;
            });
          } else if (this.isAdd || this.isCopy) {
            card.costStoreList = this.originStoreList.map(el => {
              el.costValue = typeof this.form.cardDenomination == 'number' && typeof el.costValueProportion == 'number' ? this.form.cardDenomination * el.costValueProportion : 0;
              return el;
            });
          }
        }
      }

      // 适用商品额度
      if (this.discount_limit.flag) {
        const { count, type } = this.discount_limit;
        card.useCondition.discount_limit = { count, type };
      }

      // 商品上下线控制不受渠道卡券类型影响
      card.useCondition.goods_discounts_number_upper_limit = this.form.goods_discounts_number_upper_limit;
      card.useCondition.goods_discounts_number_lower_limit = this.form.goods_discounts_number_lower_limit;

      if (card.useCondition.goods_discounts_number_upper_limit && card.useCondition.goods_discounts_number_lower_limit && card.useCondition.goods_discounts_number_lower_limit > card.useCondition.goods_discounts_number_upper_limit) {
        // 最低件数不可以大于最高件数
        this.$tips({ message: '最低适用商品件数不可以最低适用商品件数', type: 'warning' });
        return;
      }

      // 微盟券号
      if (this.form.cardApplyChannel.indexOf('WMmicroMall') !== -1) {
        /* eslint-disable */
        card.weimobDemoCode = this.weimobDemoCodeList
          .filter(v => v.save)
          .map(({ pid, card, name }) => { return { pid, card, name }; })
          || [];
        /* eslint-disable */
      }

      // 微盟适用商品
      if ((this.form.cardType === 0 || this.form.cardType === 1) && this.form.cardApplyChannel.indexOf('WMmicroMall') !== -1 && this.coupGoodsWeimobList.length !== 0) {
        card.coupGoodsWeimobList = this.coupGoodsWeimobList;
      }

      // 线下适用商品
      if (this.xxSysp.goodsEnable && this.xxSysp.goodsFilterId) {
        card.goodsFilterId = this.xxSysp.goodsFilterId;
        if (this.xxSysp.conditionList) {
          card.goodsSearchDetail = JSON.stringify({
            conditionList: this.isEdit ? this.xxSysp.conditionList_copy : this.xxSysp.conditionList, // 编辑保存备份数据
            filterAbbrInfo: this.xxSysp.filterAbbrInfo
          }); // 反显数据
        }
      }

      //卡券限制
      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;
      //自定义号段
      if (card.useCustomCode === 1) {
        card.customCodeBegin = this.form.customCodeBegin;
        card.customCodeEnd = this.form.customCodeEnd;
        if (this.form.useCodePrefix) {
          card.customCodePrefix = this.form.customCodePrefix;
        }
        if (this.form.useCodeSuffix) {
          card.customCodeSuffix = this.form.customCodeSuffix;
        }
        card.cardCodeCount = this.form.customCodeEnd - this.form.customCodeBegin + 1;
      } else {
       if(this.form.useCardCodePrefix ){
         card.cardCodePrefix = this.form.cardCodePrefix
       }
       card.useCardCodePrefix =this.form.useCardCodePrefix 
        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.manualGetFlag = this.form.manualGetFlag;
      if ((this.isAdd || this.isCopy) && this.couponAutoGetFlag == 0) {
        // 商户不允许使用自动领取配置
        card.manualGetFlag = 1;
      }
      if (card.manualGetFlag == 0 && card.cardCodeCount > this.couponAutoGetStock) {
        // 开启转赠 限制库存数
        this.$tips({ message: `无需手动领取库存超过(${this.couponAutoGetStock})上限`, type: 'warning' });
        return;
      }
      card.cardExplain = this.form.cardExplain;
      card.useDescript = this.form.useDescript;

      if (card.cardType === 2) {
        card.verificationType = this.form.verificationType || 0;
      }
      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;
      // 如果是商场抵金券，而且开启了卡券成本比例，而且选择了门店成本，storeMode就传0
      if (card.cardType == 3 && card.costValueProportionFlag == 1 && card.costValueType == 1) {
        card.storeMode = 0;
      }
      card.storeWidgetKey = card.cardType == 3 ? this.storeUuid : this.uuid;
      // 这里判断部分门店是否为空
      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;
        // }
      }

      params.card = JSON.stringify(card);
      // 转赠  与card同级
      if (this.form.giveFlag == 1 && this.giveEnable) {
        const { giveContent, giveImage, giveImageField, bannerImage, bannerImageField, useJumpFlag, bannerJumpUrl, giveRule } = this.form;
        params.giveContent = giveContent;
        params.giveImage = giveImage;
        params.giveImageField = giveImageField;
        params.bannerImage = bannerImage;
        params.bannerImageField = bannerImageField;
        params.useJumpFlag = useJumpFlag;
        params.bannerJumpUrl = JSON.stringify(bannerJumpUrl);
        params.giveRule = giveRule;
      }
      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('/card/list');
                })
                .catch(err => {
                  this.getCardDetail();
                });
            } else {
              console.log(this.$route.meta.refresh)
              this.$tips({ type: 'success', message: '新建卡券成功' });
              this.$route.meta.refresh=true;
              this.$router.push('/card/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, '') + '';
    },
    // ------微盟店铺开始-------
    async saveWmShop(saveItem, idx) {
      if (!saveItem.pid || !saveItem.card) {
        this.$message({ message: '该条券号保存不完整', type: 'warning' });
        return;
      }
      const now = this.weimobDemoCodeList[idx].cardList.find(v => v.cardTemplateId == this.weimobDemoCodeList[idx].card);
      if (idx > 0) {
        // 与上一个进行比较
        const before = this.weimobDemoCodeList[idx - 1].cardList.find(v => v.cardTemplateId == this.weimobDemoCodeList[idx - 1].card);
        // （1:固定类型；2:动态类型；3:永久有效）
        try {
          if (before.expireDateType != now.expireDateType) {
            throw new Error();
          } else {
            if (before.expireDateType == 1 && before.startDate != now.startDate || before.expireDate != now.expireDate) {
              throw new Error();
            }
            if (before.expireDateType == 2 && before.startDayCount != now.startDayCount || before.expDayCount != now.expDayCount) {
              throw new Error();
            }
          }
        } catch (error) {
          // 清空该行数据
          this.weimobDemoCodeList[idx].card = '';
          this.$message({ message: '微盟卡券有效期不一致', type: 'warning' });
          return;
        }
      } else {
        // 第一个把默认值放入
        if (now.expireDateType == 1) {
          this.form.cardEffectiveMode = 0;
          this.form.dateTime = [now.startDate, now.expireDate];
          this.$nextTick(() => {
            this.$refs.effectDate.$emit('change', 0, false);
          })
        }
        if (now.expireDateType == 2) {
          if (now.expDayCount > 1200) {
            this.$message({ message: '有效期超出限制', type: 'warning' });
            return;
          }
          this.form.cardEffectiveMode = 1;
          this.form.startDay = now.startDayCount;
          this.form.limitDay = now.expDayCount;
        }
        this.nowWmShopData = { ...now };
        // this.cardValidity = true; // 禁用有效期
      }
      this.weimobDemoCodeList[idx].save = true;
      this.weimobDemoCodeList[idx].name = saveItem.cardList.find(v => {
        return v.cardTemplateId == saveItem.card;
      }).name; // 保存name
      this.wmShopAddDisabled = false;
      this.wmShopIds.push(saveItem.pid); // 保存过得店铺新增的下拉不让选
      let res = await getWeimobCouponBindCount({ cardTemplateId: saveItem.card });
      this.weimobDemoCodeList[idx].useCount = res.result || 0;
    },
    delWmShop(saveItem, idx) {
      const id_idx = this.wmShopIds.findIndex(v => {
        return v == saveItem.pid;
      });
      this.wmShopIds.splice(id_idx, 1);
      this.weimobDemoCodeList.splice(idx, 1);
      if (this.weimobDemoCodeList.length === 0) {
        this.addWmShop();
        this.nowWmShopData = {};
        this.form.dateTime = [,];
        this.form.startDay = '';
        this.form.limitDay = '';
      }
    },
    addWmShop() {
      this.weimobDemoCodeList.push({ pid: '', card: '', loading: false, cardList: [], save: false, cardName: '', useCount: 0 });
      this.wmShopAddDisabled = true;
    },
    // getLatestReptileTime
    getLatestReptileTime() {
      getLatestReptileTime().then(res => {
        if (res.result) {
          this.latestReptileTime = formatDateTimeByType(res.result, 'yyyy-MM-dd HH:mm:ss');  ;
        }
      })
    },
    // 获取微盟店铺列表
    getListEntepriseWeimobShop() {
      listEntepriseWeimobShop().then(res => {
        this.countFlag = res.result.countFlag || 0;
        this.weimobShopList = res.result.dataList || [];
      });
    },
    // 第一层店铺change  根据微盟店铺id查询所有店铺卡券 wmPid=xxx
    handleShopChange(wmPid, idx) {
      this.weimobDemoCodeList[idx].cardList = [];
      this.weimobDemoCodeList[idx].card = '';
      this.currentPage=1;
      this.wmPid=wmPid;
      this.idx=idx;
      this.weimobDemoCodeList[this.idx].loading = true;
      this.listEntepriseWeimobCoupon();

    },
    listEntepriseWeimobCoupon(val){
     let params={
      wmPid:this.wmPid,pageSize:this.pageSize, currentPage:this.currentPage
     }
     if(val){
      params.search=val;
     }
     console.log(params)
      listEntepriseWeimobCoupon(params)
      .then(res => {
        const {result,totalPage,currentPage} =  res.result;
        this.totalPage=totalPage;
        this.currentPage=currentPage;
        if(val){this.currentPage=totalPage}
        this.weimobDemoCodeList[this.idx].cardList =this.weimobDemoCodeList[this.idx].cardList.concat(result || []) ;
        this.weimobDemoCodeList[this.idx].loading = false;
        if (this.weimobDemoCodeList[this.idx].cardList.length === 0) {
          this.$message({ message: '该店铺没有对应微盟券号', type: 'warning' });
        }
      })
      .finally(() => {
        this.weimobDemoCodeList[this.idx].loading = false;
      });
    },
    remoteMethod(val){
      console.log(val)
      this.currentPage=1;
      this.weimobDemoCodeList[this.idx].cardList =  [];
      this.weimobDemoCodeList[this.idx].loading = true;
      this.listEntepriseWeimobCoupon(val);
    },
    handleClear(){
      this.currentPage=1;
      this.weimobDemoCodeList[this.idx].cardList =  [];
      this.weimobDemoCodeList[this.idx].loading = true;
      this.listEntepriseWeimobCoupon();
    },
    getMore(){
      if(this.currentPage<this.totalPage ){
        this.currentPage++
        this.listEntepriseWeimobCoupon();
      }
    },
 
    // ---------微盟店铺结束--------
    // ------微盟适用商品开始-------
    // 获取第一层数据
    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;
        this.$refs.form.validateField('jumpLink');
        this.statusText = '';
      }
    },
    // ---------链接小工具 - 转赠---------
    linkSelect2(val) {
      if (!this.isInfo) {
        this.form.bannerJumpUrl = val;
        this.$refs.form.validateField('bannerJumpUrl');
      }
    },
    getCardEffectiveMode() {
      getCardEffectiveMode().then((res) => {
        this.isEffective = res.result;
      })
    }
  },
  mounted() {
    // this.cardGetShelfs();
    this.getCardEffectiveMode();
    this.getCardDetail();
    this.getCategoryList(); // 获取适用商品第一层数据
    this.getListEntepriseWeimobShop(); // 获取微盟店铺数据
    this.getLatestReptileTime();
    if (this.isAdd) {
      this.$refs.storeCard.init();
    }
    if(this.isAdd||this.isCopy){
      this.$route.meta.refresh=false;
    }
  }
};
