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

<script>
import * as echarts from 'echarts'
import resize from '@/views/dashboard/mixins/resize'
import { convertToUnit, toFixed2 } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '500px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null,
      myThousand: false
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.myThousand = val.series?.some(o => {
          return o.data.some(num => num >= 10000)
        })
        // this.chart.dispose()
        // this.initChart()
        this.chart.clear(); // 清除图表（重新设置）
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ expectedData, actualData } = {}) {
      // 动态计算 max 值并向上取整
      // const maxSaleValue = Math.ceil(
      //   Math.max(
      //     ...this.chartData?.data?.saleData.flat()
      //   )
      // );
      // const maxGkrcValue = Math.ceil(
      //   Math.max(
      //     ...this.chartData?.data?.gkrcData.flat()
      //   )
      // );
      // const a = roundUpToNextHighestPowerOfTen(maxSaleValue);
      // const b = roundUpToNextHighestPowerOfTen(maxGkrcValue);
      this.chart.setOption({
        xAxis: {
          data: this.chartData.xAxis,
          // boundaryGap: false,
        },
        grid: {
          top: '6%',
          left: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}, // 保存为图片
            magicType: {
              type: ['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: () => {
                this.myThousand = !this.myThousand
                this.setOptions()
              }
            }
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10],
          formatter: (params) => {
            let tooltip = '';
            params.forEach((item) => {
              if (item.seriesName.split('-')[1] === '销售额') {
                tooltip += item.marker + item.seriesName + ': ' + (this.myThousand ? convertToUnit(item.value, true) : toFixed2(item.value) + '元') + '<br>';
              } else if (item.seriesName.split('-')[1] === '观看人次') {
                tooltip += item.marker + item.seriesName + ': ' + toFixed2(item.value) + (this.myThousand ? '万' : '') + '人<br>';
              }
            });
            return tooltip;
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            // nameTextStyle: {
            //   padding: [0, 80, 0, 0]
            // },
            axisLabel: {
              formatter: '{value} ' + (this.myThousand ? '万' : '') + '元'
            },
            // min: 0, // 设置最小值
            // max: a,
            // offset: 20
          },
          {
            type: 'value',
            name: '观看人次',
            // nameTextStyle: {
            //   padding: [0, 0, 0, 80]
            // },
            axisLabel: {
              formatter: '{value} ' + (this.myThousand ? '万' : '') + '人'
            },
            // min: 0, // 设置最小值
            // max: b,
            // offset: 20
          },
        ],
        // legend: {
        //   data: this.chartData.legend
        // },
        // legend: this.chartData.legend,
        series: [
          ...this.chartData.series?.map(o => {
            return {
              ...o,
              data: o.data.map(num => {
                return parseFloat((this.myThousand ? num / 10000 : num).toFixed(2))
              })
            }
          })
        ]
      })
    }
  }
}
</script>
