<script lang="ts" setup>
import * as echarts from 'echarts'
import { ANIMATION, CHART_RENDERER, createTooltip, FONT_FAMILY, THEME } from '@/utils/kb'
import { IotDeviceApi } from '@/api/pms/device'

interface UseStatusItem {
  name: string
  value: number
}

interface DeviceStatusResponseItem {
  name?: string
  category?: string
  value?: number | string
}

const RD_DEPT_ID = 163
const chartRef = ref<HTMLDivElement>()
const loading = ref(false)
const statusData = ref<UseStatusItem[]>([])
let chart: echarts.ECharts | null = null

const chartData = computed(() => statusData.value.filter((item) => item.value > 0))

function getChartLayout() {
  const { clientWidth = 0, clientHeight = 0 } = chartRef.value ?? {}
  const compact = clientHeight > 0 && (clientHeight < 210 || clientWidth < 520)

  return {
    pieRadius: compact ? ['38%', '58%'] : ['44%', '64%'],
    pieCenterX: compact ? '30%' : '31%',
    pieCenterY: compact ? '50%' : '50%',
    legendRight: compact ? 8 : 18,
    legendTop: compact ? 34 : 40,
    legendItemSize: compact ? 9 : 13,
    legendGap: compact ? 8 : 12,
    legendFontSize: compact ? 10 : 14
  }
}

function getChartOption(): echarts.EChartsOption {
  const layout = getChartLayout()

  return {
    ...ANIMATION,
    color: [
      THEME.color.blue.line,
      THEME.color.orange.line,
      THEME.color.red.line,
      THEME.color.green.line,
      THEME.color.blue.mid,
      '#2a97c7',
      '#68c7dd',
      '#8aa4ff',
      '#78d08f',
      '#f7c66b'
    ],
    tooltip: createTooltip({
      trigger: 'item',
      formatter(params: any) {
        return `${params.marker}${params.name}<br/>数量：${params.value} 台<br/>占比：${params.percent}%`
      }
    }),
    legend: {
      type: 'plain',
      orient: 'vertical',
      top: layout.legendTop,
      right: layout.legendRight,
      width: '45%',
      itemWidth: layout.legendItemSize,
      itemHeight: layout.legendItemSize,
      itemGap: layout.legendGap,
      textStyle: {
        color: THEME.text.regular,
        fontSize: layout.legendFontSize,
        fontWeight: 600,
        fontFamily: FONT_FAMILY
      },
      formatter(name: string) {
        const item = chartData.value.find((status) => status.name === name)
        return item ? `${name}  ${item.value}台` : name
      }
    },
    series: [
      {
        name: '设备使用状态',
        type: 'pie',
        radius: layout.pieRadius,
        center: [layout.pieCenterX, layout.pieCenterY],
        minAngle: 5,
        label: { show: false },
        data: chartData.value
      }
    ]
  }
}

function initChart() {
  if (!chartRef.value) return

  chart?.dispose()
  chart = echarts.init(chartRef.value, undefined, {
    renderer: CHART_RENDERER
  })
  renderChart()
}

function renderChart() {
  chart?.setOption(getChartOption(), true)
}

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

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

async function getDeviceStatus() {
  loading.value = true

  try {
    const res = await IotDeviceApi.getIotDeviceStatus({ deptId: RD_DEPT_ID })
    statusData.value = Array.isArray(res)
      ? res.map((item: DeviceStatusResponseItem) => ({
          name: item.name || item.category || '未知',
          value: Number(item.value ?? 0)
        }))
      : []
    renderChart()
  } catch (error) {
    console.error('获取瑞都设备使用状态失败:', error)
    statusData.value = []
    renderChart()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  initChart()
  getDeviceStatus()
  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 use-status-panel flex flex-col">
    <div class="panel-title">
      <div class="icon-decorator">
        <span></span>
        <span></span>
      </div>
      设备使用状态
    </div>
    <div
      v-loading="loading"
      element-loading-text="加载中..."
      element-loading-background="rgb(222 236 252 / 72%)"
      class="use-status-body">
      <div ref="chartRef" class="use-status-chart"></div>
    </div>
  </div>
</template>

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

.use-status-panel {
  overflow: hidden;
}

.use-status-body {
  display: flex;
  min-height: 0;
  flex: 1;
  padding: calc(10px * var(--kb-scale, 1)) calc(16px * var(--kb-scale, 1))
    calc(14px * var(--kb-scale, 1));
}

.use-status-chart {
  min-height: 0;
  flex: 1;
}
</style>
