<template>
  <div class="detail" v-loading="loading">
    <dm-sub-title type="line">基本信息</dm-sub-title>
    <div class="section">
      <el-descriptions column="4">
        <el-descriptions-item label="活动场景"> {{ form.scene | sceneFilter }}</el-descriptions-item>
        <el-descriptions-item label="活动名称">{{ form.activityName }}</el-descriptions-item>
        <el-descriptions-item label="话术">{{ form.aiTemplateId && templateObject[form.aiTemplateId].name }}</el-descriptions-item>
        <el-descriptions-item label="节日名称" v-if="form.scene == 2">{{ holidayTimeData.holiday_name }}</el-descriptions-item>
        <el-descriptions-item label="节日日期" v-if="form.scene == 2">{{ holidayTimeData.holiday_date }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <dm-sub-title type="line">活动时间</dm-sub-title>
    <div class="section" v-if="form.scene == 1">
      <el-descriptions column="4">
        <el-descriptions-item label="外呼时间" v-if="birthTimeData.birth_type == 3"> 生日前{{ birthTimeData.birth_days }}天</el-descriptions-item>
        <el-descriptions-item label="外呼时间" v-else>{{ birthTimeData.birth_type | birthTypeFilter }}</el-descriptions-item>
        <el-descriptions-item label="外呼时段">{{ birthTimeData.callTime }}</el-descriptions-item>
        <el-descriptions-item label="生日范围" v-if="birthTimeData.birth_type == 1">{{ birthTimeData.birthDate1 }}</el-descriptions-item>
        <el-descriptions-item label="生日范围" v-if="birthTimeData.birth_type == 2">{{ birthTimeData.birthDate2 }}</el-descriptions-item>
        <el-descriptions-item label="生日范围" v-if="birthTimeData.birth_type == 3">{{ birthTimeData.birthDate3 }}</el-descriptions-item>
        <el-descriptions-item label="外呼周期">{{ birthTimeData.activeTime }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="section" v-if="form.scene == 2">
      <el-descriptions column="4">
        <el-descriptions-item label="外呼时间">节日前{{ holidayTimeData.holiday_day }}天内外呼完成</el-descriptions-item>
        <el-descriptions-item label="外呼时段">{{ holidayTimeData.callTime }}</el-descriptions-item>
        <el-descriptions-item label="外呼周期">{{ holidayTimeData.activeTime }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="section" v-if="form.scene == 3 || form.scene == 4 || form.scene == 0 || form.scene == 5">
      <el-descriptions column="4">
        <el-descriptions-item label="外呼时段"> {{ activeTimeData.callTime }}</el-descriptions-item>
        <el-descriptions-item label="外呼周期">{{ activeTimeData.activeTime }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <dm-sub-title type="line">人群规则</dm-sub-title>
    <div class="section">
      <el-descriptions column="4" v-if="form.scene != 5">
        <el-descriptions-item label="参与人群">{{ form.memberType == 0 && !memberCrowdWidgetId ? '全部客户' : '' }} </el-descriptions-item>
        <el-descriptions-item label="预计覆盖人数">
          <span class="numStyle">{{ form.planMemberCount }}</span></el-descriptions-item
        >
      </el-descriptions>
      <el-descriptions column="4" v-else>
        <el-descriptions-item label="号码导入">
          <span class="numStyle">{{ form.planMemberCount }}</span
          >条</el-descriptions-item
        >
      </el-descriptions>
      <ruleFilter v-show="form.memberType == 0 && memberCrowdWidgetId" :memberCrowdWidgetId="memberCrowdWidgetId" onlyRead style="width:100%" />
      <gic-new-member-group v-show="form.memberType == 1" :selectedIds="selectedGroupIds" onlyRead style="width:100%" />
    </div>
    <dm-sub-title type="line">外呼规则配置</dm-sub-title>
    <div class="section">
      <!--根据客户意向打标标签-->
      <div class="card">
        <div class="title">根据客户意向打标标签：{{ form.labelFlag ? '开启' : '未开启' }}</div>
        <div class="content" v-show="form.labelFlag">
          <table>
            <thead>
              <tr>
                <th class="tableHead">意向等级</th>
                <th class="tableHead">标签名称</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in tagMatchList" :key="index">
                <td class="cell" style="width:50%;">
                  {{ item.optionsStr }}
                </td>
                <td class="cell" style="width:50%;">
                  <el-tag type="mini">{{ item.name }}</el-tag>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <!--根据客户意向发送挂机短信：-->
      <div class="card">
        <div class="title">根据客户意向发送挂机短信：{{ form.smsFlag ? '开启' : '未开启' }}</div>
        <div class="content" v-show="form.smsFlag">
          <table>
            <thead>
              <tr>
                <th class="tableHead">意向等级</th>
                <th class="tableHead">短信模板</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in smsList" :key="index">
                <td class="cell" style="width:50%;">
                  {{ item.optionsStr }}
                </td>
                <td class="cell" style="width:50%;">
                  <el-tag type="mini">{{ item.title }}</el-tag>
                  <el-popover placement="top-start" width="200" trigger="hover" :content="item.smsContent">
                    <el-button slot="reference" type="text" class="ml10">查看短信内容 </el-button>
                  </el-popover>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <!--根据客户意向自动重拨：-->
      <div class="card">
        <div class="title">根据客户意向自动重拨：{{ form.recallFlag ? '开启' : '未开启' }}</div>
        <div class="content" v-show="form.recallFlag">
          <table>
            <thead>
              <tr>
                <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="cell">
                  {{ item.optionsStr }}
                </td>
                <td class="cell">
                  {{ item.times }}
                </td>
                <td class="cell">
                  {{ item.interval }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <dm-sub-title type="line">活动分析设置</dm-sub-title>
    <div class="section">
      <el-descriptions column="4">
        <el-descriptions-item label="活动分析"> {{ form.analyseFlag ? '开启' : '未开启' }}</el-descriptions-item>
        <el-descriptions-item label="分析天数" v-if="form.analyseFlag">触达日期起 {{ form.analyseDays }}天之内</el-descriptions-item>
        <el-descriptions-item label="活动目标" v-if="form.analyseFlag">销售额{{ form.analyseAmount }}万元</el-descriptions-item>
      </el-descriptions>
    </div>
  </div>
</template>

<script>
import ruleFilter from '@/components/dm-new-rule/ruleFilter.vue';
import filterAvater from '@/mixins/filterAvater.js';
import { formatDateTimeByType } from '@/utils/index.js';
import { getActivityDetail, aiDictList, templateList, getSmsTemplateEcho } from '@/service/api/aiApi.js';
export default {
  mixins: [filterAvater],
  data() {
    return {
      formatDateTimeByType,
      loading: false,
      form: {},
      birthTimeData: {
        // 生日场景 活动时间的回显
        birth_days: ' ', // 生日前xx天
        birthDate1: '', //生日范围 当天
        birthDate2: '', //生日范围 当月
        birthDate3: '', //生日前几天
        birth_type: 1, //外呼时间 1当天 2当月 3生日前
        callFlag: 0, //外呼时段 0 默认 1 自定义
        callTime: [{}], // 自定义时段
        activeTime: ''
      },
      holidayTimeData: {
        // 节假日场景 活动时间
        holiday_day: '', // 节日时间
        callFlag: 0, //外呼时段 0 默认 1 自定义
        activeTime: '',
        callTime: [{}] // 自定义时段
      },
      activeTimeData: {
        // 客户复购||其它场景||好友 的活动时间
        activeTime: '', //有效时间
        callFlag: 1, //外呼时段 0 默认 1 自定义
        callTime: [{}] // 自定义时段
      },
      tagMatchList: [
        // 打标签列表
      ],
      smsList: [],
      recallList: [],
      gradeObject: {}, //客户意向等级
      unlinkObject: {}, // 未接通等级
      templateObject: {}, //话术模板
      selectedGroupIds: '', // 被选中的客户分组
      memberCrowdWidgetId: '' // 规则筛选器id
    };
  },
  mounted() {
    // this.getTemplateList();
    // this.getAiDictList();
    this.getActivityDetail(this.$route.params.id);
  },
  components: {
    ruleFilter
  },
  filters: {
    birthTypeFilter(val) {
      let str = '';
      switch (val) {
        case 1:
          str = '生日当天';
          break;
        case 2:
          str = '生日当月';
          break;
      }
      return str;
    }
  },
  methods: {
    async getActivityDetail(id) {
      this.loading = true;
      const res1 = await aiDictList({ dictType: 'ai_member_label' });
      const res2 = await aiDictList({ dictType: 'ai_recall_status' });
      const res3 = await templateList({ status: 5 });
      if (res1.result) {
        res1.result.forEach(item => {
          this.gradeObject[item.dict_code] = item;
        });
      }
      if (res2.result) {
        res2.result.forEach(item => {
          this.unlinkObject[item.dict_code] = item;
        });
      }
      if (res3.result) {
        res3.result.forEach(item => {
          this.templateObject[item.aiTemplateId] = item;
        });
      }
      try {
        const { result } = await getActivityDetail({ activityId: id });
        console.log(result);
        if (!result) return;
        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: planMemberCount.toLocaleString(), //覆盖人数
          analyseDays, //分析天数
          analyseAmount, //销售额
          planId,
          planName,
          aiEventId,
          eventId,
          consume_days_flag,
          consume_days,
          consume_times_flag,
          consume_times,
          consume_amount_flag,
          consume_amount
        };
        if (memberType == 0) {
          this.memberCrowdWidgetId = filterJson;
        } else if (memberType == 1) {
          this.selectedGroupIds = filterJson;
        }
        let startDateStr = formatDateTimeByType(startDate, 'yyyy-MM-dd');
        let endDateStr = formatDateTimeByType(endDate, 'yyyy-MM-dd');
        if (scene == 1) {
          // 不同场景的活动时间回显

          this.birthTimeData = {
            //客户生日
            birth_days, // 生日前xx天
            activeTime: [startDateStr, endDateStr].join('~'),
            birth_type, //外呼时间 1当天 2当月 3生日前
            callFlag, //外呼时段 0 默认 1 自定义
            callTime: JSON.parse(callTime).join('，') // 自定义时段
          };
          if (birth_type == 1) {
            this.birthTimeData.birthDate1 = [startDateStr, endDateStr].join('~');
          } else if (birth_type == 2) {
            this.birthTimeData.birthDate2 = [formatDateTimeByType(startDate, 'yyyy-MM'), formatDateTimeByType(endDate, 'yyyy-MM')].join('~');
          } else if (birth_type == 3) {
            this.birthTimeData.birthDate3 = [formatDateTimeByType(startDate + birth_days * 86400000, 'yyyy-MM-dd'), formatDateTimeByType(endDate + birth_days * 86400000, 'yyyy-MM-dd')].join('~');
          }
        } else if (scene == 2) {
          this.holidayTimeData = {
            // 节假日场景 活动时间
            holiday_type, //  节日活动场景特有值 节日类型 1推荐 2自定义
            holiday_name, // 节日活动场景特有值 节日名称
            holiday_date, //节日活动场景特有值 节日日期
            holiday_day: '', // 节日时间
            callFlag, //外呼时段 0 默认 1 自定义
            callTime: JSON.parse(callTime).join('，'), // 自定义时段
            startDate: startDateStr, //有效时间
            activeTime: [startDateStr, endDateStr].join('~'),
            endDate: endDateStr //有效时间
          };
          console.log(new Date(`${holiday_date} 00:00:00`).getTime());
          console.log(startDate);
          this.holidayTimeData.holiday_day = (new Date(`${holiday_date} 00:00:00`).getTime() - startDate) / 86400000;
        } else {
          // 加企微好友||客服复购||其他场景
          this.activeTimeData = {
            activeTime: [startDateStr, endDateStr].join('~'), //有效时间
            callFlag, //外呼时段 0 默认 1 自定义
            callTime: JSON.parse(callTime).join('，') // 自定义时段
          };
        }
        if (labelFlag) {
          this.tagMatchList = JSON.parse(labelJson);
          this.tagMatchList.forEach(item => {
            let arr = [];
            item.options.forEach(val => {
              arr.push(this.gradeObject[val].dict_name);
            });
            item.optionsStr = arr.join('，');
          });
        }
        if (smsFlag) {
          this.smsList = JSON.parse(smsJson);
          let ids = [];
          this.smsList.forEach(item => {
            let arr = [];
            item.options.forEach(val => {
              arr.push(this.gradeObject[val].dict_name);
            });
            ids.push(item.template);
            item.optionsStr = arr.join('，');
          });
          this.getSmsTemplateEcho(ids);
        }
        if (recallFlag) {
          this.recallList = JSON.parse(recallJson);
          this.recallList.forEach(item => {
            let arr = [];
            item.options.forEach(val => {
              arr.push(this.unlinkObject[val].dict_name);
            });
            item.optionsStr = arr.join('，');
          });
        }
      } finally {
        this.loading = false;
      }
    },
    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;
      if (res1.result) {
        res1.result.forEach(item => {
          this.gradeObject[item.dict_code] = item;
        });
      }
      if (res2.result) {
        res2.result.forEach(item => {
          this.unlinkObject[item.dict_code] = item;
        });
      }
    },
    async getTemplateList() {
      const { result } = await templateList({ status: 5 });
      if (result) {
        result.forEach(item => {
          this.templateObject[item.aiTemplateId] = item;
        });
      }
    },
    async getSmsTemplateEcho(id) {
      const { result } = await getSmsTemplateEcho({ ids: id.join(',') });
      if (!result) return;
      let obj = {};
      result.length &&
        result.forEach(item => {
          obj[item.gicSmsTemplateId] = item;
        });
      this.smsList.forEach(item => {
        if (obj[item.template]) {
          item.smsContent = obj[item.template].smsContent;
        }
        this.smsList = this.smsList.slice(0);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.detail {
  margin: 10px 20px;
}
.section {
  padding: 20px 0 18px 0;
}
.numStyle {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  line-height: 20px;
}
.card {
  margin-top: 20px;
  &:first-child {
    margin-top: 0;
  }
  .content {
    width: 100%;
    background: #f7f8fa;
    border-radius: 4px;
    margin-top: 10px;
    box-sizing: border-box;
    padding: 16px 16px;
    table {
      width: 100%;
    }
    .tableHead {
      text-align: left;
      font-weight: bold;
      line-height: 20px;
      color: #303133;
      font-size: 14px;
      line-height: 20px;
    }
    .cell {
      padding: 10px 0 0 0;
      line-height: 20px;
    }
  }
}
</style>
