<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">
          <div class="no-data">
            <svg aria-hidden="true" class="no-data-icon">
              <use xlink:href="#icon-cp-no-data"></use>
            </svg>
            暂无数据
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="chart-title">
          话单质量分析
          <el-tooltip placement="top">
            <div slot="content">
              <p>系统根据接通前识别到的语音提示关键词判定通话状态</p>
              <p>已接听：客户接通电话；</p>
              <p>线路问题：客户电话欠费；</p>
              <p>被叫问题：空号、关机、拒接、未接、停机、线路盲区等；</p>
            </div>
            <i class="iconfont icon-QuestionCircleOutlined title-tip-icon"></i>
          </el-tooltip>
        </div>
        <div class="chart-box" id="chart-record">
          <div class="no-data">
            <svg aria-hidden="true" class="no-data-icon">
              <use xlink:href="#icon-cp-no-data"></use>
            </svg>
            暂无数据
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="chart-title">通话时长</div>
        <div class="chart-box">
          <div id="chart-duration">
            <div class="no-data">
              <svg aria-hidden="true" class="no-data-icon">
                <use xlink:href="#icon-cp-no-data"></use>
              </svg>
              暂无数据
            </div>
          </div>
          <div v-if="talkTimeData.length > 0">
            <div class="talk-legend" v-for="el in talkTimeData" :key="el.color">
              <span class="talk-legend-label">
                <i class="talk-legend-icon" :style="{ background: el.color }"></i>
                {{ 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 '@/components/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: 'number',
            unit: 'S'
          }
        ],
        [
          {
            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)
                    .toString()
                    .padStart(2, '0');
                  const m = Math.floor((value % 3600) / 60)
                    .toString()
                    .padStart(2, '0');
                  const s = (value % 60).toString().padStart(2, '0');
                  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 == 'sentMessagesNumber') || (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']
          };
        });
        if (data.filter(el => el.count > 0).length == 0) return;
        document.getElementById('chart-tag').innerHTML = '';
        const chart = new G2.Chart({
          container: 'chart-tag',
          forceFit: true,
          height: 260,
          padding: 0
        });
        chart.source(data.filter(el => el.count > 0));
        chart.coord('theta', {
          radius: 0.75,
          innerRadius: 0.6
        });
        chart.legend(null);
        chart
          .intervalStack()
          .position('count')
          .color('label', ['#2d4dd1', '#239EFF', '#14C9C9', '#05B770', '#F69F3E', '#7D59E0'])
          .label('percent', val => {
            return {
              formatter: (text, item) => {
                return item.point.label + ' ' + 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'] }
        ];
        if (data.filter(el => el.count > 0).length == 0) return;
        document.getElementById('chart-record').innerHTML = '';
        const chart = new G2.Chart({
          container: 'chart-record',
          forceFit: true,
          height: 260,
          padding: 0
        });
        chart.source(data.filter(el => el.count > 0));
        console.log(data);
        chart.coord('theta', {
          radius: 0.75,
          innerRadius: 0.6
        });
        chart.legend(null);
        chart
          .intervalStack()
          .position('count')
          .color('label', ['#2d4dd1', '#239EFF', '#14C9C9'])
          .label('percent', () => {
            return {
              formatter: (text, item) => {
                return item.point.label + ' ' + 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'] }
        ];
        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%;
  min-height: 300px;
  .chart-title {
    margin-top: 30px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    line-height: 20px;
    .title-tip-icon {
      font-size: 14px;
    }
  }
  .chart-box {
    width: 100%;
    height: 220px;
    .no-data {
      text-align: center;
      color: #606266;
      font-size: 14px;
      .no-data-icon {
        display: block;
        width: 120px;
        height: auto;
        margin: 20px auto 0;
      }
    }
    .talk-legend {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 auto;
      font-size: 12px;
      font-weight: 400;
      color: #606266;
      line-height: 17px;
      + .talk-legend {
        margin-top: 10px;
      }
      .talk-legend-label {
        .talk-legend-icon {
          display: inline-block;
          margin-right: 10px;
          width: 9px;
          height: 9px;
          border-radius: 9px;
        }
      }
      .talk-legend-label,
      .talk-legend-count,
      .talk-legend-percent {
        width: 33.33%;
        flex-shrink: 0;
      }
    }
  }
}
</style>
