<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-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" 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>活动时间<span class="tips">每天16:00之后不支持创建当天开始的活动</span></dm-sub-title>
      <div class="section">
        <birthSense ref="birthSense" />
      </div>
      <dm-sub-title line>人群规则<span class="tips">针对选择的客户仅会执行一次外呼任务。</span></dm-sub-title>
      <div class="section">
        <el-form-item label="参与人群" prop="memberType" required>
          <el-radio v-model="form.memberType" :label="0" @change="onChangeEffectType">客户筛选</el-radio>
          <el-radio v-model="form.memberType" :label="1" @change="onChangeEffectType">客户分组</el-radio>
        </el-form-item>
        <el-form-item label="预计覆盖人数"><span class="bold">23,098</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-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"> </el-option>
                      </el-select>
                    </td>
                    <td class="tagSelectCell" style="width:170px">
                      <el-button type="text" v-if="!item.name" @click="openTagsDialog(index)">选择标签</el-button>
                      <el-tag type="mini" v-else closable @close="handleTagClose(item)">{{ item.name }}</el-tag>
                    </td>
                    <td class="tagSelectCell">
                      <div class="delIcon" type="text" @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" :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-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"> </el-option>
                      </el-select>
                    </td>
                    <td class="tagSelectCell" style="width:170px">
                      <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>
                    </td>
                    <td class="tagSelectCell">
                      <div class="delIcon" 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-select multiple v-model="item.options" size="small" placeholder="请选择通话状态（多选）">
                        <el-option v-for="val in unlinkOptions" :value="val.dict_code" :key="val.dict_code" :label="val.dict_name"> </el-option>
                      </el-select>
                    </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" />
                    </td>
                    <td class="tagSelectCell">
                      <div class="delIcon" 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>
        <el-form-item label="分析天数" prop="analyseDays">
          触达日期起<el-input class="w100" style="margin:0 5px;" v-model="form.analyseDays" />天之内
          <div class="analyseTips">
            设置从客户被成功触达的日期计算，14 天以内的转化会被被作为此营销活动的转化收益；<br />
            注：最短 1 天，最长 31 天 (以自然日计算)，时长越长，会员的转化与此次营销的相关度越低，请酌情填写分析天数
          </div>
        </el-form-item>
        <el-form-item label="活动目标" prop="analyseAmount">销售额<el-input style="width:128px;margin:0 5px;" placeholder="1-99999" v-model="form.analyseAmount" />万元 </el-form-item>
      </div>
      <dm-form-bottom>
        <el-button type="primary" @click="submit">保 存</el-button>
        <el-button @click="$router.go(-1)">返 回</el-button>
      </dm-form-bottom>
    </el-form>
    <el-dialog title="选择标签" :visible.sync="tagsDialogVisible" width="690px">
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmTagsDialog">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择短信模板" :visible.sync="smsDialogVisible" width="690px">
      <div slot="footer" class="dialog-footer">
        <el-button @click="smsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSmsDialog">确定</el-button>
      </div>
    </el-dialog>
    <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 } from '@/service/api/aiApi.js';
import birthSense from './birthSense.vue';
export default {
  mixins: [filterAvater],
  data() {
    return {
      //ai营销场景，一个活动下只有一个计划，一个计划里有多个事件
      form: {
        activityName: '', //活动名称
        scene: '', //活动场景 「1 客户生日」、「2 节日活动邀约」、「3 加企微好友」、「4 客户复购」、「5 其它场景」
        aiTemplateId: '', //话术模板id
        memberType: 0, // 会员类型（0：会员筛选，1：会员分组）
        filterJson: '{"list":[{"type":"or","list":[{"type":"data","data":{"key":"city","compute":"in","value":"330100"}}]},{"type":"or","list":[{"type":"data","data":{"key":"mainStoreId","compute":"in","value":"e8fdc210a59411ecb9cb9f7ed8d63716","dealKey":"storeWidget"}}]}],"type":"and"}',
        analyseFlag: 1, //活动分析
        labelFlag: 0, //是否根据客户意向打标签
        smsFlag: 0, //是否根据客户意向发送挂机短信
        recallFlag: 0 //是否根据未接通状态设置重拨
      },
      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: '活动目标不能为空' }
      },
      tagMatchList: [
        // 打标签列表
        {
          options: [],
          id: 'fd6b44967aa647bcadfad10706244c56',
          name: '区间'
        },
        {
          options: [],
          id: 'ed30e6a53ce249b0a3a7607903cbd026',
          name: '归属'
        }
      ],
      smsList: [
        // 发挂机短信列表
        {
          options: [],
          template: 'ff8080817f012035017f012193240000',
          title: '虎年促销通知'
        }
      ],
      recallList: [
        // 重播列表
        {
          options: [],
          times: 2,
          interval: 5
        }
      ],
      timesOptions: [1, 2, 3, 4, 5] //重播次数下拉
    };
  },
  mounted() {
    const { scene } = this.$route.query;
    this.form.scene = scene && Number(scene);
    this.getTemplateList();
    this.getAiDictList();
  },
  components: {
    birthSense
  },
  methods: {
    async submit() {
      const activeTimeData = await this.$refs.birthSense.submit();
      if (!activeTimeData) return;
      const { startDate, endDate, call_flag, birth_type, callTime, birth_days } = activeTimeData;
      this.$refs.form.validate(async (val, obj) => {
        console.log(val);
        console.log(obj);
        console.log(this.form);
        if (val) {
          console.log(this.form);
          const { activityName, scene, analyseFlag, analyseDays, analyseAmount, planName, memberType, filterJson, aiTemplateId, labelFlag, smsFlag, recallFlag } = this.form;
          const data = {
            activityName,
            scene,
            startDate,
            endDate,
            analyseFlag,
            analyseDays,
            analyseAmount,
            activityPlanList: [
              {
                beginDate: startDate,
                endDate: endDate,
                planName,
                memberType,
                filterJson,
                sceneJson: JSON.stringify({
                  birth_type,
                  birth_days
                }),
                activityEventList: [
                  {
                    aiTemplateId,
                    eventType: 'ai',
                    call_flag,
                    labelFlag,
                    smsFlag,
                    callTime,
                    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);
          }
          const { result } = await initActivity(data);
          console.log(result);
        }
      });
    },
    /** 根据客户意向发送挂机短信 */
    delSmslist(index) {
      this.smsList.splice(index, 1);
    },
    addSmslist() {
      this.smsList.push({ options: [], template: '', title: '' });
    },
    openSmsDialog() {
      this.smsDialogVisible = true;
    },
    confirmSmsDialog() {
      this.smsDialogVisible = false;
    },
    handleSmsTemplateClose(item) {
      const obj = this.smsList.find(val => val.template == item.template);
      obj.template = '';
      obj.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.tagsDialogVisible = true;
    },
    confirmTagsDialog() {
      this.tagsDialogVisible = false;
    },
    handleTagClose(item) {
      const obj = this.tagMatchList.find(val => val.id == item.id);
      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;
}
.tips {
  font-size: 12px;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
  margin-left: 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%;
    }
    .tagSelectCell {
      padding: 0 30px 12px 0;
    }
  }
  .tableHead {
    text-align: left;
    font-weight: bold;
    line-height: 20px;
    color: #303133;
    font-size: 14px;
    height: 52px;
    line-height: 52px;
  }
  .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;
}
</style>
