<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="6" v-for="(el, index) in targetList" :key="index">
        <target-group :data-list="el"></target-group>
      </el-col>
    </el-row>
    <el-row class="chart-group">
      <el-col :span="8">
        <div class="chart-title">意向标签</div>
        <div class="chart-box" id="chart-tag">
          <svg aria-hidden="true" class="no-data-icon">
            <use xlink:href="#icon-cp-no-data"></use>
          </svg>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="chart-title">话单质量分析</div>
        <div class="chart-box" id="chart-record">
          <svg aria-hidden="true" class="no-data-icon">
            <use xlink:href="#icon-cp-no-data"></use>
          </svg>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="chart-title">通话时长</div>
        <div class="chart-box">
          <div id="chart-duration">
            <svg aria-hidden="true" class="no-data-icon">
              <use xlink:href="#icon-cp-no-data"></use>
            </svg>
          </div>
          <div v-if="talkTimeData.length > 0">
            <div class="talk-legend" v-for="el in talkTimeData" :key="el.color">
              <i class="talk-legend-icon" :style="{ background: el.color }"></i>
              <span class="talk-legend-label">{{ el.label }}</span>
              <span class="talk-legend-count">{{ numFormat(el.count) }}</span>
              <span class="talk-legend-percent">{{ el.percent }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import G2 from '@antv/g2';
import DataSet from '@antv/data-set';
import { numFormat } from '@/utils/index.js';
import { getOutBound, getIntentionLabel, getBillAnalysis, getCallDuration } from '@/service/api/aiApi.js';
import TargetGroup from './target-group.vue';

export default {
  name: 'AiData',
  components: { TargetGroup },
  props: {
    aiDataShow: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      numFormat,
      activityId: '',
      planId: '',
      // type number:数字、time:时间、amount:金额、rate:百分比
      originTargetList: [
        [
          {
            label: '营销人数',
            tips: '根据每天外呼人数累加',
            value: '',
            key: 'marketingNumber',
            type: 'number'
          },
          {
            label: '已外呼数',
            value: '',
            key: 'outboundNumber',
            type: 'number'
          }
        ],
        [
          {
            label: '总接通数',
            value: '',
            key: 'totalConnectionNumber',
            type: 'number'
          },
          {
            label: '电话接通率',
            tips: '电话接通率：表示任务中接通号码的占比<br/>计算公式为：接通的电话通数/已经外呼的电话通数',
            value: '',
            key: 'telephoneConnectionRate',
            type: 'rate'
          }
        ],
        [
          {
            label: 'A/B类客户意向',
            value: '',
            key: 'customerIntentionsNumber',
            type: 'number'
          },
          {
            label: '接通意向率',
            tips: '接通意向率：表示所有已接通的通话中意向客户占比，其中A类和B类客户为意向客户<br/>计算公式为：A/B类客户意向数/已接通的电话数',
            value: '',
            key: 'connectionIntentionRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '总挂机数',
            value: '',
            key: 'totalHangUps',
            type: 'number'
          },
          {
            label: '挂机率',
            tips: '挂机率表示接通后5s之内挂断的电话<br/>计算公式为：总挂机数/接通的电话通数',
            value: '',
            key: 'hangUpRate',
            type: 'rate'
          }
        ],
        [
          {
            label: '短信发送总数',
            value: '',
            key: 'sentMessagesNumber',
            type: 'number'
          },
          {
            label: '发送成功数',
            value: '',
            key: 'sentSuccessfullyNumber',
            type: 'number'
          }
        ],
        [
          {
            label: '总通话时长',
            value: '',
            key: 'totalCallDuration',
            type: 'time'
          },
          {
            label: '平均通话时长',
            value: '',
            key: 'averageCallDuration',
            type: 'time'
          }
        ],
        [
          {
            label: '活动费用',
            tips: '不包含短信发送失败退回金额',
            value: '',
            unit: '元',
            key: 'activityCost',
            type: 'amount'
          }
        ]
      ],
      // 外呼数据
      targetData: {},
      // 通话时长数据
      talkTimeData: []
    };
  },
  computed: {
    targetList() {
      return this.originTargetList
        .map(el => {
          return el.filter(item => {
            const value = this.targetData[item.key];
            switch (item.type) {
              case 'number':
                item.value = numFormat(value);
                break;
              case 'time':
                item.value = '--';
                if (typeof value == 'number') {
                  const h = Math.floor(value / 3600);
                  const m = Math.floor((value % 3600) / 60);
                  const s = value % 60;
                  item.value = `${h}:${m}:${s}`;
                }
                break;
              case 'amount':
                item.value = numFormat(value);
                break;
              case 'rate':
                item.value = value == null ? '--' : value;
                break;
            }
            // 活动不发送挂机短信时，数据指标不展示短信发送总数的字段
            // 活动未开启活动分析时，数据指标展示活动费用
            return !((this.aiDataShow.smsFlag == 0 && item.key == 'sentSuccessfullyNumber') || (this.aiDataShow.analyseFlag != 0 && item.key == 'activityCost'));
          });
        })
        .filter(el => el.length > 0);
    }
  },
  created() {
    this.activityId = this.$route.params.id;
    this.planId = this.$route.query.planId;
    this.getOutBound();
    this.getIntentionLabel();
    this.getBillAnalysis();
    this.getCallDuration();
  },
  methods: {
    getOutBound() {
      getOutBound({ activityId: this.activityId, planId: this.planId }).then(res => {
        this.targetData = Array.isArray(res.result) && res.result.length > 0 ? res.result[0] : {};
      });
    },
    getIntentionLabel() {
      getIntentionLabel({ activityId: this.activityId, planId: this.planId }).then(res => {
        if (!Array.isArray(res.result) || res.result.length == 0) {
          return;
        }
        const originData = res.result[0];
        const levels = ['A', 'B', 'C', 'D', 'E', 'F'];
        const data = levels.map(el => {
          return {
            label: `${el}级`,
            count: originData['count_' + el],
            percent: originData[el + '_proportion']
          };
        });
        document.getElementById('chart-tag').innerHTML = '';
        const chart = new G2.Chart({
          container: 'chart-tag',
          forceFit: true,
          height: 220,
          padding: 10
        });
        chart.source(data);
        chart.coord('theta');
        chart.legend(false);
        chart
          .intervalStack()
          .position('count')
          .color('percent', ['#2d4dd1', '#239EFF', '#14C9C9', '#05B770', '#F69F3E', '#7D59E0'])
          .label('percent', val => {
            return {
              offset: -40,
              textStyle: {
                fontSize: 10,
                textAlign: 'center',
                shadowBlur: 2,
                shadowColor: 'rgba(0, 0, 0, .45)',
                fill: '#fff'
              },
              formatter: (text, item) => {
                return item.point.label + '\n' + item.point.percent;
              }
            };
          })
          .tooltip('label*count*percent', (label, count, percent) => {
            return {
              title: label,
              name: count,
              value: percent
            };
          })
          .style({ lineWidth: 1, stroke: '#fff' });
        chart.render();
      });
    },
    getBillAnalysis() {
      getBillAnalysis({ activityId: this.activityId, planId: this.planId }).then(res => {
        if (!Array.isArray(res.result) || res.result.length == 0) {
          return;
        }
        const originData = res.result[0];
        const data = [
          { label: '已接通', count: originData['count_3'], percent: originData['3_proportion'] },
          { label: '线路问题', count: originData['count_4'], percent: originData['4_proportion'] },
          { label: '被叫问题', count: originData['count_5'], percent: originData['5_proportion'] }
        ];
        document.getElementById('chart-record').innerHTML = '';
        const chart = new G2.Chart({
          container: 'chart-record',
          forceFit: true,
          height: 220,
          padding: 10
        });
        chart.source(data);
        chart.coord('theta');
        chart.legend(false);
        chart
          .intervalStack()
          .position('count')
          .color('percent', ['#2d4dd1', '#239EFF', '#14C9C9'])
          .label('percent', () => {
            return {
              offset: -40,
              textStyle: {
                fontSize: 10,
                textAlign: 'center',
                shadowBlur: 2,
                shadowColor: 'rgba(0, 0, 0, .45)',
                fill: '#fff'
              },
              formatter: (text, item) => {
                return item.point.label + '\n' + item.point.percent;
              }
            };
          })
          .tooltip('label*count*percent', (label, count, percent) => {
            return {
              title: label,
              name: count,
              value: percent
            };
          })
          .style({ lineWidth: 1, stroke: '#fff' });
        chart.render();
      });
    },
    getCallDuration() {
      getCallDuration({ activityId: this.activityId, planId: this.planId }).then(res => {
        if (!Array.isArray(res.result) || res.result.length == 0) {
          return;
        }
        const originData = res.result[0];
        this.talkTimeData = [
          { label: '<10秒', color: '#2d4dd1', count: originData['less_than_10'], percent: originData['10_proportion'] },
          { label: '10-59秒', color: '#D6B38C', count: originData['10_to_59'], percent: originData['10_to_59_proportion'] },
          { label: '60-119秒', color: '#14C9C9', count: originData['60_to_119'], percent: originData['60_to_119_proportion'] },
          { label: '>120秒', color: '#05B770', count: originData['greater_than_120'], percent: originData['120_proportion'] }
        ];
        this.talkTimeData.splice(3, 1);
        const data = [
          this.talkTimeData.reduce(
            (result, el) => {
              result[el.label] = el.count;
              return result;
            },
            { type: '通话时长' }
          )
        ];

        const ds = new DataSet();
        const dv = ds.createView().source(data);
        dv.transform({
          type: 'fold',
          fields: this.talkTimeData.map(el => el.label), // 展开字段集
          key: '通话时长', // key字段
          value: '通话数量', // value字段
          retains: ['type'] // 保留字段集，默认为除fields以外的所有字段
        });
        document.getElementById('chart-duration').innerHTML = '';
        const chart = new G2.Chart({
          container: 'chart-duration',
          forceFit: true,
          height: 84,
          padding: 0
        });
        chart.source(dv);
        chart.coord().transpose();
        chart.legend(false);
        chart.axis(false);
        chart
          .intervalStack()
          .size(24)
          .position('type*通话数量')
          .color(
            '通话时长',
            this.talkTimeData.map(el => el.color)
          );
        chart.render();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.chart-group {
  width: 100%;
  .chart-title {
    margin-top: 30px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    line-height: 20px;
  }
  .chart-box {
    width: 100%;
    height: 220px;
    text-align: center;
    .no-data-icon {
      width: 80px;
      height: auto;
      margin-top: 20px;
    }
    .talk-legend {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 auto;
      max-width: 400px;
      font-size: 12px;
      font-weight: 400;
      color: #606266;
      line-height: 17px;
      + .talk-legend {
        margin-top: 10px;
      }
      .talk-legend-icon {
        flex-shrink: 0;
        margin-right: 10px;
        width: 9px;
        height: 9px;
        border-radius: 9px;
      }
      .talk-legend-label {
        width: 100%;
        text-align: left;
      }
      .talk-legend-count,
      .talk-legend-percent {
        flex-shrink: 0;
        width: 120px;
        text-align: right;
      }
    }
  }
}
</style>
