<template>
  <div class="main">
    <div
      class="chart"
      ref="chart"
    >
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  props: {
    dataList: {
      type: Array,
      default: []
    },
    bColor: {
      type: String,
      default: ''
    },
    lineColor: {
      type: String,
      default: ''
    }
  },
  watch: {
    dataList: function(val) {
      if (val.length > 0) {
        this.init()
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const myChart = this.chart || echarts.init(this.$refs.chart);
      let option = {
        xAxis: {
          type: 'time',
          // boundaryGap: false,
          axisLabel: {
            show: true,
            formatter: (value, index) => {
              return this.dateFormat('HH:MM', new Date(value))
            }
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{c}%'
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100
        },
        grid: {
          left: 28,
          right: 28,
          top: 33,
          bottom: 46
        },
        series: [{
          data: this.dataList,
          type: 'line',
          areaStyle: {
            color: this.bColor
          },
          symbol: 'none',
          lineStyle: {
            color: this.lineColor
          }
        }]
      };

      myChart.setOption(option);
      this.chart = myChart
    },
    dateFormat(fmt, date) {
      let ret;
      const opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      };
      for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
      };
      return fmt;
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  height: 280px;
  width: 100%;
  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>