<script lang="ts" setup>
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import {
  ANIMATION,
  ChartItem,
  createTooltip,
  FONT_FAMILY,
  formatGasAxisValue,
  formatGasLabelValue,
  formatMonthLabel,
  THEME
} from '@/utils/kb'
import { IotStatApi } from '@/api/pms/stat'

const chartData = ref<ChartItem[]>([])

const router = useRouter()
const chartRef = ref<HTMLDivElement>()
let chart: echarts.ECharts | null = null
let chartClickBound = false

function getChartOption(data: ChartItem[]): echarts.EChartsOption {
  const names = data.map((item) => item.name)
  const values = data.map((item) => item.value)

  return {
    ...ANIMATION,
    grid: { ...THEME.grid, top: 36, right: 36 },
    tooltip: createTooltip({
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: THEME.split
        }
      }
    }),
    xAxis: {
      type: 'category',
      data: names,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: THEME.text.regular,
        fontSize: 12,
        fontFamily: FONT_FAMILY,
        formatter(value: string) {
          return formatMonthLabel(value)
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '累计注气量(万方)',
      nameTextStyle: {
        color: THEME.text.regular,
        fontSize: 13,
        fontFamily: FONT_FAMILY
      },
      splitNumber: 4,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: THEME.text.regular,
        fontSize: 12,
        fontFamily: FONT_FAMILY,
        formatter(value: number) {
          return formatGasAxisValue(value)
        }
      },
      splitLine: {
        lineStyle: {
          color: THEME.split,
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '累计注气量',
        type: 'bar',
        data: values,
        barWidth: 22,
        showBackground: true,
        backgroundStyle: {
          color: THEME.split,
          borderRadius: 999
        },
        itemStyle: {
          borderRadius: [12, 12, 0, 0],
          shadowBlur: 12,
          shadowColor: THEME.color.green.bg,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: THEME.color.green.light },
            { offset: 0.5, color: THEME.color.green.mid },
            { offset: 1, color: THEME.color.green.line }
          ])
        },
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            position: 'top',
            distance: 10,
            color: THEME.color.green.strong,
            fontSize: 16,
            fontWeight: 700,
            fontFamily: FONT_FAMILY,
            formatter(params: any) {
              const value = Number(params.value || 0)
              return formatGasLabelValue(value)
            }
          },
          itemStyle: {
            shadowBlur: 18,
            shadowColor: THEME.color.green.shadow
          }
        }
      }
    ]
  }
}

function initChart() {
  if (!chartRef.value) return
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value, undefined, {
    renderer: 'svg'
  })
  chart.getZr().on('click', handleChartClick)
  chartClickBound = true
  renderChart()
}

function getChartMonthRange() {
  const startDate = dayjs(chartData.value[0]?.name)
  const endDate = dayjs(chartData.value[chartData.value.length - 1]?.name)
  if (!startDate.isValid() || !endDate.isValid()) return null

  return [
    startDate.startOf('month').format('YYYY-MM-DD HH:mm:ss'),
    endDate.endOf('month').format('YYYY-MM-DD HH:mm:ss')
  ]
}

function handleChartClick() {
  const createTime = getChartMonthRange()
  if (!createTime) return

  router.push({
    name: 'IotRhDailyReportSummary',
    query: {
      activeTab: '日报统计',
      view: 'kanban',
      createTime
    }
  })
}

function renderChart() {
  if (!chart) return

  const data = chartData.value || []

  chart.setOption(getChartOption(data), true)
}

function resizeChart() {
  chart?.resize()
}

function destroyChart() {
  if (chart) {
    if (chartClickBound) {
      chart.getZr().off('click', handleChartClick)
      chartClickBound = false
    }
    chart.dispose()
    chart = null
  }
}

async function loadChart() {
  try {
    const res = await IotStatApi.getRhZqlGases('rh')
    const seriesData = res.series?.[0]?.data || []

    chartData.value = (res.xAxis || []).map((item, index) => ({
      name: item,
      value: Number(seriesData[index] || 0)
    }))
    renderChart()
  } catch (error) {
    console.error('获取累计注气量失败:', error)
    chartData.value = []
    renderChart()
  }
}

onMounted(() => {
  initChart()
  loadChart()
  window.addEventListener('resize', resizeChart)
  window.addEventListener('rhkb:resize', resizeChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  window.removeEventListener('rhkb:resize', resizeChart)
  destroyChart()
})
</script>

<template>
  <div class="panel flex flex-col">
    <div class="panel-title">
      <div class="icon-decorator">
        <span></span>
        <span></span>
      </div>
      累计注气量统计
    </div>
    <div ref="chartRef" class="flex-1 min-h-0"></div>
  </div>
</template>

<style lang="scss" scoped>
@import url('@/styles/kb.scss');
</style>
