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

defineProps<{
  embedded?: boolean
}>()

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

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

function getBarStyle(color: (typeof THEME.color)[keyof typeof THEME.color]) {
  return {
    borderRadius: [12, 12, 0, 0],
    shadowBlur: 12,
    shadowColor: color.bg,
    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: color.light },
      { offset: 0.55, color: color.mid },
      { offset: 1, color: color.line }
    ])
  }
}

function formatValue(value: number | string) {
  return Number(value || 0).toLocaleString('en-US')
}

function isAnnualSeries(name: string) {
  return name.includes('annual') || formatSeriesName(name).includes('年累')
}

function getChartOption(data: ChartData): echarts.EChartsOption {
  const xAxisData = data.xAxis || []
  const seriesData = data.series || []
  const colorList = [THEME.color.orange, THEME.color.blue, THEME.color.green]

  return {
    ...ANIMATION,
    grid: {
      ...THEME.grid,
      top: 50,
      bottom: 10
    },
    tooltip: createTooltip({
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        shadowStyle: {
          color: THEME.split
        }
      }
    }),
    legend: createLegend(
      {
        top: 4,
        itemWidth: 12,
        itemHeight: 12
      },
      seriesData.map((item) => formatSeriesName(item.name))
    ),
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        interval: 0,
        color: THEME.text.regular,
        fontSize: 14,
        fontFamily: FONT_FAMILY,
        width: 78,
        overflow: 'break'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '日/月进尺(m)',
        nameTextStyle: {
          color: THEME.text.regular,
          fontSize: 13,
          fontFamily: FONT_FAMILY,
          align: 'left'
        },
        splitNumber: 4,
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: THEME.text.regular,
          fontSize: 12,
          fontFamily: FONT_FAMILY,
          formatter(value: number) {
            return formatValue(value)
          }
        },
        splitLine: {
          lineStyle: {
            color: THEME.split,
            type: 'dashed'
          }
        },
        position: 'left'
      },
      {
        type: 'value',
        name: '年累进尺(m)',
        splitNumber: 4,
        nameTextStyle: {
          color: THEME.text.regular,
          fontSize: 13,
          fontFamily: FONT_FAMILY
        },
        position: 'right',
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: THEME.text.regular,
          fontSize: 12,
          fontFamily: FONT_FAMILY,
          formatter(value: number) {
            return formatValue(value)
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: seriesData.map((item, index) => {
      const color = colorList[index % colorList.length]
      const annual = isAnnualSeries(item.name)

      return {
        name: formatSeriesName(item.name),
        type: 'bar',
        yAxisIndex: annual ? 1 : 0,
        data: item.data || [],
        barWidth: 22,
        showBackground: true,
        backgroundStyle: {
          color: THEME.split,
          borderRadius: [12, 12, 0, 0]
        },
        itemStyle: getBarStyle(color),
        label: {
          show: true,
          position: 'top',
          distance: 10,
          color: color.strong,
          fontSize: 14,
          fontWeight: 700,
          fontFamily: FONT_FAMILY,
          formatter(params: any) {
            return Number(params.value) ? formatValue(params.value) : ''
          }
        },
        emphasis: {
          focus: 'series',
          itemStyle: {
            ...getBarStyle(color),
            shadowColor: color.shadow,
            shadowBlur: 18
          }
        }
      }
    })
  }
}

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

function renderChart() {
  if (!chart) return
  chart.setOption(getChartOption(chartData.value), true)
}

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

function destroyChart() {
  if (chart) {
    chart.dispose()
    chart = null
  }
}

async function loadChart() {
  try {
    const res = await IotStatApi.getRepairRigWork('rig')
    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('rykb:resize', resizeChart)
})

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

<template>
  <div :class="embedded ? 'h-full flex flex-col' : 'panel flex flex-col'">
    <div v-if="!embedded" 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>
