<template>
  <div class="water-consumption-container">
    <el-card class="chart-card" shadow="never">
      <template #header>
        <div class="chart-header">
          <div class="chart-title">用水量统计</div>
          <el-radio-group v-model="dateType" size="small" @change="fetchChartData">
            <el-radio :value="'week'">周</el-radio>
            <el-radio :value="'month'">月</el-radio>
            <el-radio :value="'year'">年</el-radio>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-content">
        <div ref="chartRef" class="water-chart"></div>
        <div v-loading="loading" v-if="loading" class="loading-mask"></div>
      </div>
    </el-card>

    <el-card class="history-table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="table-title">历史记录</span>
        </div>
      </template>
      <el-table 
        v-loading="tableLoading" 
        :data="tableData" 
        border 
        stripe 
        style="width: 100%"
        :empty-text="'暂无数据'"
      >
        <el-table-column prop="updateTime" label="时间" min-width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceName" label="设备名称" min-width="120" />
        <el-table-column prop="location" label="地址" min-width="120" />
        <el-table-column label="用水量(吨)" min-width="120">
          <template #default="{ row }">
            {{ calculateWaterUsage(row) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import dayjs from 'dayjs'
import type { EChartsOption } from 'echarts'
import type { WaterConsumptionChartData, WaterConsumptionHistoryData } from '@/api/energy/waterconsumption'
import { getWaterConsumptionChart, getWaterConsumptionHistory } from '@/api/energy/waterconsumption'

const chartRef = ref<HTMLDivElement | null>(null)
const chartInstance = ref<echarts.ECharts | null>(null)
const dateType = ref<'week' | 'month' | 'year'>('week')
const chartData = ref<WaterConsumptionChartData[]>([])
const tableData = ref<WaterConsumptionHistoryData[]>([])
const loading = ref(false)
const tableLoading = ref(false)

const calculateWaterUsage = (row: WaterConsumptionHistoryData) => {
  if (row.currentValue === undefined || row.lastTonnage === undefined) return '-'
  const usage = row.currentValue - row.lastTonnage
  return usage.toFixed(3)
}

const fetchChartData = async () => {
  try {
    loading.value = true
    const res = await getWaterConsumptionChart({ type: dateType.value })
    console.log('Chart data received:', res)
    if (res && Array.isArray(res)) {
      chartData.value = res
      await nextTick()
      await initChart()
      renderChart()
    } else {
      ElMessage.error('获取用水量数据格式错误')
    }
  } catch (e) {
    console.error('Chart API Error:', e)
    ElMessage.error('获取用水量数据失败')
  } finally {
    loading.value = false
  }
}

const fetchTableData = async () => {
  try {
    tableLoading.value = true
    const res = await getWaterConsumptionHistory()
    console.log('Table data received:', res)
    if (res && Array.isArray(res)) {
      tableData.value = res
    } else {
      ElMessage.error('获取历史记录数据格式错误')
    }
  } catch (e) {
    console.error('Table API Error:', e)
    ElMessage.error('获取历史记录失败')
  } finally {
    tableLoading.value = false
  }
}

const initChart = async () => {
  console.log('Initializing chart...')
  if (!chartRef.value) {
    console.warn('Chart container not found')
    return
  }
  
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
  
  await nextTick()
  const { clientWidth, clientHeight } = chartRef.value
  console.log('Chart container size:', { width: clientWidth, height: clientHeight })
  
  if (clientWidth === 0 || clientHeight === 0) {
    console.warn('Chart container has zero size')
    return
  }
  
  chartInstance.value = echarts.init(chartRef.value)
  window.addEventListener('resize', handleResize)
  console.log('Chart initialized')
}

const handleResize = () => {
  if (!chartInstance.value || !chartRef.value) return
  const { clientWidth, clientHeight } = chartRef.value
  console.log('Resizing chart to:', { width: clientWidth, height: clientHeight })
  chartInstance.value.resize()
}

const renderChart = () => {
  console.log('Rendering chart with data:', chartData.value)
  if (!chartInstance.value) {
    console.warn('Chart instance not found')
    return
  }

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>{a}: {c} 吨'
    },
    grid: {
      top: '15%',
      left: '12%',
      right: '8%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.length > 0 ? chartData.value.map(item => item.date) : [],
      name: '日期',
      nameLocation: 'middle',
      nameGap: 50,
      axisLabel: {
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '用水量(吨)',
      nameLocation: 'middle',
      nameGap: 70,
      axisLabel: {
        formatter: (value: number) => value.toFixed(3)
      }
    },
    series: [{
      name: '用水量',
      type: 'line',
      data: chartData.value.length > 0 ? chartData.value.map(item => item.value) : [],
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      areaStyle: {
        opacity: 0.3
      },
      label: {
        show: true,
        position: 'top',
        formatter: (params: any) => params.value.toFixed(3)
      }
    }]
  }

  console.log('Setting chart option:', option)
  chartInstance.value.setOption(option)
}

const formatDate = (val: string) => {
  if (!val) return '-'
  return dayjs(val).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(async () => {
  console.log('Component mounted')
  await fetchChartData()
  await fetchTableData()
})

onUnmounted(() => {
  console.log('Component unmounting')
  window.removeEventListener('resize', handleResize)
  if (chartInstance.value) {
    chartInstance.value.dispose()
    chartInstance.value = null
  }
})

watch(dateType, fetchChartData)
</script>

<style scoped>
.water-consumption-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.chart-card {
  margin-bottom: 24px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2d3d;
}

.chart-content {
  position: relative;
  min-height: 400px;
}

.water-chart {
  height: 400px;
  width: 100%;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  z-index: 1;
}

.history-table-card {
  background: #fff;
  border-radius: 4px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #1f2d3d;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>
