<template>
  <div class="draw">
    <div id="draw_g2" v-if="!isNone"></div>
    <div class="none" v-else>
      <img :src="require('@/assets/img/chart-no-data.png')" alt="" />
      <p>暂无数据</p>
    </div>
  </div>
</template>
<script>
import * as G2 from '@antv/g2';
import { ecmTouchEffectColumnDiagram, telTaskDiagram, massDiagram } from '@/service/api/ecmApi.js';
export default {
  name: 'touch-charts',
  props: {
    type: String,
    createTime: Number
  },
  data() {
    return {
      chartData: [],
      isNone: false
    };
  },
  mounted() {
    this.getChartData();
  },
  methods: {
    draw() {
      this.chartData = this.formatterData(this.chartData);
      if (!this.chartData.length) return (this.isNone = true); // 营销开始时间为当天
      let valueArr = this.chartData.filter(item => item.value >= 0);
      let rateArr = this.chartData.filter(item => item.rate >= 0);
      let valueFlag = valueArr.every(item => item.value == 0); // value是否出现全为0的情况
      let rateFlag = rateArr.every(item => item.rate == 0); // rate是否出现全为0的情况
      const chart = new G2.Chart({
        container: 'draw_g2',
        forceFit: true,
        height: 376,
        padding: [55, 90, 46, 68]
      });
      chart.source(this.chartData);
      chart.tooltip({
        showMarkers: false,
        shared: true
      });
      chart.legend({
        position: 'top',
        offsetY: -20
      });
      chart.axis('value', {
        grid: {
          type: 'line',
          lineStyle: {
            stroke: '#d9d9d9',
            lineWidth: 1,
            lineDash: [-1, -1]
          }
        }
      });
      chart.scale({
        date: {
          dataKey: 'date',
          type: 'cat'
        },
        value: {
          min: 0,
          ticks: valueFlag ? [0, 2, 4, 6, 8] : '',
          tickCount: 5
        },
        rate: {
          min: 0,
          ticks: rateFlag ? [0, 2, 4, 6, 8] : '',
          tickCount: 5
        }
      });
      chart.axis('rate', {
        label: {
          formatter: text => {
            let num = Number(text);
            if (num > 10000) {
              return num / 10000 + '万';
            }
            return num + '元';
          }
        },
        grid: null
      });
      chart.axis('value', {
        label: {
          formatter: text => {
            let num = Number(text);
            if (num >= 10000) {
              return num / 10000 + '万';
            }
            return num;
          }
        }
      });
      chart
        .interval()
        .position('date*value')
        .color('name', ['rgba(91, 143, 249, 0.85)', 'rgba(90, 216, 166, 0.85)', '#FF9F40'])
        .adjust([
          {
            type: 'dodge',
            marginRatio: 0.1
          }
        ]); // eslint-disable-next-line
      chart
        .line()
        .position('date*rate')
        .color('name', ['#FF9F40']);
      chart.render();
    },
    getChartData() {
      let meth;
      let params = {
        ecmPlanId: this.$route.query.id || this.$route.params.id
      };
      if (!this.type) {
        meth = ecmTouchEffectColumnDiagram;
      } else if (this.type == '话务') {
        meth = telTaskDiagram;
        params.convType = 1;
      } else if (this.type == '群发转话务') {
        meth = telTaskDiagram;
        params.convType = 2;
      } else if (this.type == '群发') {
        meth = massDiagram;
      }
      meth(params).then(res => {
        if (!res.result || !res.result.length) {
          // 没数据的情况
          this.isNone = true;
        } else {
          this.chartData = res.result.map(item => {
            if (item.name == '转化收益') {
              item.rate = item.vaule ? parseFloat(item.vaule) : 0;
              delete item.vaule;
            } else {
              item.value = item.vaule ? parseFloat(item.vaule) : 0;
              delete item.vaule;
            }
            return item;
          });
          this.draw();
        }
      });
    },
    allDate() {
      let arr = [];
      let date = new Date().getTime();
      let oneDay = 86400000;
      this.createTime = parseInt(this.createTime) || 0;
      for (let i = 1; i <= 15; i++) {
        let item = date - oneDay * i;
        let obj = [
          { date: item, value: 0, name: '触达人数' },
          { date: item, value: 0, name: '转化人数' },
          { date: item, rate: 0, name: '转化收益' }
        ];
        arr.unshift(...obj);
      }
      return arr;
    },
    formatterData(chartData) {
      let dateArr = this.allDate();
      chartData.forEach(item => {
        dateArr.forEach(el => {
          if (item.date == this.formatterTime(el.date) && item.name == el.name) {
            if (el.name == '转化收益') el.rate = item.rate;
            else el.value = item.value;
          }
        });
      });
      // 过滤出从营销计划开始之后的数据
      dateArr = dateArr.filter(item => {
        // 设置为天24的时间，因为当天数据任意时间段都要展示
        if (new Date(item.date).setHours(24, 0, 0, 0) >= this.createTime) {
          item.date = this.formatterTime(item.date);
          return item;
        }
      });
      return dateArr;
    },
    formatterTime(val) {
      const t = new Date(val);
      let year = t.getFullYear();
      let month = (t.getMonth() + 1).toString().padStart(2, '0');
      let day = t
        .getDate()
        .toString()
        .padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
};
</script>
<style lang="scss" scoped>
.draw {
  .title {
    padding-left: 12px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 700;
    color: #303133;
    line-height: 22px;
    margin-bottom: 36px;
  }
  #draw_g2 {
    height: 376px;
    margin: 0 auto;
    position: relative;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.45);
    line-height: 17px;
    &::before {
      content: '人数';
      position: absolute;
      top: 10px;
      left: 41px;
    }
    &::after {
      content: '金额';
      position: absolute;
      top: 10px;
      right: 57px;
    }
  }
  .none {
    text-align: center;
    p {
      color: #c0c4cc;
      font-size: 14px;
      padding-bottom: 20px;
    }
  }
}
</style>
