<template>
  <div class="touch" v-loading="loading">
    <div class="dm-wrap effect">
      <div class="page-title touch-title">
        每日上午更新昨日数据
        <span class="intro_wrap" @click="drawer = true"><i class="iconfont icon-zhibiaoshuoming introlIcon" alt="" /><span class="intro">指标说明</span></span>
      </div>
      <dm-sub-title title-align="space-between">
        计划整体效果
        <el-button type="primary" class="detail" @click="toClue('计划整体')"><i class="iconfont icon-chakanxiangqing"></i>查看详情</el-button>
      </dm-sub-title>
      <touch-charts :type="0" :createTime="$route.query.createTime" />
      <market-list v-if="marketListData.length" :isRepeat="isRepeat" :data="marketListData" :isReference="isReference" :batchNum="batchNum" :batchTimes="batchTime" @toClue="toClue" />
    </div>
    <card-profit v-if="cardLeadTable.length" :list="findTypeIsExist(9)" :tableData="cardLeadTable" />
    <integral v-if="findTypeIsExist(8)" :data="findTypeObj(optionsList, 8)" />
    <batch-send v-if="findTypeIsExist(1) || findTypeIsExist(2) || findTypeIsExist(3)" :task-list="findTypeObj(optionsList, 1)" :tel-traffic-list="findTypeObj(optionsList, 2)" :msg-list="findTypeObj(optionsList, 3)" @toClue="toClue" />
    <phone-traffic v-if="findTypeIsExist(4)" :data="findTypeObj(optionsList, 4)" @toClue="toClue" />
    <short-msg v-if="findTypeIsExist(5)" :data="findTypeObj(optionsList, 5)" />
    <wechat v-if="(findTypeIsExist(6) || findTypeIsExist(7)) && getTouchTypeFlag" :custom-service-data="findTypeObj(optionsList, 6)" :batch-data="findTypeObj(optionsList, 7)" :touch-type="touchType" />
    <description :drawer.sync="drawer" :contentTitle="contentTitle" />
  </div>
