<template>
  <div class="card">
    <div class="panel-title panel-title-between">
      <div class="panel-title-left">
        <span class="title-dot"></span>
        <span>能耗监测</span>
      </div>
      <div class="tabs">
        <el-select
v-model="selectedEnergyTypeId" placeholder="请选择" style="width: 120px" size="small"
          @change="getChartData">
          <el-option v-for="item in energyTypes" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </div>
    </div>
    <div class="panel-body">
      <div ref="chartRef" class="chart"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import { colors, style } from '../utils'
import { EnergyTypeApi, EnergyTypeVO } from '@/api/mes/energytype'
import { EnergyDeviceApi } from '@/api/mes/energydevice'

const route = useRoute()
const orgId = route.query.orgId

const energyTypes = ref<EnergyTypeVO[]>([])
const selectedEnergyTypeId = ref<number | undefined>(undefined)
const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const getEnergyTypes = async () => {
  try {
    const res = await EnergyTypeApi.getEnergyTypeList({ orgId })
    const list = (res as any).data || (Array.isArray(res) ? res : [])
    energyTypes.value = list
    if (list.length > 0) {
      selectedEnergyTypeId.value = list[0].id
      getChartData()
    }
  } catch (e) {
    console.error('Failed to fetch energy types:', e)
  }
}

const getChartData = async () => {
  if (!selectedEnergyTypeId.value) return
  try {
    const res = await EnergyDeviceApi.getLastEnergyStatistics({
      deviceTypeId: selectedEnergyTypeId.value,
      orgId: orgId
    })
    render(res)
  } catch (e) {
    console.error('Failed to fetch chart data:', e)
  }
}

const render = (data: any = []) => {
  if (!chart) return

  // 尝试解析数据，假设数据包含时间(time/createTime)和值(value/consumption)
  // 如果数据格式未知，这里做一个简单的映射尝试
  // 默认 fallback
  let x: string[] = []
  let y: number[] = []

  const list = (data as any).data || (Array.isArray(data) ? data : [])

  if (list && list.length > 0) {
    x = list.map((item: any) => {
      const h = item.hour || ''
      // 如果包含日期和时间，只显示时间部分
      if (typeof h === 'string' && h.includes(' ')) {
        return h.split(' ')[1]
      }
      return h
    })
    y = list.map((item: any) => item.value || item.consumption || item.energy || 0)
  } else {
    // 没数据时清空或显示空
    x = []
    y = []
  }

  chart.setOption({
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis' },
    grid: { top: '18%', left: '6%', right: '4%', bottom: '12%', containLabel: true },
    xAxis: { type: 'category', data: x, axisLine: style.axisLine, axisLabel: { ...style.axisLabel, fontSize: 10, rotate: 40 } },
    yAxis: { type: 'value', axisLine: { show: false }, axisLabel: { ...style.axisLabel, fontSize: 10 }, splitLine: style.splitLine },
    series: [
      {
        type: 'bar',
        barWidth: 12,
        itemStyle: {
          borderRadius: [6, 6, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: colors.blue },
            { offset: 1, color: 'rgba(30,144,255,0.10)' }
          ])
        },
        data: y
      }
    ]
  })
}

const resize = () => {
  chart?.resize()
}

onMounted(() => {
  if (!chartRef.value) return
  chart = echarts.init(chartRef.value, 'dark', { renderer: 'canvas' })
  // 先初始化一个空图表
  render([])
  // 获取下拉选项并加载数据
  getEnergyTypes()
  window.addEventListener('resize', resize)
})

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

<style scoped>
:deep(.el-select .el-input__wrapper) {
  background-color: rgb(2 6 23 / 30%);
  box-shadow: 0 0 0 1px rgb(56 189 248 / 40%) inset;
}

:deep(.el-select .el-input__inner) {
  color: #e5f0ff;
}

:deep(.el-select .el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px rgb(56 189 248 / 90%) inset !important;
}

.card {
  position: relative;
  display: flex;
  height: 100%;
  min-height: 0;
  overflow: hidden;
  background: linear-gradient(135deg, rgb(15 23 42 / 96%), rgb(15 23 42 / 88%));
  border: 1px solid rgb(30 64 175 / 85%);
  border-radius: 8px;
  box-shadow:
    0 18px 45px rgb(15 23 42 / 95%),
    0 0 0 1px rgb(15 23 42 / 100%),
    inset 0 0 0 1px rgb(56 189 248 / 5%);
  flex-direction: column;
}

.card::before,
.card::after {
  position: absolute;
  width: 12px;
  height: 12px;
  pointer-events: none;
  border: 1px solid rgb(56 189 248 / 75%);
  border-radius: 2px;
  content: "";
  opacity: 0.6;
}

.card::before {
  top: -1px;
  left: -1px;
  border-right: none;
  border-bottom: none;
}

.card::after {
  right: -1px;
  bottom: -1px;
  border-top: none;
  border-left: none;
}

.panel-title {
  display: flex;
  padding: 10px 12px;
  font-size: 16px;
  font-weight: 900;
  color: #e5f0ff;
  border-bottom: 1px solid rgb(41 54 95 / 90%);
  align-items: center;
  gap: 10px;
}

.panel-title-between {
  justify-content: space-between;
}

.panel-title-left {
  display: inline-flex;
  align-items: center;
  gap: 10px;
}

.title-dot {
  width: 10px;
  height: 10px;
  border: 1px solid rgb(56 189 248 / 95%);
  border-radius: 50%;
  box-shadow: 0 0 12px rgb(56 189 248 / 45%);
}

.tabs {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  font-size: 11px;
  font-weight: 600;
  color: rgb(148 163 184 / 95%);
}

.tab {
  padding: 2px 8px;
  cursor: pointer;
  background: rgb(2 6 23 / 20%);
  border: 1px solid rgb(148 163 184 / 40%);
  border-radius: 999px;
  user-select: none;
}

.tab.active {
  color: #e0f2fe;
  border-color: rgb(56 189 248 / 85%);
  box-shadow: 0 0 14px rgb(56 189 248 / 35%);
}

.panel-body {
  flex: 1;
  min-height: 0;
  padding: 10px 12px;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 160px;
}

:deep(.el-select__wrapper) {
  color: #94a3b8;
  background-color: transparent;
  border: 1px solid rgb(56 189 248 / 55%);
  box-shadow: 0 0 18px rgb(56 189 248 / 35%);
}

:deep(.el-select__placeholder) {
  color: #94a3b8;
}
</style>
