<template>
  <div class="trend-chart" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'LeaveTrendChart',
  props: {
    chartData: {
      type: Object,
      default: () => ({ xAxis: [], countData: [], dayData: [] })
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart();
      }
    }
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.resizeChart);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeChart);
    this.chart && this.chart.dispose();
  },
  data() {
    return {
      chart: null
    };
  },
  methods: {
    initChart() {
      const dom = this.$refs.chartRef;
      if (!dom) return;
      this.chart = echarts.init(dom);
      const option = {
        title: { text: '按时间请假统计', left: 'center', textStyle: { fontSize: 14 } },
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: { data: ['请假记录数', '请假总小时'], top: 30 },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: [{ type: 'category', data: this.chartData.xAxis }],
        yAxis: [{ type: 'value' }],
        series: [
          { name: '请假记录数', type: 'line', data: this.chartData.countData, smooth: true },
          { name: '请假总小时', type: 'line', data: this.chartData.dayData, smooth: true }
        ]
      };
      this.chart.setOption(option);
    },
    resizeChart() {
      this.chart && this.chart.resize();
    }
  }
};
</script>

<style scoped>
.trend-chart {
  width: 100%;
  height: 100%;
}
</style>