</template>
<script>
import description from '@/views/ecm/touch-components/description.vue';
import marketList from '@/views/ecm/touch-components/market-list.vue';
import touchCharts from '@/views/ecm/touch-components/touch-charts.vue';
import cardProfit from '@/views/ecm/touch-components/card/card-profit.vue';
import batchSend from '@/views/ecm/touch-components/batch-send/index.vue';
import phoneTraffic from '@/views/ecm/touch-components/phone-traffic/index.vue';
import shortMsg from '@/views/ecm/touch-components/short-msg/index.vue';
import wechat from '@/views/ecm/touch-components/wechat/index.vue';
import integral from '@/views/ecm/touch-components/integral/index.vue';
import { ecmTouchEffectTable, ecmPlanTouchConfig, getCardLeads, getCardLeadsList, ecmTouchTypeTableList, getTouchType } from '@/service/api/ecmApi.js';
export default {
  name: 'ecm',
  data() {
    return {
      drawer: false,
      loading: false,
      ecmPlanId: '',
      marketListData: [],
      isRepeat: false, // 是否重复营销
      isReference: false,
      batchNum: 0, // 批次数量
      batchTime: '', // 批次时间
      // cardLead: {},
      cardLeadTable: [],
      touchType: {},
      getTouchTypeFlag: false,
      optionsList: [] //type 1 群发任务、2 群发失败-话务、3 群发失败-短信、4 话务、5 短信、6 微信-触点 、7 微信-文本、图文、图片
    };
  },
  components: {
    description,
    marketList,
    touchCharts,
    cardProfit,
    batchSend,
    phoneTraffic,
    shortMsg,
    wechat,
    integral
  },
  mounted() {
    this.ecmPlanId = this.$route.params.id;
    this.getOtherList();
    this.getMarketList();
    this.getTouchConfig();
    Promise.all([this.getCardLeadsSum(), this.getCardLeadTable()]).then(([res1, res2]) => {
      this.cardLeadTable = res1.result && res2.result.length > 1 ? [{ cardName: '合计（按照订单去重）', ...res1.result }] : [];
      this.cardLeadTable = this.cardLeadTable.concat(res2.result || []);
      console.log(res2.result);
    });
    // this.getCardLeadsSum();
    // this.getCardLeadTable();
    this.getTouchTypeList();
  },
  methods: {
    toClue(type) {
      let planName = this.$route.query.name;
      let id = this.$route.params.id;
      let createTime = this.$route.query.createTime;
      this.ecmPlanId = id;
      let effectType = this.$route.query.effectType;
      this.$router.push({ path: '/ecm/clue', query: { planName, id, type, createTime, effectType } });
    },
    // 获取计划整体效果的总数据
    getMarketList() {
      ecmTouchEffectTable({ ecmPlanId: this.ecmPlanId }).then(res => {
        if (!res.result || !res.result.length) {
          this.marketListData = [{ isSales: 1 }, { isSales: 0 }];
          return;
        }
        this.marketListData = res.result.map(item => {
          item.touchRate = item.touchMbrNum * 1 && item.planMbrNum * 1 ? ((item.touchMbrNum / item.planMbrNum) * 100).toFixed(2) : 0;
          item.transformRate = item.touchMbrNum * 1 && item.planMbrNum * 1 ? ((item.convMbrNum / item.touchMbrNum) * 100).toFixed(2) : 0;
          return item;
        });
      });
    },
    // 获取配置信息
    getTouchConfig() {
      ecmPlanTouchConfig({ ecmPlanId: this.ecmPlanId }).then(res => {
        if (!res.result) return;
        this.batchNum = res.result.times ? res.result.times : 0;
        this.batchTime = res.result.lastTime ? new Date(parseInt(res.result.lastTime)).toLocaleString('zh', { hour12: false }).replace(/[\/]/g, '-') : '--';
        let analyseJson = JSON.parse(res.result.analyseJson);
        if (analyseJson && analyseJson.crowd_flag == 1) {
          // 是否开启了参照组开关
          this.isReference = true;
        } else {
          this.isReference = false;
          this.marketListData.forEach((item, index) => {
            // 没开启参照组的时候删除那一组信息
            if (item.isSales == 0) this.marketListData.splice(index, 1);
          });
        }
        this.isRepeat = res.result.effectType == 1 ? true : false;
      });
    },
    // 获取卡券收益数据
    getCardLeadsSum() {
      return getCardLeads({ ecmPlanId: this.$route.params.id });
    },
    getCardLeadTable() {
      return getCardLeadsList({ ecmPlanId: this.$route.params.id });
    },
    // 获取其他所有模块数据
    getOtherList() {
      ecmTouchTypeTableList({ ecmPlanId: this.ecmPlanId }).then(res => {
        this.optionsList = res.result || [];
      });
    },
    // 获取营销类型
    getTouchTypeList() {
      getTouchType({ ecmPlanId: this.$route.params.id })
        .then(res => {
          this.touchType = {};
          const result = Array.isArray(res.result) ? [...new Set(res.result)] : [];
          result.forEach(el => {
            switch (el) {
              case 'text':
                this.touchType.text = '文本';
                break;
              case 'teletext':
                this.touchType.teletext = '图文';
                break;
              case 'wxa':
                this.touchType.wxa = '小程序';
                break;
              case 'image':
                this.touchType.image = '图片';
                break;
            }
          });
        })
        .finally(() => (this.getTouchTypeFlag = true));
    }
  },
  computed: {
    contentTitle() {
      const name = (this.$route.meta && this.$route.meta.aliasName) || this.$route.name; // 有些params跳转的需要用到route.name 这种情况如果meta中有aliasName，优先aliasName
      return name;
    },
    findTypeObj() {
      return (arr, type) => {
        return arr.find(el => el.type == type); // {} 或 undefined
      };
    },
    findTypeIsExist() {
      return type => {
        return this.findTypeObj(this.optionsList, type);
      };
    }
  }
};
</script>
<style lang="scss" scoped>
.effect {
  padding: 0 20px 27px !important;
  margin-bottom: 10px !important;
  .touch-title {
    margin-bottom: 21px;
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #e4e7ed;
    .intro_wrap {
      float: right;
      display: inline-flex;
      align-items: center;
      .introlIcon {
        color: #2f54eb;
        font-size: 16px;
        margin-right: 5px;
      }
      .intro {
        width: 64px;
        height: 22px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #2f54eb;
        line-height: 22px;
        cursor: pointer;
      }
    }
  }
  .detail {
    float: right;
    padding: 0 10px;
    background: rgba(47, 84, 235, 0.1);
    border-radius: 4px;
    height: 32px;
    color: #2f54eb;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    cursor: pointer;
    border: none;
    &:hover {
      color: #597ef7;
    }
    i {
      margin-right: 2px;
    }
  }
}
</style>
