<template>
  <div class="page-container">
  <el-row :gutter="16" class="summary">
    <!-- 原有的统计卡片部分保持不变 -->
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="device.total || 0"
        icon="fa-solid:project-diagram"
        icon-bg-color="text-blue-500"
        icon-color="bg-blue-100"
        :title="t('stat.deviceCount')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="maintain.total || 0"
        icon="fa-solid:list"
        icon-bg-color="text-pink-500"
        icon-color="bg-blue-100"
        :title="t('stat.repairOrder')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="fill.unfilledCount || 0"
        icon="fa-solid:times-circle"
        icon-bg-color="text-purple-500"
        icon-color="bg-purple-100"
        :title="t('stat.operationNotFilled')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="fill.filledCount || 0"
        icon="fa-solid:award"
        icon-bg-color="text-purple-500"
        icon-color="bg-purple-100"
        :title="t('stat.operationFilled')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="by.todo || 0"
        icon="fa-solid:times-circle"
        icon-bg-color="text-green-500"
        icon-color="bg-green-100"
        :title="t('stat.notMaintained')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="by.finished || 0"
        icon="fa-solid:award"
        icon-bg-color="text-green-500"
        icon-color="bg-green-100"
        :title="t('stat.maintained')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="inspectt.todo || 0"
        icon="fa-solid:times-circle"
        icon-bg-color="text-yellow-500"
        icon-color="bg-yellow-100"
        :title="t('stat.notInspected')"
      />
    </el-col>
    <el-col  :sm="3" :xs="12">
      <SummaryCard
        :value="inspectt.finished || 0"
        icon="fa-solid:award"
        icon-bg-color="text-yellow-500"
        icon-color="bg-yellow-100"
        :title="t('stat.inspected')"
      />
    </el-col>
    <!-- 其他统计卡片... -->
  </el-row>
  <!-- 第二行：图表行 -->
  <el-row :gutter="16" class="mb-4 mt-3">
    <el-col :span="6">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.deviceStatus')}}</span>
          </div>
        </template>
        <div ref="statusChartRef" class="h-[290px]"></div>
      </el-card>
    </el-col>
    <el-col :span="10">
      <el-card class="chart-card" shadow="never" >
        <template #header>
          <div class="flex items-center">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.deviceClassifyTop5')}}</span>
          </div>
        </template>
        <div ref="topContainer" class="h-[290px]"></div>
      </el-card>
    </el-col>
    <el-col :span="8">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.operationCost')}}</span>
          </div>
        </template>
        <div ref="chartContainer" class="h-[290px]"></div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 第三行：消息统计行 -->
  <el-row :gutter="16" class="mb-1">
    <el-col :span="12">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div style="display: flex; flex-direction: row; justify-content: space-between">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.deviceRate')}}</span>
            <div>
            <el-date-picker
              v-model="rateQueryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
              @change="handleDateChange"
            />
            </div>
          </div>
        </template>
<!--        <div ref="materialChartRef" class="h-[320px]"></div>-->
        <div class="table-container">
          <el-table
            :data="materialTableData"
            border
            @row-click="handleRowClick"
            style="width: 100%"
            :header-cell-style="{
                'background-color': '#2196df',
                'color': 'white',
                'border-color': '#457794'
              }"
            :cell-style="{
                'border-color': '#457794',
                'background-color': '#284D72',
                'color':'#F1D209'
              }"
          >
            <el-table-column
              prop="projectDeptName"
              label="项目部"
              align="center"
            />
            <el-table-column
              prop="teamCount"
              label="队伍数量"
              align="center"
            />
            <el-table-column
              prop="cumulativeDays"
              label="累计天数"
              align="center"
            />
            <el-table-column
              prop="constructionDays"
              label="施工天数"
              align="center"
            />
            <el-table-column
              prop="gasInjection"
              :formatter="gasInjectionFormatter"
              label="注气量(万方)"
              align="center"
            />
            <el-table-column
              prop="utilizationRate"
              label="设备利用率"
              align="center"
              :formatter="formatRate"
            />
          </el-table>
        </div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.orderCount')}}</span>
          </div>
        </template>
        <div ref="qxRef" class="h-[320px]"></div>
      </el-card>
    </el-col>
  </el-row>
  <el-row :gutter="16" class="mb-1 mt-4">
    <el-col :span="12">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.dailyGasWater')}}</span>
          </div>
        </template>
        <div ref="todayZqlRef" class="h-[300px]"></div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card class="chart-card" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium " style="color: #b6c8da">{{t('stat.gasWater')}}</span>
          </div>
        </template>
        <div ref="zqlChartRef" class="h-[300px]"></div>
      </el-card>
    </el-col>
  </el-row>
  </div>


  <el-dialog
    v-model="teamDialogVisible"
    :title="t('stat.teamDetail')"
    width="80vh"
    :before-close="handleDialogClose"
    class="custom-scroll-dialog"
  >
    <div class="dialog-scroll-content">
    <el-table
      :data="teamTableData"
      border
      style="width: 100%;"
      :header-cell-style="{
        'background-color': 'rgba(0, 0, 0, 0.2)',
        'color': 'black',
        'border-color': '#457794'
      }"
      :cell-style="{
        'border-color': '#457794',
        'background-color': 'transparent'
      }"
    >
      <el-table-column
        prop="teamName"
        label="队伍名称"
        align="center"
      />
      <el-table-column
        prop="cumulativeDays"
        label="累计天数"
        align="center"
      />
      <el-table-column
        prop="constructionDays"
        label="施工天数"
        align="center"
      />
      <el-table-column
        prop="utilizationRate"
        label="设备利用率"
        align="center"
        :formatter="formatRate"
      />
    </el-table>
    </div>
  </el-dialog>
