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

const chartData = ref<ChartData>({
  xAxis: [],
  series: []
})

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

function getChartOption(data: ChartData): echarts.EChartsOption {
  const xAxisData = data.xAxis || []
  const seriesData = data.series || []

  return {
    ...ANIMATION,
    grid: { ...THEME.grid, top: 40, right: 36, left: 32 },
    tooltip: createTooltip({
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter(params: any) {
        const list = Array.isArray(params) ? params : [params]
        const axisValue = list[0]?.axisValue || '--'

        const lines = list
          .map((item) => {
            const value = typeof item.value === 'number' ? item.value.toLocaleString() : item.value
            return `
            <div style="display:flex;align-items:center;margin-top:4px;">
              <span style="
                display:inline-block;
                width:10px;
                height:10px;
                border-radius:50%;
                background:${item.color};
                margin-right:6px;
              "></span>
              <span>${item.seriesName}：${value}</span>
            </div>
          `
          })
          .join('')

        return `
          <div>
            <div style="font-weight:600;margin-bottom:4px;">${axisValue}</div>
            ${lines}
          </div>
        `
      }
    }),
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: THEME.text.regular,
        fontSize: 14,
        fontFamily: FONT_FAMILY,
        formatter(value: string) {
          return formatDateLabel(value)
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '当日注气量(万方)',
      nameTextStyle: {
        color: THEME.text.regular,
        fontSize: 13,
        fontFamily: FONT_FAMILY
      },
      splitNumber: 4,
      axisLabel: {
        color: THEME.text.regular,
        fontSize: 12,
        fontFamily: FONT_FAMILY,
        formatter(value: number) {
          return value.toLocaleString()
        }
      },
      splitLine: {
        lineStyle: {
          color: THEME.split,
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          color: THEME.split
        }
      }
    },
    series: seriesData.map((item) => ({
      name: formatSeriesName(item.name),
      type: 'line',
      smooth: true,
      data: item.data || [],
      symbol: 'circle',
      symbolSize: 8,
      showSymbol: true,
      lineStyle: {
        width: 2,
        color: THEME.color.blue.line
      },
      itemStyle: {
        color: THEME.color.blue.line
      },
      areaStyle: {
        color: THEME.color.blue.bg
      },
      emphasis: {
        focus: 'series',
        scale: true
      }
    }))
  }
}

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 getChartDayRange() {
  const xAxis = chartData.value.xAxis || []
  const startDate = dayjs(xAxis[0])
  const endDate = dayjs(xAxis[xAxis.length - 1])
  if (!startDate.isValid() || !endDate.isValid()) return null

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

function handleChartClick() {
  const createTime = getChartDayRange()
  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.getRhZqlDaily('rh')
    chartData.value = {
      xAxis: res.xAxis || [],
      series: (res.series || []).map((item) => ({
        name: item.name,
        data: item.data || []
      }))
    }
    renderChart()
  } catch (error) {
    console.error('获取日注气量趋势失败:', error)
    chartData.value = {
      xAxis: [],
      series: []
    }
    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>
