<template>
  <div class="LiveOverviewChart" ref="LiveOverviewChart"></div>
</template>

<script>
// import * as echarts from "echarts";
// import config from "@/config/index";
import * as echarts from 'echarts/core';
import { BarChart } from 'echarts/charts';
import {
  TitleComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([
  TitleComponent,
  GridComponent,
  CanvasRenderer,
  LegendComponent,
  BarChart,
]);

let chart = undefined;
export default {
  name: 'LiveOverviewChart',
  props: ['list','title','dataKey'],
  data: function () {
    return {};
  },
  filters: {},
  methods: {
    numform(n) {
      let num = n;
      if (isNaN(n)) num = "0";
      else if (n >= 100000000)
        num =
          ((n / 100000000).toFixed(2) - 0 + "").replace(
            /\B(?=(?:\d{3})+\b)/g,
            ","
          ) + "亿";
      else if (n >= 10000)
        num =
          ((n / 10000).toFixed(2) - 0 + "").replace(
            /\B(?=(?:\d{3})+\b)/g,
            ","
          ) + "万";
      else num = (num + "").replace(/\B(?=(?:\d{3})+\b)/g, ",");
      return num;
    },
    createChart() {
      if (!this.$refs.LiveOverviewChart) return;
      chart = echarts.init(this.$refs.LiveOverviewChart,  undefined, {
        height: (this.$refs.LiveOverviewChart.offsetWidth * 6) / 16,
        width: this.$refs.LiveOverviewChart.offsetWidth
      });
      const data = [];
      const key = [];
      const list = JSON.parse(JSON.stringify(this.list)).sort((a, b) => {
        return b[this.dataKey] - a[this.dataKey];
      });
      for (let i = 0; i < list.length; i++) {
        const v = list[i];
        data.push(v[this.dataKey]);
        key.push(v.centerName);
      }
      chart.setOption({
        title: {
          text: this.title,
          subtext: '',
        },
        grid: { left: 80, top: 50, bottom: 30, right: 10 },
        xAxis: {
          type: 'category',
          data: key,
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: v => {
              return this.numform(v);
            },
          },
        },
        series: [
          {
            type: 'bar',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' },
              ]),
            },
            data,
          },
        ],
      });
    },
  },
  mounted() {
    this.createChart();
  },
  beforeUnmount: function () {
    chart.dispose();
  },
  components: {},
};
</script>
<style></style>