</template>

<script setup lang="ts" name="Index">
import * as echarts from 'echarts/core'
import { BarChart, GaugeChart, LineChart, PieChart } from 'echarts/charts' // 显式导入柱状图模块
import {
  GridComponent,
  LegendComponent,
  TitleComponent,
  ToolboxComponent,
  TooltipComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { useElementSize } from '@vueuse/core'
import { IotStatApi } from '@/api/pms/stat'
import SummaryCard from '@/components/SummaryCard/index.vue'
import { reactive, ref } from 'vue'
import {useLocaleStore} from "@/store/modules/locale";

/** IoT 首页 */
defineOptions({ name: 'IotRhStat' })
echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  TitleComponent,
  ToolboxComponent,
  GridComponent,
  LineChart,
  UniversalTransition,
  GaugeChart,
  BarChart
])

const teamDialogVisible = ref(false)
const teamTableData = ref([])
const currentDeptId = ref('')
const currentDateRange = ref([])

const materialTableData = ref([])

const queryParams = reactive({
  createTime: [],
})
const handleRowClick = (row, column, event) => {
  console.log('点击的行数据：', row);
  currentDeptId.value = row.deptId // 假设行数据中包含deptId字段
  currentDateRange.value = rateQueryParams.createTime

  // 打开弹窗并加载队伍详情数据
  teamDialogVisible.value = true
  // fetchTeamDetailData(row.deptId, rateQueryParams.createTime)
  const teamParams = {
    deptId: row.projectDeptId,
    createTime: rateQueryParams.createTime
  }
  IotStatApi.getRhTeamRate(teamParams).then(res => {
    teamTableData.value = res
  })

};

const handleDialogClose = () => {
  teamDialogVisible.value = false
  teamTableData.value = [] // 清空表格数据
}
// 格式化利用率为百分比
const formatRate = (row) => {
  return (row.utilizationRate * 100).toFixed(2) + '%'
}

// 注气量格式化函数（单位转换：方 -> 万方）
const gasInjectionFormatter = (row: any, column: any, cellValue: any, index: number | null) => {
  if (cellValue === null || cellValue === undefined || cellValue === '') return ''
  // 将方转换为万方，保留两位小数
  const value = parseFloat(cellValue)
  return (value / 10000).toFixed(2)
}

const by = ref({
  todo: undefined,
  finished: undefined
})
const fill = ref({
  filledCount: undefined,
  unfilledCount: undefined
})
const inspectt = ref({
  finished: 0,
  todo: 0
})
const rateQueryParams = reactive({
  createTime: [],
})
const backendData = ref([])
const statusChartRef = ref() // 设备数量统计的图表
const materialChartRef = ref() // 设备数量统计的图表
const zqlChartRef = ref() // 注气量统计的图表
const todayZqlRef = ref() // 注气量统计的图表
const { t } = useI18n() // 国际化
const device = ref({
  total: undefined,
  today: undefined
})
const maintain = ref({
  total: undefined,
  today: undefined
})
const work = ref({
  total: undefined,
  today: undefined
})
const inspect = ref({
  total: undefined,
  today: undefined
})

