import { _debounce } from '@/utils/index';
import { checkMessageSendCount } from '@/service/api/messageApi.js';
import { getEcmInfo, saveEcmInfo, getUseStoredFalg, getXsxsFalg, gicPaymentList } from '@/service/api/ecmApi.js';
import { getCardManualSetting } from '@/service/api/cardApi.js';
import { listTemplateVariables } from '@/service/api/msgApi.js';
import { klflStrategy } from '@/service/api/gameApi.js'; // 会员等级列表接口
import xxSysp_mix from '@/mixins/selector.js'; // 商品选择器方法mixins
import marketingEvent from './marketing-event/index.vue';
import { formatDateTimeByType, deepClone } from '@/utils/index.js';
import { isEmpty, numOfDecimal } from '@/utils/strlen.js';
import itemCard from './partials/item-card.vue';
import varDialog from './partials/variables.vue';
import Vue from 'vue';
export default {
  name: 'ecm-manage',
  mixins: [xxSysp_mix],
  data() {
    return {
      onlineStatus: 0,
      ecmPlanId: '', // 必传,
      creatorId: '',
      code: '1001',
      loading: false,
      effectActionOptions: [{ value: 'subscribe', label: '关注触发' }, { value: 'authentication', label: '认证触发' }, { value: 'consume', label: '消费触发' }, { value: 'degrade', label: '会员卡降级触发' }, { value: 'upgrade', label: '会员卡升级触发' }, ], // eslint-disable-line
      marketingTimesTypeOptions: [{ value: 0, label: '总共触发' }, { value: 1, label: '每天触发' }, { value: 2, label: '每周触发' }, { value: 3, label: '每月触发' }, { value: 4, label: '每年触发' }, { value: -1, label: '无限次触发' }], // eslint-disable-line
      execDateType: [
        { label: '每天', value: 1 },
        { label: '每周', value: 2 },
        { label: '每月', value: 3 }
      ], // 1按天执行 2按周 3按月
      dayOptions: Array(24)
        .fill()
        .map((v, i) => ({ value: i, label: i + ':00' })),
      sceneSettingIdOptions: [],
      // 消费触发错误提示
      // error_cost_info: '',
      // error_cost_count_info: '',
      cardNoticeType: 0, // info 老数据用得到
      // 自动领取设置
      couponAutoGetFlag: 0, // 1开启自动领取 0关闭
      couponAutoGetStock: 0, // 自动领取最大库存数
      enterpriseId: '',
      form: {
        memberType: 0,
        ecmPlanName: '',
        effectType: 0,
        execDateType: 1, // 1按天执行 2按周 3按月
        execDate: [], // 1,2,3,4,5,6,7,8,0(月底)
        execTime: '', // 重复 执行时间  10:30:00
        execType: 1, // 1立即执行0定时执行
        effectTime: 0,
        effectAction: 'subscribe',
        marketingActivityId: '',
        sceneSettingName: '',
        expireType: 0,
        cardId: '',
        mediaId: '',
        imageTextId: '',
        textContent: '',
        title: '',
        describe: '',
        lateDays: '',
        brithday_day: '',
        brithday_type: 1,
        attention_day: '',
        lastCost_day: '',
        memberSearchDTO: '',
        memberGroupIds: '',
        beginDate: '',
        endDate: '',
        cardNoticeType: 0,
        templateNoticeFlag: 0,
        // 判断模板消息能否使用
        templateUseEnable: 1,
        marketingTimesType: 0,
        marketingOnceFlag: 1, // 默认开启 限制对每个用户营销一次
        marketingTimes: 1,
        gradeIds: [],
        //消费触发
        lowest_cost: '',
        max_cost: '',
        lowest_cost_count: '',
        max_cost_count: '',
        // store_mode: 0,
        consumerStoreType: 0, // 0 固定门店 1 门店条件
        order_store: '',
        order_store_new: '',
        storedLowest: 0,
        storedMax: 0,
        consum_type: 1,
        gift_flag: 0
      },
      template: {
        headerColor: '#173177',
        remarkColor: '#173177',
        headerText: '',
        remarkText: '',
        templateKeyDataList: []
      },
      copyTemplate: {
        headerColor: '#173177',
        remarkColor: '#173177',
        headerText: '',
        remarkText: '',
        templateKeyDataList: []
      },
      dateTime: ['', ''],
      endDatePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      endDatePickerOptions2: {
        //编辑 消费触发-累计订单实付金额-结束时间
        disabledDate: time => {
          return time.getTime() < Date.now() - 8.64e7 || time.getTime() > this.endDate;
        }
      },
      endDatePickerOptions3: {
        //新增 消费触发-累计订单实付金额-结束时间
        disabledDate: time => {
          if (this.form.beginDate) {
            return time.getTime() < Date.now() - 8.64e7 || time.getTime() > new Date(this.form.beginDate).getTime() + 31 * 24 * 60 * 60 * 1000;
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        }
      },
      pickerOptions: {
        disabledDate(val) {
          return Date.now() >= val.getTime() + 24 * 60 * 60 * 1000;
        }
      },
      checked: [],
      rules: {
        ecmPlanName: { type: 'string', required: true, message: '计划名称不能为空', trigger: 'blur' },
        gradeIds: [{ type: 'array', required: true, message: '请至少选择一个卡类型', trigger: 'change' }]
        // execDate: { validator: checkExecDate, required: true, message: '执行日期填写不完整', trigger: 'change' }
      },
      isEdit: this.$route.meta.type === 'edit',
      isAdd: this.$route.meta.type === 'add' || this.$route.meta.type === 'copy',
      isInfo: this.$route.meta.type === 'info',
      isCopy: this.$route.meta.type === 'copy',
      isCopyEcm: this.$route.meta.type === 'copy',
      isInit: this.$route.meta.type === 'add',
      // 人群筛选器可传参数
      sceneValue: 'member', // 场景值
      useId: '', // 模板id
      hasSearchData: '', // 当前页回显的数据(接口返回)
      toggleTag: false, // 控制按钮显示的参数,仅供参考,可自行修改
      getSaveData: '',
      saveTag: false,

      enabledMessageState: 0, // 能否发送短信，接口获取
      showMessage: false, // 有效时间展示错误信息flag
      currentCard: {},
      varDialogShow: false, // 常量弹窗show
      currentTxet: '',
      options: [],
      editDialogShow: false,
      gradeList: [],
      // 会员分组可传参数
      defaltSelected: [], //  默认穿梭窗已选入数据
      projectName: 'marketing', // 默认是memberTag
      headerList: ['isRealTime', 'latestUpdateTime', 'updateType', 'effectiveStatus', 'effectiveDate'],
      effectiveStatus: 1, // 不传： 所有状态 1： 有效 0： 失效

      templateOptions: [],
      triggerCode: '',
      // 消费触发勾选checkbox
      consumeChecked: {
        store: false, // 门店
        cost: false, // 消费金额
        count: false, // 消费件数
        good: false, // 消费商品
        payment: false
      },
      storedChecked: false,
      discount_limit: { type: 1, count: undefined, flag: false }, // 适用商品折扣
      useStoredFlag: 0, //显示储值触发和会员卡升级事件
      analyseConfig: {
        open_flag: '',
        crowd_flag: 0,
        crowd_send: 4,
        crowd_no_send: 1,
        marke_days: 14
      },
      xsxsFlag: 0,
      allList: [], // 所有支付方式
      gicList: [], // gic支付方式
      paymentList: [], //商户支付方式
      checkList: [],
      paymentFlag: 1,
      // 是否选择了非实时分组 true：是 false：否
      hasRealTime: false,
      endDate: '' //编辑 消费触发-累计订单实付金额-结束时间修改时用到
    };
  },
  components: {
    'marketing-event': marketingEvent,
    'item-card': itemCard,
    'var-dialog': varDialog
  },
  watch: {
    checked(val) {
      switch (val[0]) {
        case 'brithday_day':
          if (!this.form.brithday_day) {
            this.form.brithday_type = 1;
          }
          this.form.attention_day = 0;
          this.form.lastCost_day = 0;
          break;
        case 'attention_day':
          if (!this.form.attention_day) {
            this.form.attention_day = 1;
          }
          this.form.brithday_day = 0;
          this.form.lastCost_day = 0;
          break;
        case 'lastCost_day':
          if (!this.form.lastCost_day) {
            this.form.lastCost_day = 1;
          }
          this.form.brithday_day = 0;
          this.form.attention_day = 0;
          break;
        default:
          this.form.brithday_day = 0;
          this.form.attention_day = 0;
          this.form.lastCost_day = 0;
          break;
      }
    }
  },
  computed: {
    execDateList() {
      // 1按天执行 2按周 3按月
      const { execDateType } = this.form;
      if (execDateType === 1) {
        return [];
      }
      if (execDateType === 2) {
        return [
          { label: '周一', value: '1' },
          { label: '周二', value: '2' },
          { label: '周三', value: '3' },
          { label: '周四', value: '4' },
          { label: '周五', value: '5' },
          { label: '周六', value: '6' },
          { label: '周日', value: '7' }
        ];
      }
      if (execDateType === 3) {
        return Array(28)
          .fill('')
          .map((v, idx) => {
            return { label: `${idx + 1}号`, value: `${idx + 1}` };
          })
          .concat({ label: '月底', value: '0' });
      }
      return [];
    },
    storeParams() {
      return !this.isInit ? { creatorId: this.creatorId } : {};
    },
    marketingTimesTips() {
      let tips = '';
      switch (this.form.marketingTimesType) {
        case 0:
          tips = `总共对同个会员触发${this.form.marketingTimes}次`;
          break;
        case 1:
          tips = `在一天内对同个会员触发${this.form.marketingTimes}次，每天0:00刷新触发次数`;
          break;
        case 2:
          tips = `在一周内对同个会员触发${this.form.marketingTimes}次，每周一0:00刷新触发次数`;
          break;
        case 3:
          tips = `在一个月内对同个会员触发${this.form.marketingTimes}次，每月1号0:00刷新触发次数`;
          break;
        case 4:
          tips = `在一年内对同个会员触发${this.form.marketingTimes}次，每年1月1号0:00刷新触发次数`;
          break;
        case -1:
          tips = `对同个会员触发无限次`;
          break;
      }
      return tips;
    },
    getRealTimeType() {
      let result = [0, 1];
      if (this.canSelectRealTime) {
        result.shift(0);
      }
      return result;
    },
    canSelectRealTime() {
      let flag = false;
      // 时效选择重复，时间选择非9-23
      // 失效选择单次，
      // 执行选择立即执行，且当前时间非9-23
      // 执行选择定时执行，且时间选择非9-23
      if (this.form.effectType == 1) {
        let effectTime = this.form.effectTime;
        if (typeof effectTime == 'string' && effectTime.length > 0) {
          effectTime = Number(effectTime.slice(0, 2));
          flag = effectTime < 9 || effectTime > 23;
        }
      }
      if (this.form.effectType == 2) {
        if (this.form.execType == 0) {
          let execTime = this.form.execTime;
          if (typeof execTime == 'string' && execTime.length > 0) {
            execTime = execTime
              .split(' ')[1]
              .split(':')
              .map(el => Number(el));
            flag = execTime[0] < 9 || (execTime[0] == 23 && (execTime[1] > 0 || execTime[2] > 0));
          }
        }
        // 小于9 或者大于23
        const now = new Date().getHours();
        if (this.form.execType == 1) {
          flag = now < 9 || now > 23;
        }
      }
      return flag;
    }
  },
  methods: {
    /* ----------------核心方法--------------- */
    onChangeDiscountLimit(type) {
      if (type == 6) {
        this.$set(this.discount_limit, 'count2', undefined);
      } else {
        this.$delete(this.discount_limit, 'count2');
      }
    },
    filterWord(prop) {
      this.copyTemplate[prop] = this.copyTemplate[prop].replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/g, '');
    },
    checkMessageSendCount() {
      return new Promise(async (resolve, reject) => {
        let events = this.$refs.marketingEvent.list.map(el => el.name);
        events = Array.from(new Set(events));
        const params = {
          memberSearchDTO: this.form.memberType ? this.form.memberGroupIds : this.form.memberSearchDTO,
          marketingType: 0,
          // 区分人员筛选和会员分组，需要传这个flag
          groupType: this.form.memberType
        };
        this.loading = true;
        const res = await checkMessageSendCount(params).finally(() => (this.loading = false));
        if (res && res.errorCode === 0) {
          this.$confirm(
            `<div>
              <div class="inline-block w300 vertical-middle ">
                <p>本计划包含营销事件有：(${events.join('，')})</p>
                <p>本计划保存这一刻合计发送人数为：${res.result}人</p>
                <p>是否发送?</p>
              </div>
            </div>`,
            '提示',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              cancelBUttonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              resolve(res.result);
            })
            .catch(() => {
              this.$tips({ type: 'info', message: '已取消发送' });
              reject();
            });
        }
      });
    },
    // 获取变量列表
    async listTemplateVariables() {
      this.loading = true;
      try {
        let res = await listTemplateVariables().finally(() => (this.loading = false));
        if (res.errorCode === 0) {
          const result = res.result;
          this.options = Object.keys(result).map(v => ({ label: result[v], value: v }));
        }
        this.getEcmInfo();
      } catch (err) {
        console.log(err);
      }
    },
    // 支付方式
    gicPaymentList() {
      gicPaymentList({ pageSize: 100 }).then(res => {
        const {
          result: { result }
        } = res;
        this.allList = result;
        let gicArr = [];
        let arr = [];
        result.forEach(item => {
          item.isGic ? arr.push(item) : gicArr.push(item);
        });
        this.gicList = gicArr;
        this.paymentList = arr;
      });
    },
    radioChange() {
      this.checkList = [];
      this.gicPaymentList();
    },
    wen(val) {
      console.log(val);
    },
    // 获取商户卡券自动领取配置
    getCardManualSetting() {
      getCardManualSetting()
        .then(res => {
          this.couponAutoGetFlag = res.result.couponAutoGetFlag || 0;
          this.couponAutoGetStock = res.result.couponAutoGetStock;
        })
        .finally(() => (this.loading = false));
    },
    // 获取ecm信息
    async getEcmInfo(isResetTemplate = false) {
      this.loading = true;
      let res = await getEcmInfo({ ecmPlanId: this.$route.params.id, copy: this.isCopy ? 1 : undefined });
      this.loading = false;
      // 如果是模板重置不需要重置基本信息
      if (!isResetTemplate && res.result) {
        const result = res.result.ecmDTO;
        const commonScene = res.result.commonScene;
        const consumTrigger = res.result.consumTrigger;
        this.enabledMessageState = res.result.enabledMessageState || 0;
        this.xxSysp.goodsEnable = res.result.goodsEnable || false; // 是否支持商品选择器
        if (result && !this.isInit) {
          this.onlineStatus = result.onlineStatus;
          this.creatorId = res.result.ecmDTO.creatorId;
          if (this.isCopy) {
            this.ecmPlanId = res.result.templateEcmPlanId || '';
          } else {
            this.ecmPlanId = this.form.ecmPlanId = result.ecmPlanId || '';
          }
          this.form.ecmPlanName = result.ecmPlanName;
          this.form.effectType = result.effectType;
          const effectTime = result.effectTime == '' || result.effectTime == undefined ? 0 : result.effectTime;
          this.form.effectTime = effectTime > 9 ? `${result.effectTime}:00` : `0${result.effectTime}:00`;
          this.form.effectAction = result.effectAction;
          this.form.marketingActivityId = result.marketingActivityId;
          this.form.sceneSettingName = result.sceneSettingName;
          this.form.memberType = result.memberType;
          this.form.expireType = result.expireType;
          this.form.execType = result.execType;
          this.form.execDateType = result.execDateType;
          this.form.execDate = result.execDate ? result.execDate.split(',') : [];
          this.form.execTime = result.execTime ? new Date(result.execTime) : '';
          //处理会员等级
          this.form.gradeIds = (result.gradeIds && result.gradeIds.split(',').filter(v => v)) || [];
          //营销次数配置
          this.form.marketingTimesType = result.marketingTimesType || 0;
          this.form.marketingTimes = result.marketingTimes || 1;
          if (result.effectType == 1) {
            // 重复
            this.form.marketingOnceFlag = result.marketingTimesType == 0 ? 1 : 0;
          }
          //'0-不通知 1-微信对话框 2-模板消息   补发通知 0-不补发 1-补发'
          this.form.cardNoticeType = result.cardNoticeType || 0;
          this.cardNoticeType = result.cardNoticeType || 0;
          this.form.templateNoticeFlag = result.templateNoticeFlag || 0;
          // 判断回显
          if (this.form.memberType === 0) {
            this.form.memberSearchDTO = result.filterJson;
          } else {
            //会员分组
            this.form.memberGroupIds = result.filterJson || '';
            this.defaltSelected = res.result.tagGroupList || [];
          }
          if (this.form.expireType) {
            this.form.beginDate = result.beginDate || '';
            this.form.endDate = result.endDate || '';
            this.endDate = this.form.endDate;
          }
          if (res.result.searchId) {
            this.useId = res.result.searchId || '';
            // console.log(this.useId, 'useid');
            this.hasSearchData = result.filterJson || '{}';
          }
          if (this.form.effectType === 1) {
            this.form.brithday_day = commonScene.brithday_day;
            this.form.brithday_type = commonScene.brithday_type || 1;
            this.form.attention_day = commonScene.attention_day;
            this.form.lastCost_day = commonScene.lastCost_day;
            if (this.form.brithday_day) {
              this.checked = ['brithday_day'];
            } else if (this.form.attention_day) {
              this.checked = ['attention_day'];
            } else if (this.form.lastCost_day) {
              this.checked = ['lastCost_day'];
            }
          }
          if (result.analyseJson) {
            this.analyseConfig = JSON.parse(result.analyseJson);
          } else {
            this.analyseConfig = {
              open_flag: 0,
              crowd_flag: 0,
              crowd_send: 4,
              crowd_no_send: 1,
              marke_days: 14
            };
          }
        } else if (this.isInit) {
          this.ecmPlanId = res.result.templateEcmPlanId || '';
        }
        this.form.templateUseEnable = res.result.templateUseEnable;
        this.$nextTick(_ => {
          this.effectActionChange(true);
        });
        // 处理消费触发
        if (consumTrigger) {
          // 消费触发配置 单笔触发，当天累计实付触发
          this.form.consum_type = consumTrigger.consum_type;
          // 触发门店初始化
          this.consumeChecked.store = Boolean(consumTrigger.store_mode) || false; /** 门店类型: 0: 所有门店, 1: 部分(包含部分门店, 部分分组等) **/
          this.form.consumerStoreType = result.consumerStoreType || 0; /** 消费门店类型 **/
          this.form.order_store = this.form.consumerStoreType === 0 ? consumTrigger.order_store : ''; /** 消费门店key值 **/
          this.form.order_store_new = this.form.consumerStoreType === 1 ? consumTrigger.order_store : ''; /** 消费门店key值 **/
          if (this.form.effectAction === 'consume' && consumTrigger.store_mode && result.consumerStoreType === 0) {
            this.$nextTick(_ => {
              this.$refs.storeCard.init();
            });
          }
          // 消费商品
          if (res.result.goodsEnable && consumTrigger.goods_filter_id) {
            this.xxSysp.goodsFilterId = consumTrigger.goods_filter_id || '';
            this.consumeChecked.good = !!consumTrigger.goods_filter_id || false;
            if (res.result.goodsSearchDetail.detail) {
              const goodsSearchDetail = JSON.parse(res.result.goodsSearchDetail.detail);
              this.xxSysp.conditionList = goodsSearchDetail.conditionList; // ref selector此时放在modal里并没有渲染，之后赋值
              this.xxSysp.conditionList_copy = deepClone(goodsSearchDetail.conditionList); // 备份数据
              this.xxSysp.filterAbbrInfo = goodsSearchDetail.filterAbbrInfo || [];
              this.xxSysp.filterLogicalOperator = goodsSearchDetail.filterLogicalOperator || [];
            }
            this.form.gift_flag = consumTrigger.gift_flag;
          }

          // 处理适用商品折扣
          if (consumTrigger.discount_limit) {
            const discount_limit = JSON.parse(consumTrigger.discount_limit);
            this.discount_limit.flag = true;
            this.discount_limit.type = discount_limit.type;
            this.discount_limit.count = discount_limit.count;
            if ('count2' in discount_limit) {
              this.$set(this.discount_limit, 'count2', discount_limit.count2);
            }
          }

          // 消费金额&消费件数
          this.consumeChecked.cost = consumTrigger['lowest_cost'] || consumTrigger['max_cost'] ? true : false;
          this.consumeChecked.count = consumTrigger['lowest_cost_count'] || consumTrigger['max_cost_count'] ? true : false;
          const _mapConsumeArr = ['lowest_cost', 'max_cost', 'lowest_cost_count', 'max_cost_count'];
          _mapConsumeArr.map(v => {
            // 为空为null代表无限制
            if (isEmpty(consumTrigger[v])) {
              this.form[v] = undefined;
            } else {
              this.form[v] = consumTrigger[v];
            }
          });

          // 支付方式回显
          this.consumeChecked.payment = consumTrigger.gic_payment_flag ? true : false;
          if (consumTrigger.gic_payment_flag) {
            this.paymentFlag = consumTrigger.gic_payment_flag;
            this.checkList = (consumTrigger.gic_payment_list && JSON.parse(consumTrigger.gic_payment_list)) || [];
            this.checkList = this.checkList.map(i => i.payCode);
          }
        }

        if (this.form.effectAction === 'stored' && result.effectTriggerJson) {
          let cost = JSON.parse(result.effectTriggerJson) || {};
          this.storedChecked = true;
          this.form.storedLowest = cost.lowest_cost;
          this.form.storedMax = cost.max_cost;
        }
      }
      if (!this.form.templateUseEnable) return;
      let template = null;
      this.templateOptions = res.result.marketingTemplateList || [];
      if (!this.isInit) {
        template = res.result.customMarketingTemplate || res.result.marketingTemplateList[0];
      } else {
        template = res.result.marketingTemplateList[0];
      }
      this.triggerCode = template ? template.triggerCode : '';
      // 模板消息
      if (template) {
        this.templateInit(template);
      }
      //新建 单笔订单时 最小值默认为1
      if (this.isInit) {
        this.form.lowest_cost = 1;
      }
      if (this.isCopy) {
        this.form.ecmPlanName = '';
        this.form.execTime = '';
        this.form.beginDate = '';
        this.form.endDate = '';
        this.form.effectTime = 0;
        this.analyseConfig = {
          open_flag: '',
          crowd_flag: 0,
          crowd_send: 4,
          crowd_no_send: 1,
          marke_days: 14
        };
      }
    },
    // 模板消息初始化
    templateInit(template) {
      this.template.templateKeyDataList = template.templateKeyDataList;
      this.template.templateKeyDataList.map((v, i) => {
        v.type = v.datas ? v.datas.split('#')[0] : '';
        v.color = v.datas ? '#' + (v.datas.split('#')[1] || '173177') : '#173177';
        this.$set(this.template.templateKeyDataList, i, {
          color: v.color,
          type: v.type,
          createTime: v.createTime,
          datas: v.datas,
          keyName: v.keyName,
          keywords: v.keywords,
          orders: v.orders,
          queryMap: v.queryMap,
          queryOrder: v.queryOrder,
          querySize: v.querySize,
          querySort: v.querySort,
          queryStart: v.queryStart,
          templateId: v.templateId,
          templateKeyDataId: v.templateKeyDataId,
          updateTime: v.updateTime
        });
      });
      this.template.weixinTemplateId = template.weixinTemplateId;
      this.template.templateBusiness = template.templateBusiness;
      this.template.typeCode = template.typeCode;
      this.template.templateName = template.templateName;
      this.template.title = template.title;
      this.template.urlType = template.urlType;
      this.template.header = template.header;
      this.template.remark = template.remark;
      this.template.headerText = this.template.header ? this.template.header.split('#')[0] : '';
      this.template.headerColor = this.template.header ? '#' + (this.template.header.split('#')[1] || '173177') : '#173177';
      this.template.remarkText = this.template.remark ? this.template.remark.split('#')[0] : '';
      this.template.remarkColor = this.template.remark ? '#' + (this.template.remark.split('#')[1] || '173177') : '#173177';
      this.template.updateTime = template.updateTime;
      this.template.jumpUrl = template.jumpUrl;
      this.template.jumpUrlInfo = template.jumpUrlInfo;
      this.template.triggerCode = template.triggerCode;

      this.options.map(v => {
        // console.log(this.template.headerText.indexOf(v.value) > -1);
        if (this.template.headerText.indexOf(v.value) > -1) {
          this.template.headerText = this.template.headerText.replace(v.value, v.label);
        }
        if (this.template.remarkText.indexOf(v.value) > -1) {
          this.template.remarkText = this.template.remarkText.replace(v.value, v.label);
        }
      });
    },
    // 下拉触发模板消息的改变
    changeTemplate() {
      let template = null;
      this.templateOptions.map(v => {
        if (this.triggerCode === v.triggerCode) {
          template = v;
        }
      });
      this.templateInit(template);
    },
    // 预修改模板
    editTemplatePre() {
      this.editDialogShow = true;
      this.copyTemplate = JSON.parse(JSON.stringify(this.template));
    },
    // 修改模板
    editTemplate() {
      this.editDialogShow = false;
      this.template = JSON.parse(JSON.stringify(this.copyTemplate));
    },
    // 预插入变量
    insetVarPre(val) {
      this.varDialogShow = true;
      this.currentTxet = val;
    },
    // 插入变量
    insetVar(val) {
      console.log(val, this.copyTemplate[this.currentTxet]);
      if (typeof this.currentTxet === 'number') {
        this.copyTemplate.templateKeyDataList[this.currentTxet].type += val;
      }
      this.copyTemplate[this.currentTxet] += val;
    },
    // 重置模板
    resetTemplate() {
      this.getEcmInfo(true);
    },
    // 变量弹窗关闭
    close() {
      this.editDialogShow = false;
    },
    // 保存 校验
    submit: _debounce(async function(formName) {
      if (this.loading) {
        return;
      }
      if (this.$refs.marketingEvent.list.length < 1) {
        this.$tips({ type: 'warning', message: '请至少保存一条营销事件' });
        return;
      }
      // // 这里强制获取人群筛选器的配置项
      // await this.$refs.peopleFilter.confirmSet();
      // 判断时间
      if (this.checkBeginEndTime()) return;
      const hasMessageInList = this.$refs.marketingEvent.hasMessageInList();
      // 判断是否能发送短信
      if (hasMessageInList && this.isMessageForbidden()) return;

      if (this.form.effectAction !== 'consume') {
        // 非消费触发 是否包含多倍积分
        const hasIntegralMultiple = this.$refs.marketingEvent.hasIntegralMultiple();
        if (hasIntegralMultiple) {
          this.$tips({ type: 'warning', message: '营销事件配置错误，积分金额倍数只生效于消费触发，请您修改设置' });
          return;
        }
      }

      if (this.form.effectType == 1) {
        // 重复
        // 校验执行频率
        const { execDateType, execDate } = this.form;
        if (execDateType !== 1) {
          // 1按天执行 2按周 3按月
          if (!(execDate && execDate.length)) {
            this.$tips({ type: 'warning', message: '执行频率填写不完整' });
            return;
          }
        }
        if (!this.form.effectTime) {
          this.$tips({ type: 'warning', message: '请填写执行时间' });
          return;
        }
      }

      if (this.form.effectType == 2) {
        // 单次
        this.form.expireType = 0;
        if (this.form.execType === 0) {
          // 定时
          const execTime = this.form.execTime;
          if (!(execTime && execTime[1])) {
            this.$tips({ type: 'warning', message: '请填写执行时间' });
            return;
          }
          // 执行时间得大于当前时间至少10min
          const minDate = Date.now() + 1 * 10 * 60 * 1000;
          if (new Date(execTime).getTime() < minDate) {
            this.$tips({ type: 'warning', message: '执行时间得大于当前时间至少10min' });
            return;
          }
          const time = this.form.execTime.split(' ')[1].split(':');
          const flag = Number(time[0]) < 9 || (Number(time[0]) == 23 && Number(time[2]) > 0);
          if (this.hasRealTime && flag) {
            // 非实时分组人群，当前时段
            this.$tips({ type: 'warning', message: '计划执行时间在9:00-23:00之外，无法选择“非实时”的会员分组' });
            return;
          }
        } else if (this.form.execType !== 1) {
          this.$tips({ type: 'warning', message: '请填写执行时间' });
          return;
        }
      }

      if (this.form.expireType && (!this.form.beginDate || !this.form.endDate)) {
        this.$tips({ type: 'warning', message: '固定期限不能为空' });
        return;
      }

      if (this.form.memberType === 0 && this.toggleTag && !this.getSaveData) {
        this.$tips({ type: 'warning', message: '人群筛选未保存条件' });
        return;
      }
      if (this.form.memberType === 1 && !this.form.memberGroupIds) {
        this.$tips({ type: 'warning', message: '会员分组不能为空' });
        return;
      }
      if (this.form.effectType == 0) {
        if (!this.form.effectAction) {
          this.$tips({ type: 'warning', message: '请选择触发行为' });
          return;
        }
        // 如果是消费触发
        if (this.form.effectAction === 'consume') {
          // 这里判断部分门店是否为空
          if (this.consumeChecked.store && this.consumeChecked.store) {
            let data = this.form.consumerStoreType === 1 ? await this.$refs.newStoreCard.getList() : await this.$refs.storeCard.getRightList();
            if (!data.length) {
              this.$tips({ type: 'warning', message: '门店不能为空' });
              return;
            }
          }
          // 校验勾选
          if (this.consumeChecked.good && !this.xxSysp.goodsFilterId) {
            this.$tips({ type: 'warning', message: '请选择指定消费商品' });
            return;
          }
          // 填一个就行
          if (this.consumeChecked.cost && !this.form.lowest_cost && !this.form.max_cost) {
            this.$tips({ type: 'warning', message: '请填写消费金额区间值' });
            return;
          }
          if (this.form.consum_type == 1) {
            if (this.consumeChecked.cost && this.form.lowest_cost && this.form.max_cost && this.form.lowest_cost > this.form.max_cost) {
              this.$tips({ type: 'warning', message: '消费金额区间值填写错误' });
              return;
            }
            // 填一个就行
            if (this.consumeChecked.count && !this.form.lowest_cost_count && !this.form.max_cost_count) {
              this.$tips({ type: 'warning', message: '请填写消费件数区间值' });
              return;
            }
            if (this.consumeChecked.count && this.form.lowest_cost_count && this.form.max_cost_count && this.form.lowest_cost_count > this.form.max_cost_count) {
              this.$tips({ type: 'warning', message: '消费件数区间值填写错误' });
              return;
            }
            if (this.form.lowest_cost_count && !/^\d+$/.test(this.form.lowest_cost_count)) {
              this.$tips({ type: 'warning', message: '消费件数为正整数' });
              return;
            }
            if (this.form.max_cost_count && !/^\d+$/.test(this.form.max_cost_count)) {
              this.$tips({ type: 'warning', message: '消费件数为正整数' });
              return;
            }
            if (this.discount_limit.flag && this.discount_limit.type == 6 && (isNaN(this.discount_limit.count) || isNaN(this.discount_limit.count2))) {
              this.$tips({ type: 'warning', message: '适用商品折扣区间未填写完整' });
              return;
            }
            // 验证适用商品折扣 discount_limit
            if (this.discount_limit.flag && isNaN(this.discount_limit.count)) {
              this.$tips({ type: 'warning', message: '适用商品折扣额度未填写' });
              return;
            }
            if (this.consumeChecked.payment && !this.checkList.length) {
              this.$tips({ type: 'warning', message: '请至少选择一种支付方式' });
              return;
            }
          }
        }
        // 如果是储值触发
        if (this.form.effectAction === 'stored') {
          if (this.storedChecked && !this.form.storedLowest && !this.form.storedMax) {
            this.$tips({ type: 'warning', message: '请填写储值金额区间值' });
            return;
          }
          if (this.storedChecked && this.form.storedLowest && this.form.storedMax && this.form.storedLowest > this.form.storedMax) {
            this.$tips({ type: 'warning', message: '储值金额区间值填写错误' });
            return;
          }
        }
        // 会员卡升降级
        // if (this.form.effectAction === 'degrade' || this.form.effectAction === 'upgrade') {
        //   if (this.form.gradeIds.length == 0) {
        //     this.$tips({ type: 'warning', message: '请选择触发的会员卡等级' });
        //     return;
        //   }
        // }
      }
      if (this.xsxsFlag == 1) {
        if (this.analyseConfig.open_flag === '') {
          this.$tips({ type: 'warning', message: '请选择是否开启营销分析' });
          return;
        } else if (this.analyseConfig.crowd_send === undefined) {
          this.$tips({ type: 'warning', message: '请填写实验组' });
          return;
        } else if (this.analyseConfig.crowd_no_send === undefined) {
          this.$tips({ type: 'warning', message: '请填写参照组' });
          return;
        } else if (this.analyseConfig.marke_days === undefined) {
          this.$tips({ type: 'warning', message: '请填写营销效果时长' });
          return;
        }
      }
      if (this.isCopy) {
        if (this.form.memberType === 1) {
          let loseMemberIds = this.defaltSelected.filter(el => 'effectiveStatus' in el && el.effectiveStatus === 0).map(el => el.memberTagGroupId);
          let selectedIds = this.form.memberGroupIds.split(',');
          if (loseMemberIds.some(el => selectedIds.includes(el))) {
            return this.$tips({ type: 'warning', message: '所选的会员分组中，有失效的会员分组，请先将失效分组删除后再保存。' });
          }
        }
        if (this.$refs.marketingEvent.hasDeleted) {
          return this.$tips({ type: 'warning', message: '所选的营销事件中，存在已失效或被删除模板的营销事件，请先将失效的营销事件删除后再保存！' });
        }
        if (this.$refs.marketingEvent.hasMaterialDeleted) {
          return this.$tips({ type: 'warning', message: '所选的群发任务中，存在已失效或被删除的营销素材，请先将失效的营销素材删除后再保存！' });
        }
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            ecmPlanId: this.form.ecmPlanId || '',
            templateEcmPlanId: this.isAdd ? this.ecmPlanId : '',
            ecmPlanName: this.form.ecmPlanName, //	是	int	计划名称不能为空,且最多9个汉字
            effectType: this.form.effectType, //是	int	时效: 实时: 0; 每天: 1
            effectTime: this.form.effectType == 1 ? this.form.effectTime : undefined, //否	int	effectType = 1每天时必填, 时效为时间为0-23
            effectAction: this.form.effectType == 0 ? this.form.effectAction : undefined, //	否	string	effectType = 0实时时必填, 关注触发: ‘subscribe’; 认证触发: ‘authentication’
            marketingType: this.form.marketingType, //是	String	营销方式: 卡券营销: ‘card’; 短信营销 : ‘message’; 图文营销: ‘teletext’; 文本营销: ‘text’; 话务: ‘teltask’; 微信图片: ‘image’
            memberType: this.form.memberType,
            memberSearchDTO: this.form.memberType ? this.form.memberGroupIds : this.form.memberSearchDTO,
            searchJson: this.getSaveData,
            expireType: this.form.expireType,
            beginDate: this.form.expireType ? formatDateTimeByType(this.form.beginDate, 'yyyy-MM-dd-HH-mm-ss') : '',
            endDate: this.form.expireType ? formatDateTimeByType(this.form.endDate, 'yyyy-MM-dd-HH-mm-ss') : '',
            brithday_day: this.form.effectType == 1 ? this.form.brithday_day : undefined,
            brithday_type: this.form.effectType == 1 ? this.form.brithday_type : undefined,
            attention_day: this.form.effectType == 1 ? this.form.attention_day : undefined,
            lastCost_day: this.form.effectType == 1 ? this.form.lastCost_day : undefined,
            cardNoticeType: this.form.cardNoticeType,
            templateNoticeFlag: this.form.templateNoticeFlag,
            gradeIds: this.form.gradeIds.join(',') || '',
            marketingTimesType: this.form.marketingTimesType,
            marketingTimes: this.form.marketingTimes,
            execType: this.form.effectType == 2 ? this.form.execType : undefined, // 单次执行类型(1:立即执行; 0:定时执行)
            execTime: this.form.effectType == 2 ? this.form.execTime : undefined, // 单次定时执行时间
            execDateType: this.form.effectType == 1 ? this.form.execDateType : undefined, // 重复执行频率(1:天; 2:周 3:月)
            execDate: this.form.effectType == 1 ? (this.form.execDate ? this.form.execDate.join() : '') : undefined // '周/月(1,2,3,4,5,6,7,)'
          };

          if (this.form.effectType == 1) {
            // 重复
            params.effectTime = Number(this.form.effectTime.split(':')[0]);
            params.marketingTimesType = this.form.marketingOnceFlag ? 0 : -1; // 1对用户营销一次
            params.marketingTimes = 1;
            params.endDate = params.endDate.replace('00:00:00', '23:59:59');
          } else {
            params.effectTime = -1;
          }
          // 如果是消费触发数据处理 - 保存
          // 全部则不传该字段
          // 单笔订单触发 或 累计消费订单触发
          if (this.form.effectType == 0) {
            if (this.form.effectAction === 'consume') {
              // 门店
              let consumeObj = {
                store_mode: this.consumeChecked.store ? 1 : 0,
                consumerStoreType: this.form.consumerStoreType,
                order_store: this.consumeChecked.store ? (this.form.consumerStoreType === 0 ? this.form.order_store : this.form.order_store_new) : ''
              };
              // 勾选消费商品
              if (this.consumeChecked.good && this.xxSysp.goodsFilterId) {
                consumeObj.goods_filter_id = this.xxSysp.goodsFilterId;
                consumeObj.goodsSearchDetail = JSON.stringify({
                  conditionList: this.isEdit ? this.xxSysp.conditionList_copy : this.xxSysp.conditionList, // 编辑保存备份数据
                  filterAbbrInfo: this.xxSysp.filterAbbrInfo
                });
                consumeObj.gift_flag = this.form.gift_flag;
              }

              consumeObj.consum_type = this.form.consum_type;
              // 勾选消费金额  --不填代表没有上下限，不传该字段
              if (this.consumeChecked.cost) {
                if (this.form.lowest_cost) {
                  consumeObj['lowest_cost'] = this.form.lowest_cost;
                }
                if (this.form.max_cost) {
                  consumeObj['max_cost'] = this.form.max_cost;
                }
              }
              // 勾选消费件数
              if (this.consumeChecked.count) {
                if (this.form.lowest_cost_count) {
                  consumeObj['lowest_cost_count'] = this.form.lowest_cost_count;
                }
                if (this.form.max_cost_count) {
                  consumeObj['max_cost_count'] = this.form.max_cost_count;
                }
              }
              // 处理适用商品折扣  未勾选不传这个对象
              if (this.discount_limit.flag) {
                const discount_limit = { ...this.discount_limit };
                delete discount_limit.flag;
                consumeObj.discount_limit = JSON.stringify(discount_limit);
              }
              // 支付方式
              if (this.consumeChecked.payment) {
                params.gic_payment_list = JSON.stringify(this.allList.filter(i => this.checkList.includes(i.payCode)));
                params.gic_payment_flag = this.paymentFlag;
              } else {
                params.gic_payment_flag = 0;
              }

              params = Object.assign(params, consumeObj); // 合并消费触发数据
            }
            if (this.form.effectAction === 'stored' && this.storedChecked) {
              params.effectTriggerJson = JSON.stringify({ lowest_cost: this.form.storedLowest || undefined, max_cost: this.form.storedMax || undefined });
            }
          }
          params.marketingActivityId = this.form.marketingActivityId || ''; //	否	String	营销场景
          // 如果适用人群-人群筛选器可编辑：需要调用await this.$refs.threshold.triggerPeopleSet(); 强制触发回显，否则数据保存有错误
          // await this.triggerPeopleSet();
          /*  模板消息的处理 */
          if (this.currentCard.comName === 'item-card' && ((this.form.cardNoticeType === 1 && this.form.effectType === 0 && this.form.templateNoticeFlag === 1) || this.form.cardNoticeType === 2)) {
            let marketingTemplate = {};
            let header = this.template.headerText;
            let remark = this.template.remarkText;
            this.options.map(v => {
              if (header.indexOf(v.label) > -1) {
                // console.log(new RegExp((v.label+'/g')))
                header = header.replace(v.label, v.value);
              }
              if (remark.indexOf(v.label) > -1) {
                remark = remark.replace(v.label, v.value);
              }
            });
            this.template.templateKeyDataList = this.template.templateKeyDataList.map(v => ({
              keyName: v.keyName,
              keywords: v.keywords,
              datas: v.type + v.color,
              orders: v.orders
            }));
            marketingTemplate = {
              weixinTemplateId: this.template.weixinTemplateId,
              templateBusiness: this.template.templateBusiness,
              typeCode: this.template.typeCode,
              templateName: this.template.templateName,
              title: this.template.title,
              urlType: this.template.urlType,
              jumpUrl: this.template.jumpUrl,
              jumpUrlInfo: this.template.jumpUrlInfo,
              triggerCode: this.template.triggerCode,
              header: header + this.template.headerColor,
              remark: remark + this.template.remarkColor,
              templateKeyDataList: this.template.templateKeyDataList
            };
            params.marketingTemplate = JSON.stringify(marketingTemplate);
          }
          if (this.xsxsFlag == 1) {
            params.analyseJson = JSON.stringify(this.analyseConfig);
          }
          this.saveEcmInfo(params);
        } else {
          this.$tips({ type: 'warning', message: '表单填写不完整' });
          return false;
        }
      });
    }),
    // 保存
    async saveEcmInfo(params) {
      if (this.loading) {
        return;
      }
      if (this.isEdit && this.form.cardNoticeType === 1) {
        this.$tips({ type: 'warning', message: `修改卡券目前不支持微信客服/群发接口` });
        return false;
      }
      if (this.canSelectRealTime && this.hasRealTime) {
        this.$tips({ type: 'warning', message: '计划执行时间在9:00-23:00之外，无法选择“非实时”的会员分组' });
        return false;
      }
      if (this.form.effectType != 0) {
        let count = await this.checkMessageSendCount();
        params.forecastMemberCount = count;
      }
      this.loading = true;
      saveEcmInfo(params)
        .then(res => {
          if (res.errorCode === 0) {
            if (this.isEdit) {
              this.loading = false;
              this.$confirm('操作成功, 是否返回列表?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(() => {
                  this.$router.push('/ecm/list');
                })
                .catch(err => {
                  this.getEcmInfo();
                });
            } else {
              this.$router.push('/ecm/list');
            }
          } else {
            this.loading = false;
            this.$tips({ type: 'error', message: res.message || '操作失败' });
          }
        })
        .catch(err => {
          this.loading = false;
        });
    },
    //加载会员卡等级
    getGradeList() {
      return new Promise((resolve, reject) => {
        klflStrategy({}).then(res => {
          if (res.errorCode === 0) {
            resolve(res.result.gradeList || []);
          }
          reject();
        });
      });
    },
    // 触发行为变化 会员卡升降级
    effectActionChange(isInit = false) {
      if (this.form.effectAction === 'upgrade') {
        if (isInit !== true) this.form.gradeIds = [];
        this.getGradeList().then(data => {
          this.gradeList = data.map((v, i) => {
            if (!i) {
              v.disabled = true;
            }
            return v;
          });
          //  console.log(this.gradeList)
        });
      } else if (this.form.effectAction === 'degrade') {
        if (isInit !== true) this.form.gradeIds = [];
        this.getGradeList().then(data => {
          this.gradeList = data.reverse().map((v, i) => {
            if (!i) {
              v.disabled = true;
            }
            return v;
          });
          // console.log(this.gradeList )
        });
      }
      if (isInit !== true) {
        this.resetConsumType();
      }
    },
    // 消费触发
    handleLowestCost() {
      const { lowest_cost, max_cost } = this.form;
      let info = '';
      if (isEmpty(lowest_cost) && isEmpty(max_cost)) {
        info = '消费金额上下限必填一个';
      } else if (lowest_cost > max_cost && max_cost) {
        info = '消费金额区间设置错误';
      } else if (numOfDecimal(lowest_cost) > 2 || numOfDecimal(max_cost) > 2) {
        info = '消费金额最多保留两位小数';
      }
      this.error_cost_info = info;
      return info;
    },
    handleLowestCostCount() {
      const { lowest_cost_count, max_cost_count } = this.form;
      let info = '';
      if (isEmpty(lowest_cost_count) && isEmpty(max_cost_count)) {
        info = '消费件数上下限必填一个';
      } else if (lowest_cost_count > max_cost_count && max_cost_count) {
        info = '消费件数区间设置错误';
      } else if (numOfDecimal(lowest_cost_count) > 0 || numOfDecimal(max_cost_count) > 0) {
        info = '消费件数必须为正整数';
      }
      this.error_cost_count_info = info;
      return info;
    },
    changeChecked(e) {
      console.log(e);
    },

    /* ----------------辅助方法--------------- */
    // 消费金额触发修改
    handleConsumTypeChange(val) {
      if (val == 1) {
        this.form.marketingTimesType = 0;
        this.form.expireType = 0;
        this.consumeChecked.cost = false;
        this.form.lowest_cost = 1; // 新建时 消费触发 单笔订单 最小值默认为1 方便后端判断
      } else if (val == 2) {
        this.form.marketingTimesType = 1;
        this.form.expireType = 1;
        this.consumeChecked.cost = true;
        this.form.lowest_cost = '';
      }
      this.form.max_cost = '';
      this.form.beginDate = '';
      this.form.endDate = '';
    },
    //  对比开始时间结束时间
    checkBeginEndTime() {
      let beginDate = this.form.beginDate && new Date(this.form.beginDate);
      let endDate = this.form.endDate && new Date(this.form.endDate);
      if (this.form.expireType && beginDate && endDate && beginDate.getTime() > endDate.getTime()) {
        this.$tips({ type: 'warning', message: '开始时间不能大于结束时间' });
        // this.form.beginDate = this.form.endDate;
        this.showMessage = true;
        return true;
      } else if (this.form.expireType && this.form.consum_type == 2 && beginDate && endDate && endDate.getTime() - beginDate.getTime() > 31 * 24 * 60 * 60 * 1000) {
        this.$tips({ type: 'warning', message: '最长时间跨度为31天' });

        this.showMessage = true;
        return true;
      } else {
        this.showMessage = false;
        return false;
      }
    },
    // 是否禁止发短信 逻辑 => 当用户选择每天发送，且短信模板选择为营销短信时，需要判断定时发送时间是否在08:00至22:00之间，若否则停留在新建计划页面，禁止短信群发并进行提醒。
    isMessageForbidden() {
      // console.log(this.$refs.marketingEvent.hasMessageInList(),this.form.effectType === 1,this.form.effectTime)
      if (this.form.effectType === 1 && (this.form.effectTime >= 22 || this.form.effectTime <= 8)) {
        this.$alert(
          `<div>
        <i class="el-icon-warning warning-color fz30 vertical-middle mr20"></i>
        <p class="inline-block vertical-middle w300">短信运营商限制：为避免骚扰用户，营销短信只允许在8点到22点发送</p>
        </div>`,
          '提示',
          {
            dangerouslyUseHTMLString: true,
            showCancelButton: true,
            showConfirmButton: false,
            cancelButtonText: '关闭'
          }
        );
        return true;
      } else {
        return false;
      }
    },
    // 接收的子方法 是否有卡券 value为卡券
    hasCard(value) {
      this.currentCard = value;
    },
    // 初始化门店左侧数据
    initStoreCardLeft() {
      if (this.consumeChecked.store) {
        if (this.isInit) {
          // TODO: 可能会有问题
          // 这里新增的情况下也要初始化 门店组件
          this.$nextTick(_ => {
            this.$refs.storeCard.init();
          });
        } else {
          this.$nextTick(_ => {
            this.$refs.storeCard.initLeftList();
          });
        }
      }
    },
    // 改变单次 定时  time
    changeExecTime(val) {
      if (val && new Date(val) <= new Date()) {
        this.form.execTime = formatDateTimeByType(Date.now() + 1 * 30 * 60 * 1000); // 最多只能选择当前时间的30分钟之后
      }
    },
    /* ----------------人群筛选器的方法--------------- */
    // async triggerPeopleSet() {
    //   await this.$refs.peopleFilter.confirmSet();
    // },
    getData() {
      this.$refs.peopleFilter.confirmSet();
    },
    // 子组件触发父组件事件,返回过滤条件数据 -- 仅新增时保存
    findFilter(value) {
      if (this.isAdd) {
        this.form.memberSearchDTO = value;
      }
    },
    // 取消
    cancelFilter() {
      this.$refs.peopleFilter.cancelSet();
    },
    // 获取需要回显的数据, 供保存时候使用 -- 仅新增时保存
    getBackData(val) {
      return new Promise((resolve, reject) => {
        if (this.isAdd) {
          this.getSaveData = val;
        }
        // console.log(this.getSaveData, val);
        resolve();
      });
    },
    // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
    editShow() {
      this.toggleTag = true;
      this.saveTag = false;
    },
    // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
    editHide() {
      this.toggleTag = false;
      this.saveTag = true;
    },
    // 隐藏保存按钮和确认按钮  (子组件会调用)
    hideBtn() {
      this.toggleTag = false;
      this.saveTag = false;
    },
    handleDataTransferred(data) {
      // 会员分组 情况下 memberSearchDTO 传数组字符串
      // 只有新增时处理数据
      if (this.form.memberType === 1 && this.isAdd) {
        this.form.memberGroupIds = data
          .map(v => {
            this.hasRealTime = this.hasRealTime || v.isRealTime == 0;
            return v.memberTagGroupId;
          })
          .filter(v => v)
          .join(',');
      }
    },
    handleDataLeft(selectedData, selectionToRemove) {
      // 不可编辑
      if (this.form.memberType === 1 && this.isAdd) {
        this.hasRealTime = false;
        this.form.memberGroupIds = selectedData
          .map(v => {
            this.hasRealTime = this.hasRealTime || v.isRealTime == 0;
            return v.memberTagGroupId;
          })
          .filter(v => v)
          .join(',');
      }
    },
    onChangeAnalyseConfig(isOpen, isOpenFlag) {
      if (!isOpen) {
        this.analyseConfig.crowd_send = 4;
        this.analyseConfig.crowd_no_send = 1;
        isOpenFlag && (this.analyseConfig.marke_days = 14);
        isOpenFlag && (this.analyseConfig.crowd_flag = 0);
      }
    },
    onChangeEffectType(val) {
      if (val == 0) {
        this.analyseConfig.crowd_flag = 0;
        this.analyseConfig.crowd_send = 4;
        this.analyseConfig.crowd_no_send = 1;
      }
      this.resetConsumType();
    },
    resetConsumType() {
      //切换时效或触发行为 重置 累计消费的配置
      if (this.form.consum_type == 2) {
        this.form.consum_type = 1;
        this.form.beginDate = '';
        this.form.endDate = '';
      }
    }
  },
  filters: {
    filterDate(val) {
      if (val) {
        return `${new Date(val).getMonth() + 1}月${new Date(val).getDate()}日`;
      } else {
        return '未知时间';
      }
    }
  },
  updated() {
    this.enterpriseId = JSON.parse(localStorage.getItem('dmUserInfo')).enterpriseId;
  },
  mounted() {
    this.enterpriseId = JSON.parse(localStorage.getItem('dmUserInfo')).enterpriseId;
    const Profile = Vue.extend({
      template: '<p>{{ alias }}{{ ppp }}</p>',
      data: function() {
        return {
          alias: 'yeluosen'
        };
      },
      props: ['ppp']
    });
    new Profile().$mount('#mount-point');
    this.gicPaymentList();
  },
  created() {
    getUseStoredFalg().then(res => {
      this.useStoredFlag = res.result.useStoredFlag;
      if (this.useStoredFlag) {
        this.effectActionOptions.push({ value: 'stored', label: '储值触发' });
      }
    });
    getXsxsFalg().then(res => {
      this.xsxsFlag = res.result;
    });
    this.listTemplateVariables();
    this.getCardManualSetting();
  }
};
