<template>
  <div 
    id="analysischartLine"
    style="width: 100%"
    :style="{ height: chartHeight + 'px' }"
  ></div>
</template>
<script>
import * as echarts from 'echarts'
import resize from '@/utils/chartMixins/resize'
export default {
  name: "LineChart",
  mixins: [resize],
  data() {
    return {
      chartDom: '',
      chart: '',
      chartHeight: this.tableHeight(214) - 70
    }
  },
  props: {
    chartData: {
      type: Array,
      required: true,
      default: () => {
        return []
      }
    },
    timeDim: {
      type: String,
      default: ''
    }
  },
  watch: {
    chartData: function () {
      this.getChart()
    }
  },
  mounted() {
    window.addEventListener('resize', () => {
      this.chartHeight = this.tableHeight(214) - 70
    })
  },
  methods: {
    getChart() {
      if (
        this.chart !== null &&
        this.chart !== '' &&
        this.chart !== undefined
      ) {
        this.chart.dispose() // 页面多次刷新会出现警告，Dom已经初始化了一个实例，这是销毁实例
      }
      this.chartDom = document.getElementById('analysischartLine')
      this.chart = echarts.init(this.chartDom)
      let tempArr = []
      let xData = []
      let yData = []
      let legendData = []
      if (this.chartData.length === 0) {
        return false
      } else {
        tempArr = this.chartData[0].trendRespVOList
      }
      for (let k = 0; k < tempArr.length; k++) {
        let time = ''
        if (this.timeDim === '3') {
          let year = tempArr[k].time.slice(0,4)
          let weak = tempArr[k].time.slice(4,6)
          time = year+' 第 '+weak+' 周'
        } else {
          time = tempArr[k].time
        }
        xData.push(time)
      }
      for (let i = 0; i < this.chartData.length; i++) {
        let obj = {
          name: this.chartData[i].objName + this.chartData[i].objCode,
          type: 'line',
          stack: 'Total',
          data: []
        }
        legendData.push(this.chartData[i].objName + this.chartData[i].objCode)
        let temp = this.chartData[i].trendRespVOList
        for (let j = 0; j < temp.length; j++) {
          let num = temp[j].useNum ? temp[j].useNum : ''
          obj.data.push(num)
        }
        yData.push(obj)
      }

      var option = {
        color:['#FFDC94','#8EF0AB','#63BDFF','#288AFF','#7164FF'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '4%',
          right: '1%',
          bottom: '1%',
          containLabel: true
        },
        legend: {
          data: legendData,
          right: '1%'
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            rotate: "45"
          }
        },
        yAxis: {
          type: 'value'
        },
        series: yData
      };

      option && this.chart.setOption(option);
    }
  }
}
</script>