const status = ref({
  finished: 0,
  todo: 0
})
const todayStatus = ref({
  finished: 0,
  todo: 0
})
const handleDateChange = () => {
  IotStatApi.getRhRate(rateQueryParams).then((res) =>{
    materialTableData.value = res
  })
}
const typeData = ref({})
const materialData = ref({})
const orderSevenData = ref({})
const ywcbSevenData = ref({})
const zqlData = ref({})
const zqlTodayData = ref({})
/** 获取统计数据 */
const getStats = () => {
  initYwcbChart()
  // 获取基础统计数据
  IotStatApi.getDeviceCount('rh').then((res) => {
    device.value = res
  })
  IotStatApi.getMaintainCount('rh').then((res) => {
    maintain.value = res
  })
  IotStatApi.getMainWorkCount("").then((res) => {
    work.value = res
  })
  IotStatApi.getInspectCount("").then((res) => {
    inspect.value = res
  })
  // IotStatApi.getMaintenanceStatus("").then((res) => {
  //   status.value = res
  //   // initCharts()
  // })
  IotStatApi.getMaintenanceTodayStatus("").then((res) => {
    todayStatus.value = res
    initTopChart()
  })

  IotStatApi.getDeviceStatusCount('rh').then((res) => {
    typeData.value = res
    initDeviceStatusCharts()
  })
  // IotStatApi.getSafeCount().then((res) => {
  //   safe.value = res
  // })
  IotStatApi.getMaterial().then((res) => {
    materialData.value = res
    initMaterials()
  })

  IotStatApi.getOrderSeven('rh').then((res) => {
    orderSevenData.value = res
    initQxChart()
  })
  IotStatApi.getOrderYwcb('rh').then((res) => {
    ywcbSevenData.value = res
    initYwcbChart()
  })
  IotStatApi.getMaintenanceStatus('rh').then((res) => {
    by.value = res
  })
  IotStatApi.getRhZqlGases('rh').then((res) => {
    zqlData.value = res
    const localeStore = useLocaleStore()
    const lang = localeStore.getCurrentLocale.lang
    if (lang==='zh-CN') {
      initZqlChart('累计注气量','累计注水量')
    } else if (lang==='en') {
      initZqlChart('gas','water')
    }

  })
  IotStatApi.getRhZqlDaily('rh').then((res) => {
    zqlTodayData.value = res
    const localeStore = useLocaleStore()
    const lang = localeStore.getCurrentLocale.lang
    if (lang==='zh-CN') {
      initTodayZqlChart('当日注气量','当日注水量')
    } else if (lang==='en') {
      initTodayZqlChart('gas','water')
    }
  })
  const fillQueryParams = reactive({
    startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // 设置默认开始时间为 7 天前
    endTime: Date.now(), // 设置默认结束时间为当前时间
    createTime: [],
    deptId: '', // 选中的部门ID
    status: null // 填写状态
  })
  IotStatApi.getInspectStatuss(fillQueryParams, 'rh').then((res) => {
    inspectt.value = res
  })
  fillQueryParams.deptId = '157'
  IotStatApi.getDeptStatistics(fillQueryParams).then((res) => {
    fill.value = res.totalList[0] || []
  })

  // 计算近一周时间
  const end = new Date();
  const start = new Date();
  start.setTime(start.getTime() - 7 * 24 * 60 * 60 * 1000);

  // 格式化日期为后端需要的格式
  const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };

  rateQueryParams.createTime = [formatDate(start), formatDate(end)];
  IotStatApi.getRhRate(rateQueryParams).then((res) =>{
    materialTableData.value = res
  })
}
let materialInstance;
const initMaterials = () => {
  if (!materialChartRef.value) return
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color:'#B6C8DA'
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['50%', '80%'],
        avoidLabelOverlap: false,
        center: ['50%', '44%'],
        label: {
          show: false,
          position: 'outside',
          color:'#B6C8DA'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: materialData.value
      }
    ]
  }
  // 初始化图表
  materialInstance = echarts.init(materialChartRef.value)
  materialInstance.setOption(option)

  // 窗口缩放监听
  window.addEventListener('resize', handleMaterialResize)
  handleMaterialResize()
}
let zqlTodayInstance = null
const initTodayZqlChart = async (gas:any,water:any) => {
  if (!todayZqlRef.value) return
  zqlTodayInstance = echarts.init(todayZqlRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: zqlTodayData.value.series.map((item) => item.name),
      top: 30,
      textStyle: {
        color: '#B6C8DA'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: zqlTodayData.value.xAxis,
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
      axisLabel: {
        color: '#B6C8DA',
        formatter: (value) => value.split('-').join('/') // 显示为 2023/01
      }
    },
    yAxis: [
      {
        type: 'value',
        name:gas+'(m³)',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'left' // 左侧 Y 轴
      },
      // {
      //   type: 'value',
      //   name:water+'(m³)',
      //   axisLabel: {
      //     color: '#B6C8DA',
      //     formatter: '{value}'
      //   },
      //   splitLine: {
      //     show: true, // 显示水平网格线（默认显示）
      //     lineStyle: {
      //       // 水平网格线颜色（可设置为纯色或带透明度的颜色）
      //       color: '#457794', // 浅灰色半透明
      //       // 可选：设置线条类型（实线/虚线/点线）
      //       type: 'dashed'
      //     }
      //   },
      //   axisLine: {
      //     lineStyle: {
      //       color: '#B6C8DA'
      //     }
      //   },
      //   position: 'right', // 右侧 Y 轴
      //   splitLine: {
      //     show: false // 隐藏右侧 Y 轴的分割线
      //   }
      // }
    ],

    series: zqlTodayData.value.series.map((item, index) => {
      // 假设前两条曲线使用左侧 Y 轴，后两条曲线使用右侧 Y 轴
      // const yAxisIndex = index < 1 ? 0 : 1
      return {
        name: item.name,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: ['#5470c6', '#f1d209'][index]
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84,112,198,0.4)' },
            { offset: 1, color: 'rgba(84,112,198,0.1)' }
          ])
        },
        data: item.data,
        // yAxisIndex: yAxisIndex // 指定使用的 Y 轴
      }
    })
  }

  zqlTodayInstance.setOption(option)
  // 窗口缩放监听
  window.addEventListener('resize', handleZqlTodayResize)
  handleZqlTodayResize()
}

