<template>
  <div>
    <el-form class="content" ref="form" :model="form" label-width="100px" :rules="rules" v-loading="loading" element-loading-text="拼命加载中">
      <dm-sub-title line>基本信息</dm-sub-title>
      <div class="section">
        <el-form-item label="活动场景">
          {{ form.scene | sceneFilter }}

          <el-button type="text" @click="openTutorial" v-if="form.scene == 3">操作教程</el-button>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-input class="w340" :maxlength="30" placeholder="请输入活动名称" show-word-limit v-model="form.activityName"></el-input>
        </el-form-item>
        <el-form-item label="选择话术" prop="aiTemplateId">
          <el-select filterable class="w340" v-model="form.aiTemplateId" :disabled="isEdit" placeholder="请选择话术" @change="effectActionChange">
            <el-option v-for="item in templateOptions" :key="item.aiTemplateId" :label="item.name" :value="item.aiTemplateId"></el-option>
          </el-select>
          <span class="tips">仅支持选择已上线的话术，若需要增加话术，请联系运营经理</span>
        </el-form-item>
      </div>
      <dm-sub-title line>活动时间</dm-sub-title>
      <div class="section">
        <birthSense ref="activeTime1" :data="birthTimeData" v-show="form.scene == 1" @change="getMemberCount" />
        <holidaySense ref="activeTime2" :data="holidayTimeData" v-show="form.scene == 2" @change="getMemberCount" />
        <activeTime ref="activeTime" :data="activeTimeData" v-show="form.scene == 3 || form.scene == 4 || form.scene == 0" :scene="scene" @change="getMemberCount" />
      </div>
      <dm-sub-title line>人群规则<span class="tips">针对选择的客户仅会执行一次外呼任务。</span></dm-sub-title>
      <div class="section">
        <el-form-item label="参与人群" prop="memberType" required>
          <el-radio-group v-model="form.memberType" @change="getMemberCount">
            <el-radio :label="0">客户筛选</el-radio>
            <el-radio :label="1">客户分组</el-radio>
          </el-radio-group>
          <div>
            <div class="tips" style="margin:0 0 12px 0; " v-if="form.memberType == 0">{{ this.form.scene == 3 ? '默认为全部未添加企微好友的客户' : '默认为权限范围内的全部客户' }}</div>
            <el-button v-if="form.memberType == 0 && !memberCrowdWidgetId && form.scene != 4" size="small" @click="ruleVisible = true">添加其他条件</el-button>
            <ruleFilter v-show="form.memberType == 0 && form.scene != 4" :visiable.sync="ruleVisible" @save="handleRuleFilterSave" :memberCrowdWidgetId="memberCrowdWidgetId" />
            <el-button v-if="form.memberType == 1 && !selectedGroupIds" size="small" @click="groupVisible = true">添加分组</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <gic-new-member-group v-show="form.memberType == 1" :visiable.sync="groupVisible" :selectedIds="selectedGroupIds" @change="confirmGroupDialog" />
        </el-form-item>

        <el-form-item label="消费条件" v-if="form.scene == 4 && form.memberType == 0">
          <div class="consumeLine">
            <el-checkbox v-model="form.consume_days_flag0" :true-label="1" :false-label="0" :disabled="disabledCheck" @change="handleLastconsume">最近消费间隔</el-checkbox>
            <el-input-number v-model="form.consume_days0" @change="handleChangeNum(form.consume_days_flag0)" controls-position="right" :max="730" :min="30" :precision="0" size="small" style="margin:0 10px;" />天
          </div>
          <div class="consumeLine">
            <el-checkbox v-model="form.consume_times_flag0" :true-label="1" :false-label="0" :disabled="disabledCheck" @change="handleLastconsume">最近消费次数</el-checkbox>
            <el-input-number v-model="form.consume_times0" @change="handleChangeNum(form.consume_times_flag0)" controls-position="right" :max="100" :min="1" :precision="0" size="small" style="margin:0 10px;" /> 次
          </div>
          <div class="consumeLine">
            <el-checkbox v-model="form.consume_amount_flag0" :true-label="1" :false-label="0" :disabled="disabledCheck" @change="handleLastconsume">累计消费金额</el-checkbox>
            <el-input-number v-model="form.consume_amount0" @change="handleChangeNum(form.consume_amount_flag0)" controls-position="right" :precision="0" :max="100000" :min="1" size="small" style="margin:0 10px;" /> 元
          </div>
          <el-button size="small" @click="ruleVisible2 = true" v-if="!memberCrowdWidgetId">添加其它条件</el-button>
          <ruleFilter :visiable.sync="ruleVisible2" @save="handleRuleFilterSave" :memberCrowdWidgetId="memberCrowdWidgetId" :hideId="hideId" />
          <span class="tips">勾选消费条件后，添加规则不支持选择【金字塔分层】</span>
        </el-form-item>
        <el-form-item label="消费条件" v-if="form.scene == 4 && form.memberType == 1">
          <div class="consumeLine">
            <el-checkbox v-model="form.consume_days_flag1" @change="getMemberCount" :true-label="1" :false-label="0">最近消费间隔</el-checkbox>
            <el-input-number v-model="form.consume_days1" @change="handleChangeNum(form.consume_days_flag1)" controls-position="right" :max="730" :precision="0" :min="30" size="small" style="margin:0 10px;" />天
          </div>
          <div class="consumeLine">
            <el-checkbox v-model="form.consume_times_flag1" @change="getMemberCount" :true-label="1" :false-label="0">最近消费次数</el-checkbox>
            <el-input-number v-model="form.consume_times1" @change="handleChangeNum(form.consume_times_flag1)" controls-position="right" :max="100" :precision="0" :min="1" size="small" style="margin:0 10px;" /> 次
          </div>
          <div class="consumeLine">
            <el-checkbox v-model="form.consume_amount_flag1" @change="getMemberCount" :true-label="1" :false-label="0">累计消费金额</el-checkbox>
            <el-input-number v-model="form.consume_amount1" @change="handleChangeNum(form.consume_amount1)" controls-position="right" :max="100000" :precision="0" :min="1" size="small" style="margin:0 10px;" /> 元
          </div>
        </el-form-item>
        <el-form-item label="预计覆盖人数">
          <span class="bold">{{ form.planMemberCount }}</span>
          <span class="tips">不包含无手机号的客户，以最终活动覆盖人数为准</span>
        </el-form-item>
      </div>
      <dm-sub-title line>外呼规则配置</dm-sub-title>
      <div class="section">
        <!--根据客户意向打标签 -->
        <div class="card">
          <div class="tagHead">
            <div class="left">
              <div class="title">根据客户意向打标签</div>
              <el-switch v-model="form.labelFlag" :active-value="1" :inactive-value="0" />
            </div>
            <el-button type="text" @click="openTipsDialog(1)">意向等级说明</el-button>
          </div>
          <div v-show="form.labelFlag">
            <div class="tagBody">
              <table>
                <thead>
                  <tr>
                    <th class="tableHead">客户意向等级</th>
                    <th class="tableHead">选择标签</th>
                    <th class="tableHead">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in tagMatchList" :key="index">
                    <td class="tagSelectCell" style="width:420px">
                      <el-form-item prop="options" :rules="validateOption(item.options, form.labelFlag)" label-width="0">
                        <el-select multiple v-model="item.options" size="small" placeholder="请选择意向等级（多选）">
                          <el-option v-for="val in gradeOptions" :value="val.dict_code" :key="val.dict_code" :disabled="selectedTag.includes(val.dict_code)" :label="val.dict_name"> </el-option>
                        </el-select>
                      </el-form-item>
                    </td>
                    <td class="tagSelectCell" style="width:170px">
                      <el-form-item prop="name" :rules="validateVal(item.name, form.labelFlag)" label-width="0">
                        <el-button type="text" v-if="!item.name" @click="openTagsDialog(index)">选择标签</el-button>
                        <el-tag type="mini" v-else closable @close="handleTagClose(index)">{{ item.name }}</el-tag>
                      </el-form-item>
                    </td>
                    <td class="tagSelectCell">
                      <div class="delIcon" type="text" v-show="tagMatchList.length > 1" @click="delTagList(index)">
                        <i class="iconfont icon-Delete"></i>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="tagFooter">
              <el-button type="text" @click="addTagList"> <i class="iconfont icon-Plus"></i> 添加等级 </el-button>
            </div>
          </div>
        </div>
        <!--根据客户意向发送挂机短信 -->
        <div class="card">
          <div class="tagHead">
            <div class="left">
              <div class="title">根据客户意向发送挂机短信</div>
              <el-switch v-model="form.smsFlag" :disabled="form.scene == 3" :active-value="1" :inactive-value="0" />
            </div>
            <el-button type="text" @click="openTipsDialog(1)">意向等级说明</el-button>
          </div>
          <div v-show="form.smsFlag">
            <div class="tagBody">
              <table>
                <thead>
                  <tr>
                    <th class="tableHead">客户意向等级</th>
                    <th class="tableHead">选择短信模板</th>
                    <th class="tableHead">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in smsList" :key="index">
                    <td class="tagSelectCell" style="width:420px">
                      <el-form-item prop="options" :rules="validateOption(item.options, form.smsFlag)" label-width="0">
                        <el-select multiple v-model="item.options" size="small" placeholder="请选择意向等级（多选）">
                          <el-option v-for="val in gradeOptions" :value="val.dict_code" :key="val.dict_code" :label="val.dict_name" :disabled="selectedSms.includes(val.dict_code)"> </el-option>
                        </el-select>
                      </el-form-item>
                    </td>
                    <td class="tagSelectCell" style="width:170px">
                      <el-form-item prop="title" :rules="validateVal(item.title, form.smsFlag)" label-width="0">
                        <el-button type="text" v-if="!item.title" @click="openSmsDialog(index)">选择短信模板</el-button>
                        <el-tag type="mini" v-else closable @close="handleSmsTemplateClose(item)">{{ item.title }}</el-tag>
                      </el-form-item>
                    </td>
                    <td class="tagSelectCell">
                      <div class="delIcon" v-show="smsList.length > 1" type="text" @click="delSmslist(index)">
                        <i class="iconfont icon-Delete"></i>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="tagFooter">
              <el-button type="text" @click="addSmslist"> <i class="iconfont icon-Plus"></i> 添加等级 </el-button>
            </div>
          </div>
        </div>
        <!--根据未接通状态设置重拨 -->
        <div class="card">
          <div class="tagHead">
            <div class="left">
              <div class="title">根据未接通状态设置重拨</div>
              <el-switch v-model="form.recallFlag" :active-value="1" :inactive-value="0" />
              <div class="tips">开启后，可提高接通率</div>
            </div>
            <el-button type="text" @click="openTipsDialog(2)">未接通状态说明</el-button>
          </div>
          <div v-show="form.recallFlag">
            <div class="tagBody">
              <table>
                <thead>
                  <tr>
                    <th class="tableHead">通话状态</th>
                    <th class="tableHead">重拨次数</th>
                    <th class="tableHead">重拨间隔(分钟)</th>
                    <th class="tableHead">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in recallList" :key="index">
                    <td class="tagSelectCell" style="width:420px">
                      <el-form-item prop="options" :rules="validateOption(item.options, form.recallFlag)" label-width="0">
                        <el-select multiple v-model="item.options" size="small" placeholder="请选择通话状态（多选）">
                          <el-option v-for="val in unlinkOptions" :value="val.dict_code" :key="val.dict_code" :disabled="selectedRecall.includes(val.dict_code)" :label="val.dict_name"> </el-option>
                        </el-select>
                      </el-form-item>
                    </td>
                    <td class="tagSelectCell" style="width:170px">
                      <el-select v-model="item.times" size="small" placeholder="请选择">
                        <el-option v-for="item in timesOptions" :key="item" :label="item" :value="item"></el-option>
                      </el-select>
                    </td>
                    <td class="tagSelectCell" style="width:170px">
                      <el-input-number v-model="item.interval" controls-position="right" :max="60" :min="1" size="small" :precision="0" />
                    </td>
                    <td class="tagSelectCell">
                      <div class="delIcon" v-show="recallList.length > 1" type="text" @click="delRecallList(index)">
                        <i class="iconfont icon-Delete"></i>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="tagFooter">
              <el-button type="text" @click="addRecallList"> <i class="iconfont icon-Plus"></i> 添加等级 </el-button>
            </div>
          </div>
        </div>
      </div>
      <dm-sub-title line>活动分析设置</dm-sub-title>
      <div class="section">
        <el-form-item label="活动分析" required>
          <el-radio v-model="form.analyseFlag" :label="1" @change="onChangeEffectType">开启</el-radio>
          <el-radio v-model="form.analyseFlag" :label="0" @change="onChangeEffectType">关闭</el-radio>
          <div class="analyseTips">
            开启后，可用于统计活动的触达转化收益情况
          </div>
        </el-form-item>
        <div v-if="form.analyseFlag == 1">
          <el-form-item label="分析天数" prop="analyseDays">
            触达日期起 <el-input-number style="width:128px;margin:0 5px;" v-model="form.analyseDays" controls-position="right" :precision="0" :max="31" :min="1" size="small" /> 天之内
            <div class="analyseTips">
              设置从客户被成功触达的日期计算，14 天以内的转化会被被作为此营销活动的转化收益；<br />
              注：最短 1 天，最长 31 天 (以自然日计算)，时长越长，会员的转化与此次营销的相关度越低，请酌情填写分析天数
            </div>
          </el-form-item>
          <el-form-item label="活动目标" prop="analyseAmount"
            >销售额
            <el-input-number style="width:128px;margin:0 5px;" v-model="form.analyseAmount" placeholder="1-99999" controls-position="right" :precision="0" :max="99999" :min="1" size="small" />
            万元
          </el-form-item>
        </div>
      </div>
      <dm-form-bottom>
        <el-button type="primary" @click="submit" :loading="btnLoading">保 存</el-button>
        <el-button @click="$router.go(-1)">返 回</el-button>
      </dm-form-bottom>
    </el-form>
    <lib-message v-if="smsDialogVisible" :show.sync="smsDialogVisible" :useByEcm="false" @sendItem="handleSendItem"></lib-message>
    <tagPop :visiable.sync="tagsDialogVisible" @save="saveTagPop" />
    <el-dialog :title="tipsDialogContent.title" :visible="tipsDialogContent.visible" width="700px" @close="tipsDialogContent.visible = false">
      <div class="gradeContent">
        <div class="tips">
          {{ tipsDialogContent.tips }}
        </div>
        <div class="line" v-for="(item, index) in tipsDialogContent.content" :key="index">
          <div class="title">{{ item.dict_name }}</div>
          <div class="lineContent">{{ item.dict_remark }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import filterAvater from '@/mixins/filterAvater.js';
import { templateList, aiDictList, initActivity, getActivityDetail, getMemberCount } from '@/service/api/aiApi.js';
import birthSense from '@/views/ai/task/components/birthActiveTime.vue';
import holidaySense from '@/views/ai/task/components/holidayActiveTime.vue';
import LibMessage from '@/views/ecm/marketing-event/components/lib-message.vue';
import activeTime from '@/views/ai/task/components/activeTime.vue';
import tagPop from '@/views/ai/task/tagPop.vue';

import { formatDateTimeByType, _debounce } from '@/utils/index';
import gicNewMemberGroup from '@/components/dm-new-member-group/index.vue';
import ruleFilter from '@/components/dm-new-rule/ruleFilter.vue';

export default {
  mixins: [filterAvater],
  data() {
    const memberType = (rule, value, callback) => {
      if (this.form.memberType == 1 && !this.selectedGroupIds) {
        return callback(new Error('客户分组不能为空'));
      }
      callback();
    };
    const validateOption = (item, bool) => ({
      required: true,
      validator: (rule, _, cb) => {
        console.log(item);
        if (bool && item && !item.length) {
          cb(new Error('请选择'));
        }
        cb();
      }
    });
    const validateVal = (item, bool) => ({
      required: true,
      validator: (rule, _, cb) => {
        console.log(item);
        if (bool && !item) {
          cb(new Error('请选择'));
        }
        cb();
      }
    });
    return {
      validateOption,
      validateVal,
      //ai营销场景，一个活动下只有一个计划，一个计划里有多个事件
      form: {
        activityName: '', //活动名称
        activityId: '', //活动id
        scene: '', //活动场景 「1 客户生日」、「2 节日活动邀约」、「3 加企微好友」、「4 客户复购」、「5 其它场景」
        aiTemplateId: '', //话术模板id
        memberType: 0, // 会员类型（0：会员筛选，1：会员分组）
        filterJson: '',
        analyseFlag: 1, //活动分析
        consume_days_flag0: 0, // 【最新消费金额 0否1是】
        consume_days0: '',
        consume_times_flag0: 0, //【有效消费次数 0否1是】
        consume_times0: '',
        consume_amount_flag0: 0, // 【累计消费金额 0否1是】
        consume_amount0: '',
        consume_days_flag1: 0, // 【最新消费金额 0否1是】
        consume_days1: '',
        consume_times_flag1: 0, //【有效消费次数 0否1是】
        consume_times1: '',
        consume_amount_flag1: 0, // 【累计消费金额 0否1是】
        consume_amount1: '',
        labelFlag: 0, //是否根据客户意向打标签
        smsFlag: 0, //是否根据客户意向发送挂机短信
        recallFlag: 0, //是否根据未接通状态设置重拨
        planMemberCount: '', //覆盖人数
        analyseDays: '', //分析天数
        analyseAmount: '' //销售额
      },
      birthTimeData: {
        // 生日场景 活动时间的回显
        birth_days: ' ', // 生日前xx天
        birthDate1: '', //生日范围 当天
        birthDate2: '', //生日范围 当月
        birth_type: 1, //外呼时间 1当天 2当月 3生日前
        callFlag: 0, //外呼时段 0 默认 1 自定义
        callTime: [{}] // 自定义时段
      },
      holidayTimeData: {
        // 节假日场景 活动时间
        holiday_day: '', // 节日时间
        callFlag: 0, //外呼时段 0 默认 1 自定义
        callTime: [{}] // 自定义时段
      },
      activeTimeData: {
        // 客户复购||其它场景||好友 的活动时间
        activeTime: '', //有效时间
        callFlag: 1, //外呼时段 0 默认 1 自定义
        callTime: [{}] // 自定义时段
      },

      isEdit: this.$route.meta.type === 'edit',
      isAdd: this.$route.meta.type === 'add',
      isCopy: this.$route.meta.type === 'copy',
      groupVisible: false, //客户分组弹窗
      ruleVisible: false, // 客户筛选弹窗
      ruleVisible2: false, // 客户筛选弹窗 复购场景
      tagsDialogVisible: false, //选择标签弹窗
      smsDialogVisible: false, //短信模板弹窗
      gradeOptions: [], //客户意向等级下拉
      unlinkOptions: [], // 未接通等级下拉
      tipsDialogContent: {
        //意向等级说明弹窗||未接通状态说明
        visible: false
      },
      templateOptions: [], //话术模板下拉
      rules: {
        activityName: { required: true, message: '活动名称不能为空' },
        aiTemplateId: { required: true, message: '话术模板不能为空' },
        analyseDays: { required: true, message: '分析天数不能为空' },
        analyseAmount: { required: true, message: '活动目标不能为空' },
        memberType: { required: true, validator: memberType }
      },
      tagMatchList: [
        // 打标签列表
        {
          options: [],
          id: '',
          name: ''
        }
      ],
      smsList: [
        // 发挂机短信列表
        {
          options: [],
          template: '',
          title: ''
        }
      ],
      recallList: [
        // 重播列表
        {
          options: [],
          times: 2,
          interval: 5
        }
      ],
      timesOptions: [1, 2, 3, 4, 5], //重播次数下拉
      loading: false,
      currentIndex: 0,
      selectedGroupIds: '', // 被选中的客户分组id
      memberCrowdWidgetId: null, // 被选的规则id
      filterFrontShow: [], // 筛选器回显数据
      hideIdVal: ['0f1c75e854ed4b05bd6baa2a757c1701'],
      btnLoading: false
    };
  },
  computed: {
    hideId() {
      if (this.form.consume_days_flag0 || this.form.consume_times_flag0 || this.form.consume_amount_flag0) {
        return ['0f1c75e854ed4b05bd6baa2a757c1701']; // 隐藏客户筛选中的金字塔分层
      } else {
        return [];
      }
    },
    disabledCheck() {
      return this.filterFrontShow.find(item => this.hideIdVal.includes(item.esScreeningWidgetChainId));
    },
    selectedTag() {
      let arr = [];
      this.tagMatchList.forEach(item => (arr = arr.concat(item.options)));
      return arr;
    },
    selectedSms() {
      let arr = [];
      this.smsList.forEach(item => (arr = arr.concat(item.options)));
      return arr;
    },
    selectedRecall() {
      let arr = [];
      this.recallList.forEach(item => (arr = arr.concat(item.options)));
      return arr;
    }
  },
  mounted() {
    const { scene, id } = this.$route.params;
    this.form.scene = scene && Number(scene);
    this.getTemplateList();
    this.getAiDictList();
    if (this.isAdd) {
      this.$route.meta.refresh = false;
    } else {
      this.getActivityDetail(id);
    }
    if (scene == 3) {
      this.form.smsFlag = 1;
      this.form.analyseFlag = 0;
    }
  },
  components: {
    birthSense,
    holidaySense,
    activeTime,
    LibMessage,
    gicNewMemberGroup,
    ruleFilter,
    tagPop
  },
  methods: {
    async getActivityDetail(activityId) {
      this.loading = true;
      try {
        const { result } = await getActivityDetail({ activityId });
        if (result) {
          const { activityId, activityName, activityPlanList, analyseAmount, analyseDays, analyseFlag, startDate, endDate, scene } = result;
          const { activityEventList, filterJson, memberType, planId, planMemberCount, planName, sceneJson } = activityPlanList[0];
          const { aiEventId, aiTemplateId, callFlag, callTime, eventId, labelFlag, recallFlag, smsFlag, labelJson, recallJson, smsJson } = activityEventList[0];
          const { birth_type, birth_days, holiday_type, holiday_name, holiday_date, consume_days_flag, consume_days, consume_times_flag, consume_times, consume_amount_flag, consume_amount } = JSON.parse(sceneJson);
          this.form = {
            activityName, //活动名称
            activityId, //活动id
            scene, //活动场景 「1 客户生日」、「2 节日活动邀约」、「3 加企微好友」、「4 客户复购」、「5 其它场景」
            aiTemplateId, //话术模板id
            memberType, // 会员类型（0：会员筛选，1：会员分组）
            filterJson,
            analyseFlag, //活动分析
            labelFlag, //是否根据客户意向打标签
            smsFlag, //是否根据客户意向发送挂机短信
            recallFlag, //是否根据未接通状态设置重拨
            planMemberCount: this.isCopy ? 0 : planMemberCount, //覆盖人数
            analyseDays, //分析天数
            analyseAmount, //销售额
            planId,
            planName,
            aiEventId,
            eventId
          };
          if (labelFlag) {
            this.tagMatchList = JSON.parse(labelJson);
          }
          if (smsFlag) {
            this.smsList = JSON.parse(smsJson);
          }
          if (recallFlag) {
            this.recallList = JSON.parse(recallJson);
          }
          if (scene == 4) {
            const obj = {
              consume_days_flag0: 0, // 【最新消费金额 0否1是】
              consume_days0: '',
              consume_times_flag0: 0, //【有效消费次数 0否1是】
              consume_times0: '',
              consume_amount_flag0: 0, // 【累计消费金额 0否1是】
              consume_amount0: '',
              consume_days_flag1: 0, // 【最新消费金额 0否1是】
              consume_days1: '',
              consume_times_flag1: 0, //【有效消费次数 0否1是】
              consume_times1: '',
              consume_amount_flag1: 0, // 【累计消费金额 0否1是】
              consume_amount1: ''
            };
            obj[`consume_days_flag${memberType}`] = consume_days_flag; // 【最新消费金额 0否1是】
            obj[`consume_days${memberType}`] = consume_days;
            obj[`consume_times_flag${memberType}`] = consume_times_flag; //【有效消费次数 0否1是】
            obj[`consume_times${memberType}`] = consume_times;
            obj[`consume_amount_flag${memberType}`] = consume_amount_flag; // 【累计消费金额 0否1是】
            obj[`consume_amount${memberType}`] = consume_amount;

            this.form = Object.assign(obj, this.form);
          }

          if (!this.isEdit) return;
          if (memberType == 0) {
            this.memberCrowdWidgetId = filterJson;
          } else if (memberType == 1) {
            this.selectedGroupIds = filterJson;
          }
          // 不同场景的活动时间回显
          if (scene == 1) {
            this.birthTimeData = {
              //客户生日
              birth_days, // 生日前xx天
              birthDate1: [startDate, endDate], //生日范围 当天
              birthDate2: [startDate, endDate], //生日范围 当月
              birth_type, //外呼时间 1当天 2当月 3生日前
              callFlag, //外呼时段 0 默认 1 自定义
              callTime: callFlag == 1 ? callTime : [] // 自定义时段
            };
          } else if (scene == 2) {
            this.holidayTimeData = {
              // 节假日场景 活动时间
              holiday_type, //  节日活动场景特有值 节日类型 1推荐 2自定义
              holiday_name, // 节日活动场景特有值 节日名称
              holiday_date, //节日活动场景特有值 节日日期
              holiday_day: '', // 节日时间
              callFlag, //外呼时段 0 默认 1 自定义
              callTime: callFlag == 1 ? callTime : [], // 自定义时段
              startDate, //有效时间
              endDate //有效时间
            };
          } else {
            // 加企微好友||客服复购||其他场景
            this.activeTimeData = {
              activeTime: [startDate, endDate], //有效时间
              callFlag, //外呼时段 0 默认 1 自定义
              callTime: callFlag == 1 ? callTime : [] // 自定义时段
            };
          }
        }
      } finally {
        this.loading = false;
      }
    },
    async submit() {
      const activeTimeData = await this.$refs[`activeTime${[1, 2].includes(this.form.scene) ? this.form.scene : ''}`].submit();
      console.log(activeTimeData);
      if (!activeTimeData) return;
      const { startDate, endDate, callFlag, callTime, birth_type, birth_days, holiday_date, holiday_type, holiday_name } = activeTimeData;

      if (new Date(startDate).getFullYear() == new Date().getFullYear() && new Date(startDate).getMonth() + 1 == new Date().getMonth() + 1 && new Date(startDate).getDate() == new Date().getDate()) {
        if (callFlag == 1) {
          let arr = callTime.map(item => item.split('-')[1]);
          let endTime = arr.reduce((p, v) => (p < v ? v : p));
          if (new Date(new Date().toLocaleDateString() + ' ' + endTime).getTime() < new Date().getTime()) {
            this.$message.error('外呼时段的结束时间早于当前时间，今日营销人群无法执行外呼任务，请修改外呼时段');
            return;
          }
        }
      }
      this.$refs.form.validate(async (val, obj) => {
        console.log(val, obj);
        if (val) {
          this.btnLoading = true;
          const { activityName, scene, analyseFlag, analyseDays, analyseAmount, planName, memberType, aiTemplateId, labelFlag, smsFlag, recallFlag, activityId, planId, aiEventId, eventId, planMemberCount } = this.form;
          let sceneJson = {};
          if (scene == 1) {
            sceneJson = {
              birth_type,
              birth_days
            };
          } else if (scene == 2) {
            sceneJson = {
              holiday_date,
              holiday_type,
              holiday_name
            };
          } else if (scene == 4) {
            sceneJson = {
              consume_days_flag: this.form[`consume_days_flag${memberType}`],
              consume_days: this.form[`consume_days${memberType}`],
              consume_times_flag: this.form[`consume_times_flag${memberType}`],
              consume_times: this.form[`consume_times${memberType}`],
              consume_amount_flag: this.form[`consume_amount_flag${memberType}`],
              consume_amount: this.form[`consume_amount${memberType}`]
            };
          }
          sceneJson = JSON.stringify(sceneJson);
          const data = {
            activityId,
            activityName,
            scene,
            startDate,
            endDate,
            analyseFlag,
            analyseDays: analyseFlag == 1 ? analyseDays : undefined,
            analyseAmount: analyseFlag == 1 ? analyseAmount : undefined,
            activityPlanList: [
              {
                planId,
                activityId,
                planName,
                memberType,
                filterJson: memberType == 0 ? this.memberCrowdWidgetId : this.selectedGroupIds,
                planMemberCount,
                beginDate: startDate,
                endDate: endDate,
                sceneJson,
                activityEventList: [
                  {
                    labelFlag,
                    eventId,
                    callFlag,
                    smsFlag,
                    eventType: 'ai',
                    activityId,
                    aiTemplateId,
                    planId,
                    aiEventId,
                    callTime: callFlag == 1 ? callTime : undefined,
                    recallFlag
                  }
                ]
              }
            ]
          };
          if (labelFlag) {
            data.activityPlanList[0].activityEventList[0].labelJson = JSON.stringify(this.tagMatchList);
          }
          if (smsFlag) {
            data.activityPlanList[0].activityEventList[0].smsJson = JSON.stringify(this.smsList);
          }
          if (recallFlag) {
            data.activityPlanList[0].activityEventList[0].recallJson = JSON.stringify(this.recallList);
          }
          if (this.isCopy) {
            delete data.activityId;
            delete data.activityPlanList[0].planId, delete data.activityPlanList[0].activityId;
            delete data.activityPlanList[0].activityEventList[0].eventId;
            delete data.activityPlanList[0].activityEventList[0].activityId;
            delete data.activityPlanList[0].activityEventList[0].planId;
            delete data.activityPlanList[0].activityEventList[0].aiEventId;
          }
          try {
            const { result } = await initActivity(data);
            if (result) {
              this.$message.success('保存成功');
              this.$route.meta.refresh = true;
              this.$router.go(-1);
            }
          } finally {
            this.btnLoading = false;
          }
        } else {
          this.scrollToError(this);
        }
      });
    },
    async getMemberCount() {
      const activeTimeData = await this.$refs[`activeTime${[1, 2].includes(this.form.scene) ? this.form.scene : ''}`].submit();
      if (!activeTimeData) return;
      const { startDate, endDate, birth_type, birth_days, holiday_date, holiday_type, holiday_name } = activeTimeData;
      const { scene, memberType } = this.form;
      let sceneJson = {};
      let filterJson = '';
      if (scene == 1) {
        sceneJson = {
          birth_type,
          birth_days
        };
      } else if (scene == 2) {
        sceneJson = {
          holiday_date,
          holiday_type,
          holiday_name
        };
      } else if (scene == 4) {
        sceneJson = {
          consume_days_flag: this.form[`consume_days_flag${memberType}`],
          consume_days: this.form[`consume_days${memberType}`],
          consume_times_flag: this.form[`consume_times_flag${memberType}`],
          consume_times: this.form[`consume_times${memberType}`],
          consume_amount_flag: this.form[`consume_amount_flag${memberType}`],
          consume_amount: this.form[`consume_amount${memberType}`]
        };
      }
      sceneJson = JSON.stringify(sceneJson);
      if (memberType == 0) {
        filterJson = this.memberCrowdWidgetId;
      } else if (memberType == 1) {
        filterJson = this.selectedGroupIds;
      }
      const data = {
        memberType,
        sceneJson,
        endDate: formatDateTimeByType(endDate, 'yyyy-MM-dd'),
        beginDate: formatDateTimeByType(startDate, 'yyyy-MM-dd'),
        filterJson
      };
      const { result } = await getMemberCount(data);
      this.form.planMemberCount = result == -1 ? 0 : result;
    },
    handleChangeNum: _debounce(function(val) {
      val && this.getMemberCount();
    }, 600),
    openTutorial() {
      window.open('https://www.yuque.com/exnmlu/hpbb1c/wnud7g');
    },
    handleLastconsume() {
      if (this.filterFrontShow.find(item => this.hideIdVal.includes(item.esScreeningWidgetChainId))) {
        this.form.consume_times_flag = 0;
        this.form.consume_days_flag = 0;
        this.form.consume_amount_flag = 0;
        this.$message.warning('选择了金字塔会员分层不支持选择消费条件');
      }
      this.getMemberCount();
      return 0;
    },
    /**客户筛选 */
    handleRuleFilterSave(id, data) {
      this.memberCrowdWidgetId = id;
      this.filterFrontShow = data ? JSON.parse(data.filterFrontShow) : [];
      this.getMemberCount();
    },
    /**客户分组 */
    confirmGroupDialog(arr, idStr) {
      this.selectedGroupIds = idStr;
      this.$refs.form.clearValidate('memberType');
      this.getMemberCount();
    },
    /** 根据客户意向发送挂机短信 */
    delSmslist(index) {
      this.smsList.splice(index, 1);
    },
    addSmslist() {
      this.smsList.push({ options: [], template: '', title: '' });
    },
    openSmsDialog(index) {
      this.smsDialogVisible = true;
      this.currentIndex = index;
    },
    handleSmsTemplateClose(item) {
      const obj = this.smsList.find(val => val.template == item.template);
      obj.template = '';
      obj.title = '';
    },
    handleSendItem(item) {
      const { gicSmsTemplateId, title } = item;
      const row = this.smsList[this.currentIndex];
      row.template = gicSmsTemplateId;
      row.title = title;
    },
    /** 根据未接通状态设置重拨 */
    delRecallList(index) {
      this.recallList.splice(index, 1);
    },
    addRecallList() {
      this.recallList.push({ options: [], times: 2, interval: 5 });
    },
    async openTipsDialog(type) {
      // 1 客户意向等级说明 2 未接通状态说明
      if (type == 1) {
        const obj = {
          title: '客户意向等级说明',
          tips: '系统根据外呼通话情况智能判断客户意向等级',
          content: [...this.gradeOptions]
        };
        this.tipsDialogContent = { ...obj, visible: true };
      } else if (type == 2) {
        const obj = {
          title: '未接通状态说明',
          tips: '系统根据接通前识别到的语音提示关键词判定通话状态',
          content: [...this.unlinkOptions]
        };
        this.tipsDialogContent = { ...obj, visible: true };
      }
    },
    /** 根据客户意向打标签 */
    openTagsDialog(index) {
      this.currentIndex = index;
      this.tagsDialogVisible = true;
    },
    saveTagPop(data) {
      const { tagItemId, tagItemName } = data;
      this.tagMatchList[this.currentIndex].id = tagItemId;
      this.tagMatchList[this.currentIndex].name = tagItemName;
      this.tagMatchList = this.tagMatchList.splice(0);
    },
    handleTagClose(index) {
      console.log(index);
      const obj = this.tagMatchList[index];
      obj.id = '';
      obj.name = '';
    },
    delTagList(index) {
      this.tagMatchList.splice(index, 1);
    },
    addTagList() {
      this.tagMatchList.push({ options: [], id: '', name: '' });
    },
    /** 其他 */
    async getTemplateList() {
      const { result } = await templateList({ status: 5 });
      this.templateOptions = result || [];
    },
    async getAiDictList(dictType) {
      // 营销场景=marketing_activity_scene ，客户意向等级=ai_member_label , 重拨状态=ai_recall_status
      const res1 = await aiDictList({ dictType: 'ai_member_label' });
      const res2 = await aiDictList({ dictType: 'ai_recall_status' });
      this.gradeOptions = res1.result;
      this.unlinkOptions = res2.result;
      this.unlinkOptions.forEach(item => {
        if (item.dict_code && !isNaN(Number(item.dict_code))) {
          item.dict_code = Number(item.dict_code);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.content {
  margin: 10px 20px;
}
.bold {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  line-height: 20px;
}
.section {
  padding: 20px 0 40px 0;
}
.card {
  width: 730px;
  background: #f7f8fa;
  border-radius: 4px;
  box-sizing: border-box;
  margin-top: 20px;
  &:first-child {
    margin-top: 0;
  }
  .tagHead {
    width: 100%;
    height: 60px;
    display: flex;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 20px;
    .left {
      display: flex;
      align-items: center;
      .title {
        width: 173px;
        margin-right: 15px;
      }
    }
  }
  .tagBody {
    border-top: 1px solid #e4e7ed;
    box-sizing: border-box;
    padding: 0 20px;
    table {
      width: 100%;
    }
    .tableHead {
      text-align: left;
      font-weight: bold;
      line-height: 20px;
      color: #303133;
      font-size: 14px;
      height: 52px;
      line-height: 52px;
    }
    .tagSelectCell {
      padding: 0 30px 0 0;
    }
  }

  .tagFooter {
    padding: 0 20px 17px 20px;
  }
}
.gradeContent {
  .line {
    line-height: 20px;
    font-size: 14px;
    margin-top: 20px;
    .title {
      font-weight: bold;
    }
    .lineContent {
      font-weight: 400;
    }
  }
}
.analyseTips {
  margin-top: 6px;
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
}
.consumeLine {
  margin-bottom: 20px;
}
</style>
