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

type RateRange = 'week' | 'sixMonth'

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

const chartRef = ref<HTMLDivElement>()
const activeRange = ref<RateRange>('week')
const loading = ref(false)
const rangeOptions: Array<{ label: string; value: RateRange }> = [
  { label: '近一周', value: 'week' },
  { label: '近六个月', value: 'sixMonth' }
]
let chart: echarts.ECharts | null = null
const router = useRouter()
let chartClickBound = false
let loadRequestId = 0

function formatRate(value: number) {
  return `${Number(value || 0).toFixed(2)}%`
}

function getChartOption(data: ChartData): echarts.EChartsOption {
  const names = data.xAxis || []
  const values = (data.series?.[0]?.data || []).map((value) => Number(value || 0) * 100)

  return {
    ...ANIMATION,
    grid: { ...THEME.grid, top: 40, right: 28, left: 32 },
    tooltip: createTooltip({
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      valueFormatter(value: number) {
        return formatRate(value)
      }
    }),
    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 activeRange.value === 'sixMonth' ? formatMonthLabel(value) : formatDateLabel(value)
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '设备利用率(%)',
      min: 0,
      max: 100,
      splitNumber: 4,
      nameTextStyle: {
        color: THEME.text.regular,
        fontSize: 13,
        fontFamily: FONT_FAMILY
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        color: THEME.text.regular,
        fontSize: 12,
        fontFamily: FONT_FAMILY,
        formatter(value: number) {
          return `${value}`
        }
      },
      splitLine: {
        lineStyle: {
          color: THEME.split,
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '设备利用率',
        type: 'line',
        smooth: true,
        data: values,
        symbol: 'circle',
        symbolSize: 8,
        showSymbol: true,
        lineStyle: {
          width: 2,
          color: THEME.color.green.line
        },
        itemStyle: {
          color: THEME.color.green.line
        },
        areaStyle: {
          color: THEME.color.green.bg
        },
        label: {
          show: true,
          position: 'top',
          distance: 10,
          color: THEME.color.green.strong,
          fontSize: 14,
          fontWeight: 700,
          fontFamily: FONT_FAMILY,
          formatter(params: any) {
            return formatRate(Number(params.value))
          }
        },
        emphasis: {
          focus: 'series',
          scale: true
        }
      }
    ]
  }
}

function initChart() {
  if (!chartRef.value) return
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value, undefined, {
    renderer: CHART_RENDERER
  })
  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

  const rangeUnit = activeRange.value === 'sixMonth' ? 'month' : 'day'
  return [
    startDate.startOf(rangeUnit).format('YYYY-MM-DD HH:mm:ss'),
    endDate.endOf(rangeUnit).format('YYYY-MM-DD HH:mm:ss')
  ]
}

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

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

function renderChart() {
  chart?.setOption(getChartOption(chartData.value), 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(range: RateRange = activeRange.value) {
  const requestId = ++loadRequestId
  loading.value = true
  try {
    const res =
      range === 'sixMonth'
        ? await IotStatApi.getRdSixMonthUtilization()
        : await IotStatApi.getRdSevenDayUtilization()
    if (requestId !== loadRequestId) return

    chartData.value = {
      xAxis: res.xAxis || [],
      series: (res.series || []).map((item) => ({
        name: item.name,
        data: item.data || []
      }))
    }
    renderChart()
  } catch (error) {
    if (requestId !== loadRequestId) return
    console.error('获取设备利用率失败:', error)
    chartData.value = {
      xAxis: [],
      series: []
    }
    renderChart()
  } finally {
    if (requestId === loadRequestId) {
      loading.value = false
    }
  }
}

watch(activeRange, (range) => {
  loadChart(range)
})

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

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

<template>
  <div class="panel flex flex-col">
    <div class="panel-title flex items-center justify-between">
      <div class="kb-panel-title-text flex items-center">
        <div class="icon-decorator">
          <span></span>
          <span></span>
        </div>
        设备利用率
      </div>
      <el-segmented
        v-model="activeRange"
        :options="rangeOptions"
        size="small"
        class="rate-range-switch" />
    </div>
    <div ref="chartRef" v-loading="loading" class="rate-chart flex-1 min-h-0"></div>
  </div>
</template>

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

.rate-range-switch {
  --el-segmented-item-selected-color: #03409b;
  --el-segmented-item-selected-bg-color: rgb(255 255 255 / 86%);
  --el-segmented-bg-color: rgb(31 91 184 / 10%);
  --el-segmented-item-hover-bg-color: rgb(255 255 255 / 56%);

  min-height: calc(26px * var(--kb-scale, 1));
  padding: calc(2px * var(--kb-scale, 1));
  border: 1px solid rgb(31 91 184 / 12%);
  transform: translateY(calc(-2px * var(--kb-scale, 1)));

  :deep(.el-segmented__item) {
    min-height: calc(22px * var(--kb-scale, 1));
    padding: 0 calc(7px * var(--kb-scale, 1));
    font-size: calc(13px * var(--kb-scale, 1));
    font-weight: 600;
    color: #29527f;
  }
}

.rate-chart {
  :deep(.el-loading-mask) {
    background-color: rgb(221 233 251 / 42%);
  }
}
</style>