/** 初始化图表 */
const initDeviceStatusCharts = () => {
  // 设备数量统计
  echarts.init(statusChartRef.value).setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color: '#B6C8DA'
      }
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['50%', '80%'],
        avoidLabelOverlap: false,
        center: ['50%', '44%'],
        label: {
          show: false,
          position: 'outside',
          color: 'white'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: typeData.value
      }
    ]
  })
}

/** 初始化消息统计图表 */
const chartContainer = ref(null)
let chartInstance;

// 模拟数据获取
const fetchChartData = async () => {
  // 模拟异步请求
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        months: ['空压机', '增压机', '提纯撬'],
        repairs: [10, 30, 90]
      })
    }, 300)
  })
}

// 初始化图表配置
const initYwcbChart = async () => {
  if (!chartContainer.value) return

  // 获取数据
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      // formatter: (params) => {
      //   return `${params[0].axisValue}<br/>
      //           ${params[0].marker} ${params[0].seriesName}: ${params[0].value}`
      // }
    },
    // legend: {
    //   data: ['当日运维成本'],
    //   top: 1,
    //   textStyle: {
    //     color: '#B6C8DA'
    //   }
    // },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '1%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ywcbSevenData.value.xAxis,
      axisLabel: {
        color: '#B6C8DA',
        formatter: (value) => value.split('-').join('/')
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#B6C8DA',
        // formatter: (value) => Math.floor(value).toString()
      },
      splitLine: {
        show: true, // 显示水平网格线（默认显示）
        lineStyle: {
          // 水平网格线颜色（可设置为纯色或带透明度的颜色）
          color: '#457794', // 浅灰色半透明
          // 可选：设置线条类型（实线/虚线/点线）
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA'
        }
      }

    },
    series: [
      {
        name: '当日运维成本',
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#f69606' }])
        },
        emphasis: {
          focus: 'series'
        },
        data: ywcbSevenData.value.series
      }
    ]
  }

  // 初始化图表
  chartInstance = echarts.init(chartContainer.value)
  chartInstance.setOption(option)

  // 窗口缩放监听
  window.addEventListener('resize', handleResize)
  handleResize()
}

// 自适应调整
const handleResize = () => {
  chartInstance?.resize()
}

