<template>
  <el-form ref="form" :model="form" label-width="100px" :rules="rules" v-loading="loading" element-loading-text="拼命加载中" >
    <!-- 计划内容设置 -->
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">计划内容设置</h3>
      <el-form-item label="计划名称" prop="ecmPlanName">
        <dm-input class="w400" :maxlength="9" v-model="form.ecmPlanName" ></dm-input>
      </el-form-item>
      <el-form-item label="时效">
        <el-radio v-model="form.effectType" :label="0" :disabled="!isAdd">实时</el-radio>
        <el-radio class="mr10" v-model="form.effectType" :label="1" :disabled="!isAdd">每天</el-radio>
        <el-select style="width:262px;" v-model="form.effectTime"  v-if="form.effectType"  placeholder="请选择时间">
          <el-option v-for="(v,i) in dayOptions" :key="i" :label="v.label" :value="v.value"></el-option>
        </el-select>
         <div class="layout--tips" v-if="form.effectType">
          <!-- <i class="el-icon-info inline-block"></i> -->
          <div class="layout--tips__content">
          <p><span class="dm-status--primary pl10"></span>每天发送<b class="bold">图文、文本、图片</b>将使用微信群发接口，占用每个用户每月4条的群发次数</p>
          <p><span class="dm-status--primary pl10"></span>每天发送<b class="bold">小程序</b>使用客服接口，但客服接口需要用户在24小时之内与微信公众号互动才能发送成功，可能导致成功率过低，不占用每个用户每月4条的群发次数。</p>
          <p><span class="dm-status--primary pl10"></span>每天发送<b class="bold">短信、卡券、话务</b>均不占用群发次数。</p></div>
        </div>
        <div class="layout--tips" v-else>
          <span class="dm-status--primary pl10"></span>
          实时发送调用微信客服接口，不占用每个用户每月4条的群发次数
        </div>
      </el-form-item>
      <el-form-item label="触发行为" class="width50" v-if="!form.effectType">
        <el-select class="w400" v-model="form.effectAction"  placeholder="选择发送状态">
          <el-option v-for="(v,i) in effectActionOptions" :key="i" :label="v.label" :value="v.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="常用场景" class="width50" v-if="form.effectType">
        <div class="fz12 gray">选填，勾选后生效</div>
        <el-checkbox-group v-model="checked" :max="1">
          <div class="pb10">
            <el-checkbox  class="w150" label="brithday_day">会员生日前 </el-checkbox>
            <el-input-number controls-position="right" :min="0" style="width:244px;" :disabled="checked[0] !== 'brithday_day'" v-model="form.brithday_day"></el-input-number> 天
          </div>
          <div class="pb10">
            <el-checkbox  class="w150" label="attention_day">关注时长超过 </el-checkbox>
            <el-input-number controls-position="right" :min="0" :max="100000" style="width:244px;" :disabled="checked[0] !== 'attention_day'" v-model="form.attention_day"></el-input-number> 天
          </div>
          <div class="pb10">
            <el-checkbox class="w150" label="lastCost_day">最近消费间隔 </el-checkbox>
            <el-input-number controls-position="right" :min="0" style="width:244px;" :disabled="checked[0] !== 'lastCost_day'" v-model="form.lastCost_day"></el-input-number> 天
          </div>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="营销场景">
        <span v-if="isEdit">{{form.sceneSettingName}}</span>
        <el-select  v-else class="w400"  v-model="form.sceneSettingId" placeholder="选择营销场景">
          <el-option v-for="item in sceneSettingIdOptions" :key="item.sceneSettingId" :label="item.sceneName" :value="item.sceneSettingId"></el-option>
        </el-select>
      </el-form-item>
    </section>
    <!-- 有效时间 -->
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">有效时间</h3>
      <el-form-item label="有效时间"  prop="endDate" :show-message="showMessage">
        <el-radio v-model="form.expireType" :label="0">长期有效</el-radio>
        <el-radio v-model="form.expireType" :label="1">固定期限</el-radio>
        <el-date-picker class="ml10" v-if="form.expireType"
          v-model="form.beginDate" type="datetime"
          placeholder="开始时间" @change="checkBeginEndTime">
        </el-date-picker>
        <el-date-picker v-if="form.expireType"
          v-model="form.endDate" type="datetime"
          :picker-options="endDatePickerOptions"
          placeholder="结束时间" @change="checkBeginEndTime">
        </el-date-picker>
      </el-form-item>
    </section>
    <!-- 人群筛选器 -->
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">适用人群</h3>
        <div class="mb20">
            <vue-gic-people :projectName="projectName" :useId="useId" :hasSearchData="hasSearchData" :sceneValue="sceneValue" ref="peopleFilter" @findFilter="findFilter" @getBackData="getBackData"  @editHide= "editHide" @editShow="editShow" @hideBtn="hideBtn"/>
            <div class="gic-people--button" v-show="toggleTag">
              <el-button size="small" type="primary" @click="getData">确 定</el-button>
              <el-button size="small" @click="cancelFilter">取 消</el-button>
            </div>
        </div>
    </section>
    <!-- 营销事件 -->
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">营销事件</h3>
      <marketing-event ref="marketingEvent" @has-card="hasCard" v-if="ecmPlanId" :ecmPlanId="ecmPlanId" :code="code" :enabledMessageState="enabledMessageState"></marketing-event>
    </section>

    <!-- 只有存在卡券的情况下出现卡券通知方式 -->
    <section class="dm-form__wrap" v-if="currentCard.comName">
      <h3 class="dm-title__label">卡券通知方式配置</h3>
      <el-form-item label="通知方式" class="is-required" prop="cardNoticeType">
        <el-radio v-model="form.cardNoticeType" :label="0">不通知
          <el-tooltip placement="top-start" content="不通知用户，但用户可以在GIC卡券包查看到该卡券。建议线下发券使用，或使用其他通知方式代替（如小程序、短信等）">
            <i class="iconfont icon-xinxixianshi pl5 gray"></i>
          </el-tooltip>
          </el-radio>
        <el-radio v-model="form.cardNoticeType" :label="1">微信{{form.effectType?'群发':'客服'}}接口
          <el-tooltip placement="top-start" :content="form.effectType?'建议大规模发券、智能营销定时计划使用，占用每个会员每月4次的营销次数。':'客服接口需要用户在24小时之内与微信公众号互动才能发送成功，不占用每个用户每月4条的群发次数。'">
            <i class="iconfont icon-xinxixianshi pl5 gray"></i>
          </el-tooltip>
        </el-radio>
        <el-radio v-model="form.cardNoticeType" :label="2" :disabled="form.templateUseEnable === 0">微信模板消息
          <el-tooltip placement="top-start">
            <span slot="content">建议小规模发券、智能营销实时计划使用，滥用可能导致模板消息被封。参考微信<a target="_blank" href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751288">《模板消息运营规范》</a></span>
            <i class="iconfont icon-xinxixianshi pl5 gray"></i>
          </el-tooltip>
        </el-radio>
      </el-form-item>
      <!-- 如果时效是实时（0）并且通知方式是微信群发接口（1） 出现补发设置-->
      <el-form-item label="补发设置"  prop="templateNoticeFlag" v-if="form.cardNoticeType === 1 && form.effectType === 0">
        <el-checkbox v-model="form.templateNoticeFlag" :true-label="1" :false-label="0">发送失败使用微信模板消息补发该通知
          <el-tooltip placement="top-start" content="若微信客服接口调用失败，则使用微信模板消息进行补发卡券领取通知。">
            <i class="iconfont icon-xinxixianshi pl5 gray"></i>
          </el-tooltip>
        </el-checkbox>
      </el-form-item>
      <!-- 通知非 不通知-->
      <el-form-item label="效果预览" v-if="form.cardNoticeType">
        <div>
          <!-- 通知方式是微信群发接口 -->
          <item-card :item="currentCard.item" class="mr20" v-if="form.cardNoticeType === 1"></item-card>
          <!-- 模板消息预览 -->
           <!-- （如果时效是实时（0）并且通知方式是微信群发接口（1） 并且 勾选了补发设置 出现补发设置） 或者  通知方式是微信群发接口是模板消息  -->
          <div class="ecm-msg__preview" v-if="(form.cardNoticeType === 1 && form.effectType === 0 && form.templateNoticeFlag === 1) || form.cardNoticeType === 2">
            <div class="ecm-msg__preview--inner">
              <h4 class="pre-templateName">{{template.templateName}}</h4>
              <p class="fz13 gray pre-updateTime">{{template.updateTime | filterDate}}</p>
              <p class="pre-header" :style="'color:'+template.headerColor+';'">{{template.headerText}}</p>
              <p class="pre-keyName" v-for="(v,i) in template.templateKeyDataList" :key="i">
                <template v-if="v.keyName">
                  {{v.keyName}}
                  <span :style="`color:${v.color}`">示例文字</span>
                </template>
              </p>
              <p class="pre-remark" :style="'color:'+template.remarkColor+';'">{{template.remarkText}}</p>
              <div class="pre-foot">
                <span class="fz13">详情</span>
                <i class="el-icon-arrow-right"></i>
              </div>
            </div>
            <div class="text-center">
              <el-button type="text" :disabled="form.templateUseEnable === 0" @click="editTemplatePre">修改</el-button>
              <el-button type="text" :disabled="form.templateUseEnable === 0" @click="resetTemplate">重置</el-button>
            </div>
          </div>
        </div>
        <div class="ecm-send__tips">
          <i class="el-icon-info pl5 gray"></i>
          <span class="fz13">若一个智能营销计划中添加多张卡券，{{form.cardNoticeType === 1?'则会推送多条对话框卡券投放':'只会推送一条模板消息卡券领取'}}通知{{form.templateNoticeFlag?'；使用模板消息补发时只会推送一条模板消息卡券领取通知。':'。'}}</span>
        </div>
      </el-form-item>
    </section>
    <div class="btn-wrap_fixed" :class="{'on':asideShow}">
      <el-button type="primary" @click="submit('form')">保 存</el-button>
      <el-button  @click="$router.go(-1)">返 回</el-button>
    </div>

    <var-dialog :options="options" :show.sync="varShow" @get-data="insetVar"></var-dialog>

    <el-dialog title="修改模板消息" :visible.sync="editDialogShow" width="600px" :before-close="close">
      <div class="ecm-msg__edit">
        <div class="ecm-msg__edit--inner">
          <el-form-item label-width="100px" label="头部文案">
            <el-input type="textarea" :style="'color:'+copyTemplate.headerColor"  v-model="copyTemplate.headerText" :rows="4" class="w450" :maxlength="200"></el-input>
            <div class="input-suffix clearfix">
              <el-color-picker class="ml10 vertical-middle"  v-model="copyTemplate.headerColor"></el-color-picker>
              <el-button type="text" class="vertical-middle" @click="insetVarPre('headerText')">插入变量</el-button>
              <span class="gray fz13 fr mr10">{{copyTemplate.headerText.length}}/200</span>
            </div>
          </el-form-item>
          <el-form-item label-width="100px" :label="v.keyName" v-for="(v,i) in copyTemplate.templateKeyDataList" :key="i">
            <div v-if="v.keyName">
              <span class="vertical-middle">显示接收人{{v.keyName}}</span>
              <el-color-picker class="ml10 vertical-middle"  v-model="v.color"></el-color-picker>
            </div>
          </el-form-item>
          <el-form-item label-width="100px" label="尾部文案">
            <el-input type="textarea" :style="'color:'+copyTemplate.remarkColor" v-model="copyTemplate.remarkText" :rows="4" class="w450" :maxlength="200"></el-input>
            <div class="input-suffix clearfix">
              <el-color-picker class="ml10 vertical-middle"  v-model="copyTemplate.remarkColor"></el-color-picker>
              <el-button type="text" class="vertical-middle" @click="insetVarPre('remarkText')">插入变量</el-button>
              <span class="gray fz13 fr mr10">{{copyTemplate.remarkText.length}}/200</span>
            </div>
          </el-form-item>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogShow = false">取 消</el-button>
      <el-button type="primary" @click="editTemplate">确 定</el-button>
      </span>
    </el-dialog>
  </el-form>
