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

<script>
// import * as echarts from "echarts";
import * as echarts from "echarts/core";
import { LineChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
} from "echarts/components";
import { CanvasRenderer } from "echarts/renderers";
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LineChart,
  CanvasRenderer,
]);
let chart = undefined;
export default {
  name: "trendLineChart",
  props: ["list"],
  watch: {},
  data: function() {
    return {
      leftList: [],
      rightList: [],
      chart: undefined,
    };
  },
  filters: {},
  methods: {
    read(v) {
      if (isNaN(v)) return 0;
      let o = v;
      if (v > 10000) {
        o = (v / 10000).toFixed(4) + "万";
      }
      return o;
    },
    formatte() {
      let keys = [],
        values = [],
        title = "";
      this.list.map(v => {
        if (!title) title = v.n || "";
        keys.push(v.t);
        values.push(v.r * 100);
      });
      return {
        title,
        keys,
        values,
      };
    },
    createChart() {
      if (!this.$refs.trendLineChart) return;
      chart = echarts.init(this.$refs.trendLineChart);
      let chartData = this.formatte();
      chart.resize({
        height: (this.$refs.trendLineChart.offsetWidth * 6) / 16,
      });
      var option = {
        xAxis: {
          type: "category",
          data: chartData.keys,
          boundaryGap: false,
          axisLabel: {
            formatter: arr => {
              return arr.split(" ")[0];
            },
          },
        },
        tooltip: {
          trigger: "axis",
          triggerOn: "mousemove",
          axisPointer: {
            type: "line",
            axis: "x",
          },
          formatter(p) {
            let params = p[0] || {}
            return "收视率：" + params.value.toFixed(4) + "%";
          },
        },
        yAxis: {
          type: "value",
            scale: true,
        },
        grid: [{ left: 150, top: "10%", buttom: 0, right: 100 }],
        series: [
          {
            data: chartData.values,
            type: "line",
            smooth: true,
          },
        ],
      };

      option && chart.setOption(option);
    },
  },
  mounted() {
    this.createChart();
  },
  beforeUnmount: function() {
    chart.dispose();
  },
  components: {},
};
</script>
<style>
.trendLineChart {
  width: 100%;
}
</style>