// 自适应调整
const handleQxResize = () => {
  qxInstance?.resize()
}
const handleZqlResize = () => {
  zqlInstance?.resize()
}
const handleZqlTodayResize = () => {
  zqlTodayInstance?.resize()
}
const handleMaterialResize = () => {
  materialInstance?.resize()
}
const topContainer = ref(null)
let topInstance;
// 响应式容器尺寸
const { width, height } = useElementSize(topContainer)

// 初始化图表配置
const getTopOption = () => {
  // backendData.value = data
  const data = backendData.value.sort((a, b) => a.value - b.value)
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params) => {
        const item = params[0]
        return `${item.name}<br/>${item.marker} ${item.value.toLocaleString()}`
      }
    },
    grid: {
      height: '200px',
      left: '6%',
      right: '6%',
      bottom: '18%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        color: '#B6C8DA',
        formatter: (value) => {
          if (value >= 10000) return `${(value / 10000).toFixed(1)}万`
          return value.toLocaleString()
        }
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
      splitLine: {
        show: true, // 显示水平网格线（默认显示）
        lineStyle: {
          // 水平网格线颜色（可设置为纯色或带透明度的颜色）
          color: '#457794', // 浅灰色半透明
          // 可选：设置线条类型（实线/虚线/点线）
          type: 'dashed'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: data.map((item) => item.category),
      axisTick: { show: false },
      axisLabel: { color: '#B6C8DA' },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      }
    },
    series: [
      {
        type: 'bar',
        data: data.map((item) => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.7, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ]),
          borderRadius: [0, 8, 8, 0]
        },
        label: {
          show: true,
          position: 'right',
          formatter: '{@value}',
          color: '#B6C8DA',
          fontWeight: 'bold'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

// 初始化图表
const initTopChart = async () => {
  await IotStatApi.getDeviceTypeCount('rh').then((res) => {
    backendData.value = res
  })
  if (!topContainer.value) return
  topInstance = echarts.init(topContainer.value)
  updateTopChart()
}

// 更新图表
const updateTopChart = () => {
  if (!topInstance) return
  topInstance.setOption(getTopOption())
}

// 自适应调整
watch([width, height], () => {
  topInstance?.resize()
})

// 监听数据变化
watch(
  backendData,
  () => {
    updateTopChart()
  },
  { deep: true }
)

const qxRef = ref(null)
let qxInstance;
let zqlInstance;

const initZqlChart = (gas:any,water:any) => {
  if (!zqlChartRef.value) return

  // 获取数据
  // ECharts配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          backgroundColor: '#6a7985'
        }
      }
      // trigger: 'axis',
      // axisPointer: {
      //   type: 'shadow'
      // },
      // formatter: (params) => {
      //   return `${params[0].axisValue}<br/>
      //           ${params[0].marker} ${params[0].seriesName}: ${params[0].value}`
      // }
    },
    legend: {
      data: zqlData.value.series.map((item) => item.name),
      top: 30,
      textStyle: {
        color: '#B6C8DA'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: zqlData.value.xAxis,
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
      axisLabel: {
        color: '#B6C8DA',
        formatter: (value) => value.split('-').join('/')
      }
    },
    yAxis: [
      {
        type: 'value',
        name: gas+'(m³)',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'left' // 左侧 Y 轴
      },
    ],
    series: zqlData.value.series.map((item, index) => {
      // 假设前两条曲线使用左侧 Y 轴，后两条曲线使用右侧 Y 轴
      return {
        name: item.name,
        type: 'bar',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: [ '#91cc75','#f1d209'][index]
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84,112,198,0.4)' },
            { offset: 1, color: 'rgba(84,112,198,0.1)' }
          ])
        },
        data: item.data,
      }
    })
  }

  // 初始化图表
  zqlInstance = echarts.init(zqlChartRef.value)
  zqlInstance.setOption(option)

  // 窗口缩放监听
  window.addEventListener('resize', handleZqlResize)
  handleZqlResize()

}

