<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from './index';
import resize from './mixins/resize';

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    },
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        if(this.chart){
          this.setOptions(val)
        }else{
          this.$nextTick(() => {
            if(this.chartData.sData.length!=0){
              this.initChart()
            }
          })
        }
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      if(this.chartData.sData.length!=0){
        this.initChart()
      }
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');
      this.chart.showLoading({
        text: '加载中...',
        color: '#c23531',
        textColor: '#000',
        maskColor: 'rgba(255, 255, 255, 0.7)',
        zlevel: 0,
      });
      this.setOptions(this.chartData)
    },
    setOptions( chartData ) {
      let sData = [];
      const colorList = ["#633EF3", "#23B799", "#D29D80", "#5db6ef"];
      chartData.sData.forEach((item,index) => {
        sData.push({
          name: item.name, itemStyle: {
            normal: {
              color: colorList[index],
              lineStyle: {
                color: colorList[index],
                width: 2
              }
            }
          },
          smooth: true,
          type: 'line',
          data: item.data,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        })
      });
      console.log(sData)
      this.chart.setOption({
        xAxis: {
          data: chartData.xData || [],
          boundaryGap: false,
          axisTick: {
            show: false
          }
        },
        grid: {
          left: 30,
          right: 40,
          bottom: 10,
          top: 40,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
          // data: ['expected', 'actual']
          top:0,
          bottom:40
        },
        series: sData
      });
      this.$nextTick(()=>{
        this.chart.hideLoading();
      });
    }
  }
}
</script>
