<template>
  <div ref="barLineChart" class="echart_line"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import { throttle } from 'lodash-es'

// 类型定义
interface MarkLineItem {
  xAxis: number | string
  name: string
  color: string
}

interface TooltipDataItem {
  value: string
}

// 定义 Props 与类型
const props = defineProps({
  datax: {
    type: Array<string>,
    default: () => ['语文', '数学', '英语', '物理', '化学', '生物', '政治', '历史', '地理'],
  },
  datay: {
    type: Array<Array<string | number>>,
    default: () => [
      ['85', '78', '69', '67', '77', '88', '74', '66', '73'],
      ['82', '74', '63', '62', '73', '86', '71', '62', '71'],
    ],
  },
  fullScore: {
    type: Number,
    default: 100,
  },
  markLine: {
    type: Array<MarkLineItem>,
    default: () => [],
  },
  title: {
    type: Array<string>,
    default: () => [],
  },
  color: {
    type: Array<string>,
    default: () => ['#3BA272', '#FAC858'],
  },
  unit: {
    type: String,
    default: '',
  },
  tooltipTitle: {
    type: String,
    default: '',
  },
  tooltipData: {
    type: Array<TooltipDataItem>,
    default: () => [],
  },
  gridLeft: {
    type: Number,
    default: 30,
  },
  gridRight: {
    type: Number,
    default: 20,
  },
  gridTop: {
    type: Number,
    default: 20,
  },
  fontSize: {
    type: [Number, String],
    default: '',
  },
  fontColor: {
    type: String,
    default: '',
  },
})

// 图表实例
const barLineChart = ref<HTMLElement>()
let echartInstance: echarts.ECharts | null = null

// 监听数据变化
watch(
  () => props.datay,
  () => {
    loadEchart()
  },
  { deep: true }
)

// 窗口 resize 节流监听
const handleResize = throttle(() => {
  echartInstance?.resize()
}, 500)

// 初始化图表
const loadEchart = () => {
  if (!barLineChart.value) return

  // 销毁旧实例
  if (echartInstance) {
    echartInstance.dispose()
    echartInstance = null
  }

  if (props.datay.length === 0) return

  // 初始化新实例
  echartInstance = echarts.init(barLineChart.value, undefined, {
    devicePixelRatio: 2,
  })

  // 辅助线数据处理
  const markLineData = props.markLine.map((item) => ({
    xAxis: item.xAxis,
    label: {
      show: true,
      position: 'end',
      color: props.fontColor || '#666',
      fontSize: props.fontSize ? +props.fontSize : 14,
      formatter: () => item.name,
    },
    name: item.name,
    itemStyle: {
      color: item.color,
      type: 'dashed',
    },
  }))

  // Y轴最大值
  const flatData = props.datay.flat().map(Number)
  const maxValue = Math.max(...flatData)

  const option: echarts.EChartsOption = {
    tooltip: {
      show: true,
      axisPointer: { type: 'shadow' },
      trigger: 'item',
      triggerOn: 'mousemove | click',
      renderMode: 'html',
      confine: true,
      extraCssText:
        'border-radius: 4px;padding:5px 0px 5px 5px;white-space:normal;word-wrap:break-word;max-width: 400px;',
      enterable: true,
      formatter: (params: any) => {
        if (params.componentType === 'series') {
          let tooltip = `<div class='tooltip_content'>`
          const title = params.name
          tooltip += `<div class='tooltip_title'>${title}</div>`
          const obj = props.tooltipData[params.dataIndex]
          tooltip += `<div class='tooltip_student'>
                      <div class='tooltip_rect_icon' style='background:${params.color}'></div>
                      <div class='tooltip_student_name'>${obj?.value || ''}</div>
                    </div>`
          tooltip += `</div>`
          return tooltip
        }
        return ''
      },
    },
    legend: {
      show: false,
      left: 0,
      itemGap: 20,
      itemHeight: 10,
      itemWidth: 20,
      textStyle: {
        fontSize: props.fontSize ? +props.fontSize : 12,
        color: '#333',
      },
    },
    grid: {
      top: props.gridTop,
      left: props.gridLeft,
      right: props.gridRight,
      bottom: 0,
      containLabel: true,
    },
    yAxis: {
      type: 'value',
      splitArea: {
        show: true,
        areaStyle: {
          color: ['#fafafa', '#ffffff'],
        },
      },
      axisLabel: {
        formatter: '{value}',
        fontSize: props.fontSize ? +props.fontSize : 14,
        color: props.fontColor || '#666',
        fontWeight: 400,
      },
      max: getMaxValue(maxValue),
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      axisLabel: {
        rotate: props.datax.length > 12 ? 45 : 0,
        width: 100,
        overflow: 'break',
        interval: 0,
        hideOverlap: true,
        fontSize: props.fontSize ? +props.fontSize : 14,
        color: props.fontColor || '#666',
      },
    },
    series: [
      {
        type: 'bar',
        name: props.title[0],
        data: props.datay[0].map((value, index) => ({
          value: value,
          itemStyle: {
            color: getColor(props.datax[index], index),
          },
        })),
        barGap: 0,
        barCategoryGap: '30%',
        barMinWidth: 8,
        barMaxWidth: 50,
        label: {
          show: true,
          position: 'top',
          color: props.fontColor || '#666',
          fontSize: props.fontSize ? +props.fontSize : 12,
          formatter: (params: any) => {
            return params.value == 0 ? '' : `${params.value}人`
          },
        },
        markLine: {
          symbol: ['none', 'none'],
          label: { position: 'top', formatter: '{b}' },
          itemStyle: { color: props.fontColor || '#666' },
          data: markLineData,
        },
      },
      {
        type: 'line',
        name: props.title[1],
        data: props.datay[1],
        symbol: 'emptyCircle',
        showSymbol: true,
        symbolSize: 8,
        itemStyle: {
          color: props.color[1],
          borderColor: props.color[0],
          borderWidth: 2,
        },
        lineStyle: {
          color: props.color[1],
          type: 'solid',
          width: 4,
        },
        label: {
          show: false,
          position: 'top',
          color: props.fontColor || '#666',
          fontSize: props.fontSize ? +props.fontSize : 12,
          formatter: '{c}' + props.unit,
        },
      },
    ],
  }

  echartInstance.setOption(option)
}

// 获取最大值（保留全局方法逻辑）
const getMaxValue = (value: number) => {
  // 如果你有全局工具方法，直接替换即可
  // return window.$global.getMaxValue(value)
  return value
}

// 柱子颜色逻辑
const getColor = (value: string, index: number) => {
  const list = value.split('-')
  let num1 = list[0].replace(/[\[\]()]/g, '')
  const num = Number(num1)

  if (index !== 0) {
    num1 = String(num - 1)
  }

  const fullScore = props.fullScore
  if (num >= fullScore * 0.8) return '#3BA272'
  if (num >= fullScore * 0.6 && num < fullScore * 0.8) return '#FAC858'
  return '#EE6666'
}

// 生命周期
onMounted(() => {
  loadEchart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  echartInstance?.dispose()
})
</script>

<style lang="scss" scoped>
.echart_line {
  width: 100%;
  height: 380px;
}
</style>