const initQxChart = () => {
  if (!qxRef.value) return
  qxInstance = echarts.init(qxRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: orderSevenData.value.series.map((item) => item.name),
      top: 30,
      textStyle: {
        color:'#B6C8DA'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: orderSevenData.value.xAxis,
      axisLabel: {
        color: '#B6C8DA',
        formatter: (value) => value.split('-').join('/')
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      },
    },
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'left' // 左侧 Y 轴
      },
      {
        type: 'value',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'right', // 右侧 Y 轴
        splitLine: {
          show: false // 隐藏右侧 Y 轴的分割线
        }
      }
    ],

    series: orderSevenData.value.series.map((item, index) => {
      // 假设前两条曲线使用左侧 Y 轴，后两条曲线使用右侧 Y 轴
      const yAxisIndex = index < 2 ? 0 : 1
      return {
        name: item.name,
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: ['#5470c6', '#f1d209', '#e14f0f', '#91cc75'][index]
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(84,112,198,0.4)' },
            { offset: 1, color: 'rgba(84,112,198,0.1)' }
          ])
        },
        data: item.data,
        yAxisIndex: yAxisIndex // 指定使用的 Y 轴
      }
    })
  }

  qxInstance.setOption(option)
  // 窗口缩放监听
  window.addEventListener('resize', handleQxResize)
  handleQxResize()
}

// 响应式调整
const resizeQxChart = () => qxInstance?.resize()
const resizeZqlChart = () => zqlInstance?.resize()
const resizeZqlTodayChart = () => zqlTodayInstance?.resize()
const resizeMaterialChart = () => materialInstance?.resize()
/** 初始化 */
onMounted(() => {
  getStats()
  // initChart()
  // initTopChart()
  // initActiveChart()
  // initQxChart()
  window.addEventListener('resize', resizeQxChart)
  // fetchTop()
  window.addEventListener('resize', () => topInstance?.resize())
})
onBeforeUnmount(() => {
  chartInstance?.dispose()
  window.removeEventListener('resize', () => chartInstance?.resize())
  topInstance?.dispose()
  window.removeEventListener('resize', handleResize)
  qxInstance?.dispose()
  window.removeEventListener('resize', resizeQxChart)
  zqlInstance?.dispose()
  window.removeEventListener('resize', resizeZqlChart)
  zqlTodayInstance?.dispose()
  window.removeEventListener('resize', resizeZqlTodayChart)
  materialInstance?.dispose()
  window.removeEventListener('resize', resizeMaterialChart)
})
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #3a6fa3;
  min-height: 100vh;
  padding: 20px;
}

.summary {
  margin-bottom: 20px;
}

::v-deep .chart-card {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.5);
  transition: all 0.3s ease;
  border: none;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  }
}

.safety-days-card {
  .safety-days-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 150px;
    position: relative;

    .days-number {
      font-size: 58px;
      font-weight: bold;
      color: darkorange;
      line-height: 1;
      transition: all 0.3s ease;
    }

    .days-number:hover {
      transform: scale(1.05);
    }

    .days-label {
      font-size: 20px;
      color: white;
      margin-top: 8px;
    }

    .safety-desc {
      font-size: 14px;
      color: #999;
      position: absolute;
      bottom: 10px;
      text-align: center;
      width: 90%;
    }
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 10px;
  }
}
::v-deep .el-card__header {
  border-bottom: none !important;
  padding-bottom: 0;
}

.table-container {
  padding: 16px;
  height: 320px;
  box-sizing: border-box;
  overflow: auto;

  // 滚动条样式优化
  &::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: transparent;
  }
}

// 修复表格hover样式
::v-deep .el-table__row:hover > td {
  background-color: rgba(255, 255, 255, 0.05) !important;
}
.custom-scroll-dialog {
  /* 可选：限制对话框整体最大高度（避免超出屏幕） */
  max-height: 90vh;
  overflow: hidden; /* 隐藏整体溢出，避免出现双重滚动条 */
}
/* 滚动内容容器：核心样式 */
.dialog-scroll-content {
  max-height: 60vh; /* 固定最大高度（可根据需求调整，如500px） */
  overflow-y: auto; /* 垂直方向溢出时显示滚动条 */
  padding-right: 8px; /* 避免滚动条遮挡内容（可选） */
}

/* 优化滚动条样式（可选，提升UI体验） */
.dialog-scroll-content::-webkit-scrollbar {
  width: 6px; /* 滚动条宽度 */
}
.dialog-scroll-content::-webkit-scrollbar-thumb {
  background-color: #e5e7eb; /* 滚动条滑块颜色 */
  border-radius: 3px; /* 滚动条圆角 */
}
.dialog-scroll-content::-webkit-scrollbar-thumb:hover {
  background-color: #d1d5db; /*  hover时滑块颜色 */
}
</style>
