<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { IotStatApi } from '@/api/pms/stat'
import dayjs from 'dayjs'
import quarterOfYear from 'dayjs/plugin/quarterOfYear'
import * as echarts from 'echarts'

dayjs.extend(quarterOfYear)

const chartRef = ref(null)
let myChart: echarts.ECharts | null = null
const currentTimeType = ref('month')

const timeOptions = [
  { label: '本月', value: 'month' },
  { label: '本季度', value: 'quarter' },
  { label: '本年', value: 'year' }
]

const getDateRange = (type: 'year' | 'quarter' | 'month') => {
  const now = dayjs()
  let start: dayjs.Dayjs, end: dayjs.Dayjs

  if (type === 'year') {
    start = now.startOf('year')
    end = now.endOf('year')
  } else if (type === 'quarter') {
    start = now.startOf('quarter')
    end = now.endOf('quarter')
  } else {
    start = now.startOf('month')
    end = now.endOf('month')
  }

  return {
    start: start.format('YYYY-MM-DD HH:mm:ss'),
    end: end.format('YYYY-MM-DD HH:mm:ss')
  }
}

const fetchData = async () => {
  if (myChart) {
    myChart.showLoading({
      text: '加载中 ...',
      color: '#409eff',
      textColor: '#B6C8DA',
      maskColor: 'rgba(0, 0, 0, 0.2)'
    })
  }

  const { start, end } = getDateRange(currentTimeType.value as 'year' | 'quarter' | 'month')

  const params = {
    'createTime[0]': start,
    'createTime[1]': end,
    timeType: currentTimeType.value
  }

  try {
    let list: any[] = []

    const res = await IotStatApi.getUtilization(params)
    if (res && Array.isArray(res)) list = res

    renderChart(list)
  } catch (error) {
    console.error('Workload API Error:', error)
  } finally {
    myChart?.hideLoading()
  }
}

const renderChart = (data: any[]) => {
  if (!myChart) return

  const xAxisData = data.map((item) => item.projectDeptName.replace('项目部', ''))

  const seriesData = data.map((item) => {
    const val = item.utilizationRate
    if (val === null || val === undefined || isNaN(val)) return 0
    return parseFloat((val * 100).toFixed(2))
  })

  const option: echarts.EChartsOption = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.7)',
      borderColor: '#409eff',
      textStyle: { color: '#fff' },
      axisPointer: {
        type: 'shadow',
        shadowStyle: { color: 'rgba(255, 255, 255, 0.1)' }
      },
      // 自定义 Tooltip 内容，加上 %
      formatter: (params: any) => {
        const item = params[0]
        return `${item.name}<br/>
                <span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:${item.color.colorStops ? item.color.colorStops[0].color : item.color};"></span>
                ${item.seriesName}: <span style="font-weight:bold; color: #fff">${item.value}%</span>`
      }
    },
    grid: { top: '15%', left: '3%', right: '3%', bottom: '5%', containLabel: true },
    xAxis: {
      data: xAxisData,
      type: 'category',
      boundaryGap: true,
      axisLabel: { color: '#B6C8DA', interval: 0, fontSize: 12 },
      axisLine: { lineStyle: { color: '#B6C8DA' } },
      axisTick: { show: false }
    },
    yAxis: {
      type: 'value',
      name: '利用率 (%)',
      axisLabel: { color: '#B6C8DA', formatter: '{value}' },
      nameTextStyle: { color: '#B6C8DA', padding: [0, 0, 0, 10] },
      axisLine: { lineStyle: { color: '#B6C8DA' } },
      splitLine: { lineStyle: { color: '#457794', type: 'dashed' } }
    },
    series: {
      name: '设备利用率',
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.1)',
        borderRadius: [4, 4, 0, 0]
      },
      itemStyle: {
        borderRadius: [4, 4, 0, 0],
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#23D0F6' },
          { offset: 1, color: '#1A7BF8' }
        ])
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#4FFBDF' },
            { offset: 1, color: '#23D0F6' }
          ])
        }
      },
      data: seriesData
    }
  }

  myChart.setOption(option)
}

const handleTimeChange = () => {
  fetchData()
}

const resizeChart = () => myChart?.resize()

onMounted(() => {
  nextTick(() => {
    myChart = echarts.init(chartRef.value, undefined, { renderer: 'canvas' })
    fetchData()
    window.addEventListener('resize', resizeChart)
  })
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  myChart?.dispose()
})
</script>

<template>
  <div class="card size-full rounded-lg p-4 flex flex-col">
    <div class="flex justify-between items-center mb-4">
      <div class="flex items-center gap-2 items-center">
        <div class="w-1 h-4 bg-[#00E5FF] rounded-full shadow-[0_0_8px_#00E5FF]"></div>
        <div class="text-[#e0e0e0] text-lg font-bold">设备利用率</div>
      </div>
      <el-segmented
        size="default"
        v-model="currentTimeType"
        :options="timeOptions"
        @change="handleTimeChange"
        class="dark-segmented w-50!"
        block
      />
    </div>
    <div ref="chartRef" class="flex-1 w-full min-h-0"></div>
  </div>
</template>

<style scoped>
.card {
  background-color: rgb(0 0 0 / 30%);
  box-shadow: 0 2px 12px rgb(0 0 0 / 50%);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgb(0 0 0 / 8%);
  }
}

.dark-segmented {
  --el-segmented-item-selected-color: #e5eaf3;
  --el-border-radius-base: 16px;
  --el-segmented-color: #cfd3dc;
  --el-segmented-bg-color: #262727;
  --el-segmented-item-selected-bg-color: #409eff;
  --el-segmented-item-selected-disabled-bg-color: rgb(42 89 138);
  --el-segmented-item-hover-color: #e5eaf3;
  --el-segmented-item-hover-bg-color: #39393a;
  --el-segmented-item-active-bg-color: #424243;
  --el-segmented-item-disabled-color: #8d9095;
}

:deep(.el-segmented__item) {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
