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

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

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  },
  // 图表总体数据对象
  chartData: {
    type: Object,
    required: true,
    validator: (val) => {
      // 必要属性
      // title: 图表标题，data：图表系列数据, xData：图表x轴数据, yName：图表y轴名称
      const requiredPrototype = ['title', 'data', 'xData', 'yName']
      return requiredPrototype.every(key => {
        return Object.prototype.hasOwnProperty.call(val, key)
      })

    }
  },
  // 图表是否显示工具
  showTool: {
    type: Boolean,
    default: true
  }
})

let chart = null
const chartRef = ref(null)
const myThousand = ref(true)

const setOptions = () => {
  chart.setOption({
    color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#444648', '#fc8452', '#9a60b4', '#ea7ccc'],
    title: {
      text: props.chartData.title,
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let tooltip = '';
        params.forEach((item) => {
          // 获取系列颜色
          var color = item.color;
          // 拼接提示内容
          tooltip += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + color + ';"></span>' + item.seriesName + ': ' + formatNumberWithUnit({
            value: item.value,
            des: props.chartData.yName,
            carry: myThousand.value
          }) + '<br>';
        });
        return tooltip;
      }
    },
    legend: {
      data: props.chartData.data?.map(o => o.name)
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    toolbox: {
      show: props.showTool,
      feature: {
        saveAsImage: {}, // 保存为图片
        magicType: {
          type: ['line', 'bar', 'stack', 'tiled'] // 切换图表类型
        },
        myThousandTool: {
          show: true,
          title: '切换万单位',
          icon: 'path://M50,50 L100,50 L100,100 L150,100 L150,150 L100,150 L100,200 L50,200 L50,150 L0,150 L0,100 L50,100 Z',
          onclick: () => {
            myThousand.value = !myThousand.value
            setOptions()
          }
        }
      }
    },
    xAxis: {
      type: 'category',
      // boundaryGap: false,
      data: props.chartData.xData
    },
    yAxis: {
      type: 'value',
      name: props.chartData.yName,
      axisLabel: {
        formatter(value) {
          return formatNumberWithUnit({
            value,
            des: props.chartData.yName,
            carry: myThousand.value
          })
        }
      },
    },
    series: props.chartData.data?.map(o => {
      return {
        name: o.name,
        type: 'line',
        data: o.data
      }
    })
  }, true)
}

watch(() => props.chartData, () => {

  // 自动计算是否需要过万单位
  // if (!this.lockThousand) {
  myThousand.value = props.chartData.data?.some(o => {
    return o.data.some(num => num >= 10000)
  })
  // }
  chart && setOptions()
}, {
  deep: true
})

watch(() => props.showTool, () => {
  setOptions()
})

const initChart = () => {
  chart = echarts.init(chartRef.value)
  setOptions()
}


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

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

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

</script>