</template>

<script>
import {getEcmInfo,saveEcmInfo} from '@/service/api/ecmApi.js';
import {listTemplateVariables} from '@/service/api/msgApi.js';
import {sceneSettingList} from '@/service/api/commonApi.js';
import {checkMessageSendCount} from '@/service/api/messageApi.js';
import marketingEvent from './marketing-event/index.vue';
import {formateDateTimeByType} from '@/utils/index.js'
import itemCard from './partials/item-card.vue';
import varDialog from './partials/variables.vue'
export default {
  name:'ecm-manage',
  data () {
    return {
      ecmPlanId:'',  // 必传,
      code:'1001',
      loading:false,
      effectActionOptions:[{value:'subscribe',label:'关注触发'},{value:'authentication',label:'认证触发'}],
      // {value:'consume',label:'消费触发'}
      dayOptions:Array(24).fill().map((v,i) =>({value:i,label:i+':00'})),
      sceneSettingIdOptions:[],
      form:{
        ecmPlanName:'',
        effectType:0,
        effectTime:0,
        effectAction:'subscribe',
        sceneSettingId:'',
        sceneSettingName:'',
        expireType:0,
        cardId:'',
        mediaId:'',
        imageTextId:'',
        textContent:'',
        title:'',
        describe:'',
        lateDays:'',
        brithday_day:'',
        attention_day:'',
        lastCost_day:'',
        memberSearchDTO:'',
        beginDate:'',
        endDate:'',
        cardNoticeType:2,
        templateNoticeFlag:0,

        // 判断模板消息能否使用
        templateUseEnable:1,
      },
      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;
        }
      },
      checked:[],
      rules:{
        ecmPlanName:{type:'string', required: true, message: '计划名称不能为空', trigger: 'blur' },
      },
      isEdit:this.$route.meta.type === 'edit',
      isAdd:this.$route.meta.type === 'add',
      // 人群筛选器可传参数
      projectName: '', // 当前项目名
      sceneValue: 'member', // 场景值
      useId: '', // 模板id
      hasSearchData: '' , // 当前页回显的数据(接口返回)
      toggleTag: false, // 控制按钮显示的参数,仅供参考,可自行修改
      getSaveData:'',
      saveTag:false,
      enabledMessageState:0,
      showMessage:false,

      currentCard:{},
      varShow:false,
      currentTxet:'',
      options:[],
      editDialogShow:false
    }
  },
  components:{
    'marketing-event':marketingEvent,
    'item-card':itemCard,
    'var-dialog':varDialog
  },
  computed: {
    asideShow() {
      return this.$store.state.marketing.asideShow
    }
  },
  created(){
    // 设置面包屑
    this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'智能营销',path:'/ecm'},{name:'智能营销管理',path:''}]);
    if (this.isAdd) {
      this.sceneSettingList();
    }
    this.listTemplateVariables();
  },
  methods: {
    /* ----------------核心方法--------------- */
    // 获取变量列表
    async listTemplateVariables() {
      this.loading = true;
      try {
        let res = await listTemplateVariables();
        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)
      }
    },
    // 获取营销场景
    async sceneSettingList() {
        let res = await sceneSettingList();
        this.sceneSettingIdOptions = res.result;
    },
    // 获取ecm信息
    async getEcmInfo(isResetTemplate = false) {
      this.loading = true;
      let res = await getEcmInfo({ecmPlanId:this.$route.params.id});
      this.loading = false;
      // 如果是模板重置不需要重置基本信息
      if (!isResetTemplate) {
        const result = res.result.ecmDTO;
        const commonScene = res.result.commonScene;
        this.enabledMessageState = res.result.enabledMessageState || 0;
        if(result && this.isEdit) {
          this.ecmPlanId = this.form.ecmPlanId = result.ecmPlanId || '';
          this.form.ecmPlanName = result.ecmPlanName;
          this.form.effectType = result.effectType;
          this.form.effectTime = result.effectTime;
          this.form.effectAction = result.effectAction;
          this.form.sceneSettingId = result.sceneSettingId;
          this.form.sceneSettingName = result.sceneSettingName;
          this.form.memberSearchDTO = result.filterJson;
          this.form.expireType = result.expireType;
          if (this.form.expireType){
            this.form.beginDate = result.beginDate || '';
            this.form.endDate = result.endDate || '';
          }
          if (res.result.searchId) {
            this.useId = res.result.searchId || '';
            this.hasSearchData = result.filterJson || '{}';
          }
          if (this.form.effectType === 1) {
            this.form.brithday_day = commonScene.brithday_day;
            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']
            }
          }
          /** '0-不通知 1-微信对话框 2-模板消息' **/
          /** '客服接口发送失败是否使用模板消息进行补发通知 0-不补发 1-补发' **/
          this.form.cardNoticeType = result.cardNoticeType || 0;
          this.form.templateNoticeFlag = result.templateNoticeFlag || 0;
        } else if (this.isAdd) {
          this.ecmPlanId = res.result.templateEcmPlanId || '';
        }
        this.form.templateUseEnable  = res.result.templateUseEnable;
      }

      const template = res.result.marketingTemplate;
      // 模板消息
      if (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);
          }
        });
        console.log(this.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.varShow = 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 (formName) {
      // 判断时间
      if(this.checkBeginEndTime()) return;
      if(this.isMessageForbidden()) return;

      if (this.form.expireType && (!this.form.beginDate || !this.form.endDate)) {
        this.$tips({type:'warning',message:'固定期限不能为空'});
        return;
      }
      if (this.toggleTag && !this.getSaveData ) {
        this.$tips({type:'warning',message:'人群筛选未保存条件'})
        return;
      }
      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.effectTime,	//否	int	effectType = 1每天时必填, 时效为时间为0-23
        effectAction:this.form.effectAction, //	否	string	effectType = 0实时时必填, 关注触发: ‘subscribe’; 认证触发: ‘authentication’
        marketingType:this.form.marketingType,	//是	String	营销方式: 卡券营销: ‘card’; 短信营销 : ‘message’; 图文营销: ‘teletext’; 文本营销: ‘text’; 话务: ‘teltask’; 微信图片: ‘image’
        memberSearchDTO:this.form.memberSearchDTO,
        searchJson:this.getSaveData,
        expireType:this.form.expireType,
        beginDate:this.form.expireType ? formateDateTimeByType(this.form.beginDate,'yyyy-MM-dd-HH-mm-ss') : '',
        endDate:this.form.expireType ? formateDateTimeByType(this.form.endDate,'yyyy-MM-dd-HH-mm-ss') : '',

        cardNoticeType:this.form.cardNoticeType,
        templateNoticeFlag:this.form.templateNoticeFlag
      }

      if (this.form.effectType) {
        params[this.checked[0]] = this.form[this.checked[0]] || 0;
      }

      if (this.isAdd) {
        params.sceneSettingId = this.form.sceneSettingId;//	否	String	营销场景
      }

      /*  模板消息的处理 */
      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);
      }

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveEcmInfo(params);
        } else {
          this.$tips({type:'warning',message:'表单填写不完整'});
          return false;
        }
      });
    },
    // 保存
    saveEcmInfo(params) {
      this.loading = true;
      saveEcmInfo(params).then(res => {
        this.loading = false;
        if (res.errorCode === 0) {
          if (this.isEdit) {
            this.$confirm('操作成功, 是否返回列表?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.go(-1);
            }).catch(err => { this.getEcmInfo(); });
          } else {
            this.$router.go(-1);
          }
        } else {
          this.$tips({type:'error',message:res.message || '操作失败'});
        }
      }).catch(err => {
        this.loading = false;
      })
    },

    /* ----------------辅助方法--------------- */
    //  对比开始时间结束时间
    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 {
        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.$refs.marketingEvent.hasMessageInList() && 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;
    },

    /* ----------------人群筛选器的方法--------------- */
    getData() {
      this.$refs.peopleFilter.confirmSet()
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter(value){
      this.form.memberSearchDTO = value;
    },
    // 取消
    cancelFilter(){
      this.$refs.peopleFilter.cancelSet()
    },
    // 获取需要回显的数据, 供保存时候使用
    getBackData(val) {
      this.getSaveData = val;
    },
    // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
    editShow() {
      this.toggleTag = true
      this.saveTag = false
    },
    // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
    editHide() {
      this.toggleTag = false
      this.saveTag = true
    },
    // 隐藏保存按钮和确认按钮  (子组件会调用)
    hideBtn() {
      this.toggleTag = false;
      this.saveTag = false
    },
  },
  filters:{
    filterDate(val) {
      if (val) {
        return `${new Date(val).getMonth()+1}月${new Date(val).getDate()}日`
      } else {
        return '未知时间';
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .ecm-msg__edit {
    display: inline-block;
    vertical-align: top;
    max-height: 400px;
    overflow: auto;
    &--inner {
      background: #fff;
      width: 565px;
      // margin: 15px auto;
      // padding: 10px;
      /deep/ .input-suffix{
        width: 448px;
        height: 40px;
        background: #f0f2f5;
        border:1px solid #E4E7ED;
        border-top: none;
        border-radius:0 0 4px 4px;
      }
      /deep/ .el-textarea__inner{
        color: inherit;
      }
      /deep/ .el-form-item {
        margin-bottom:3px;
      }
    }
  }
  .ecm-msg__preview{
    position: relative;
    width: 320px;
    display: inline-block;
    vertical-align:middle;
    &--inner {
      border:1px solid #DCDFE6;
      border-radius: 4px;
      background: #fff;
      width: 320px;
      min-height: 100px;
      top: 103px;
      left: 37px;
      padding: 20px 10px 10px;

       .pre-templateName{
         font-size: 17px;
         font-weight: 700;

       }
      .pre-updateTime{
        font-size: 14px;
        line-height: 1.5;
      }
      .pre-header{
        font-size: 15px;
        margin: 10px 0;
      }
      .pre-keyName{
        font-size: 14px;
        line-height: 1.5;
      }
      .pre-remark{
        font-size: 15px;
        margin: 20px 0 10px 0;
      }
      .pre-foot{
        border-top:1px solid #DCDFE6;
        padding-top: 5px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
  .ecm-send__tips{
    display: inline-block;
    border: 1px solid #B3D8FF;
    padding: 10px 20px;
    background: #ECF5FF;
    margin: 10px;
    i {
      color: #1890ff;
    }
  }
</style>
