<template>
  <div>
    <div id="myChart" :style="{height: '290px'}" style="display: inline-block;width: 100%;margin-bottom:24px;"></div>
  </div>
</template>

<script>
  export default {
    name: 'Bar',
    props: {
      dataSource: {
        type: Object,
        required: true
      },
      title: {
        type: String,
        default: ''
      }
    },
    watch:{
      dataSource:{
        handler: function (newVal,oldVal) {
          this.initChart();
        }
      }
    },
    methods:{
      initChart() {
        console.log("this.dataSource", this.dataSource)
        var data = this.dataSource
        let myChart = this.$echarts.getInstanceByDom(document.getElementById('myChart'));
        if (!myChart) {
          myChart = this.$echarts.init(document.getElementById('myChart'));
        }
        let xData = [];
        let yData = [];
        if (data) {
          for (var i = 0; i < data["x"].length; i++) {
            xData.push(data["x"][i]);
            yData.push(data["y"][i]);
          }
        }
        // console.log(xData);
        const myOptions = {
          title: {
            left: 'center',
            text: this.title
          },
          tooltip: {
            trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            data: xData
          },
          yAxis: {
            type: 'value',
            name: "能耗/kW·h"
          },
          series: [{
            data: yData,
            type: 'bar',
            name: "能耗"
          }]
        };
        myChart.setOption(myOptions, true)
      },
      }
  }
</script>