<script lang="ts" setup>
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import {
  ANIMATION,
  ChartItem,
  createTooltip,
  FONT_FAMILY,
  formatDateLabel,
  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: 40, left: 32 },
    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: 14,
        fontWeight: 500,
        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,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: THEME.text.regular,
        fontSize: 12,
        fontFamily: FONT_FAMILY
      },
      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.orange.bg,
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: THEME.color.orange.light },
            { offset: 0.5, color: THEME.color.orange.mid },
            { offset: 1, color: THEME.color.orange.line }
          ])
        },
        label: {
          show: true,
          position: 'top',
          distance: 10,
          color: THEME.color.orange.strong,
          fontSize: 16,
          fontWeight: 700,
          fontFamily: FONT_FAMILY
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 18,
            shadowColor: THEME.color.orange.shadow
          }
        }
      }
    ]
  }
}

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

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

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

function handleChartClick() {
  router.push({
    path: '/report-statistics/operational-costs',
    query: {
      createTime: getChartDateRange()
    }
  })
}

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.getOrderYwcb('rh')
    chartData.value = res.xAxis.map((item, index) => ({
      name: item,
      value: res.series[index]
    }))
    renderChart()
  } catch (error) {
    console.error('运维成本:', error)
    chartData.value = []
    renderChart()
  }
}

onMounted(() => {
  initChart()
  chart?.getZr().on('click', handleChartClick)
  chartClickBound = true
  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>
