<template>
  <div ref="chartRef"
    :class="className"
    :style="{ height: height, width: width }" />
</template>

<script setup>
import * as echarts from 'echarts'
import { useWindowResize } from '@/hooks'

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '350px'
  },
  chartData: {
    type: Object,
    required: true
  }
})

let chart = {}
const chartRef = ref(null)

const setOptions = () => {
  chart.setOption({
    xAxis: {
      data: ['6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      boundaryGap: false,
      axisTick: {
        show: false
      }
    },
    grid: {
      left: 15,
      right: 15,
      bottom: 20,
      top: 30,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      padding: [5, 10]
    },
    yAxis: {
      axisTick: {
        show: false
      }
    },
    legend: {
      data: ['今年销量', '去年销量'],
      textStyle: {
        color: '#888'
      }
    },
    series: [{
      name: '今年销量',
      itemStyle: {
        // normal: {
        color: '#FF005A',
        lineStyle: {
          color: '#FF005A',
          width: 2
        }
        // }
      },
      smooth: true,
      type: 'line',
      data: props.chartData.expectedData,
      // animationEasing: 'cubicInOut',
      animationDuration: 2000
    },
    {
      name: '去年销量',
      smooth: true,
      type: 'line',
      itemStyle: {
        // normal: {
        color: '#3888fa',
        lineStyle: {
          color: '#3888fa',
          width: 2
        },
        areaStyle: {
          color: '#f3f8ff'
        }
        // }
      },
      data: props.chartData.actualData,
      // animationEasing: 'quadraticOut'
      animationDuration: 2000
    }]
  })
}

watch(() => props.chartData, (newData, oldData) => {
  setOptions();
}, { deep: true });

onMounted(() => {
  nextTick(() => {
    chart = echarts.init(chartRef.value)
    setOptions()
  })
})

useWindowResize(() => {
  chart.resize()
})

onBeforeUnmount(() => {
  if (!chart) {
    return
  }
  chart.dispose()
  chart = null
})
</script>
