<template>
  <div class="min-h-screen p-4 bg-[#3a6fa3] flex flex-col">
    <el-row :gutter="16" class="summary">
      <!-- 原有的统计卡片部分保持不变 -->
      <el-col v-loading="loading" :sm="3" :xs="24">
        <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 v-loading="loading" :sm="3" :xs="24">
        <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 v-loading="loading" :sm="3" :xs="24">
        <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 v-loading="loading" :sm="3" :xs="24">
        <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 v-loading="loading" :sm="3" :xs="24">
        <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 v-loading="loading" :sm="3" :xs="24">
        <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 v-loading="loading" :sm="3" :xs="24">
        <SummaryCard
          :value="inspect.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 v-loading="loading" :sm="3" :xs="12">
        <SummaryCard
          :value="inspect.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">
      <!-- 设备状态统计和工单数量情况图表部分保持不变 -->
      <el-col :span="6" :xs="24">
        <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
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              min-height: 290px;
              flex-direction: column;
              gap: 6px;
            "
          >
            <div ref="statusChartRef" style="width: 100%; height: 170px; max-width: 200px"></div>
            <div class="text-[12px] h-[100px] w-[90%] flex flex-col justify-between items-center">
              <div v-for="item in legendData" :key="item.name" class="flex">
                <div class="flex items-center gap-1">
                  <span class="status-legend-color" :style="{ background: item.color }"></span>
                  <span class="w-[100px] text-[#fff]">{{ item.name }}</span>
                </div>
                <div class="flex items-center">
                  <span class="text-[#fff] text-right w-12">{{ item.value }} 台</span>
                  <span class="status-legend-percent text-right w-14">{{ item.percent }}%</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="10" :xs="24">
        <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"
                >设备分布及价值（国内RMB）</span
              >
            </div>
          </template>
          <div
            style="
              display: flex;
              min-height: 295px;
              flex-direction: column;
              align-items: center;
              gap: 8px;
            "
          >
            <div ref="domesticChartRef" style="width: 100%; height: 200px; max-width: 420px"></div>
            <div
              class="domestic-legend"
              style="
                display: flex;
                width: 100%;
                max-width: 520px;
                font-size: 12px;
                flex-wrap: wrap;
                gap: 1px;
              "
            >
              <div
                v-for="(item, idx) in domesticData"
                :key="item.dept"
                class="legend-item"
                style="display: flex; align-items: center; gap: 8px; padding: 4px 8px"
              >
                <span
                  class="legend-dot"
                  :style="{
                    background: statusColors[idx % statusColors.length],
                    width: '10px',
                    height: '10px',
                    display: 'inline-block',
                    borderRadius: '50%'
                  }"
                ></span>
                <span
                  class="legend-name"
                  style="
                    display: inline-block;
                    max-width: 150px;
                    overflow: hidden;
                    color: #fff;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                  "
                  >{{ item.dept }}</span
                >
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8" :xs="24">
        <WorkloadChart />
        <!-- <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-[290px]"></div>
        </el-card> -->
      </el-col>
    </el-row>
    <el-row :gutter="16" class="mb-4">
      <el-col class="mb-4" :span="12" :xs="24">
        <AvailabilityChart />
      </el-col>
      <el-col class="mb-4" :span="12" :xs="24">
        <ExceptionChart />
      </el-col>
    </el-row>
    <el-row :gutter="16" class="mb-4">
      <el-col :span="12" :xs="24">
        <UtilizationChart />
      </el-col>
      <!-- <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 class="table-container">
            <div ref="utilizationRef" style="width: 100%; height: 360px"></div>
          </div>
        </el-card> -->
      <!-- 添加两个卡片 -->
      <!--          <div class="flex justify-between mb-2">-->
      <!--            <el-card class="stat-card">-->
      <!--              <div class="flex flex-row justify-evenly">-->
      <!--                <div>-->
      <!--                  <Icon icon="fa-solid:award" size="30" color="blue" />-->
      <!--                </div>-->
      <!--                <div class="flex flex-col items-center">-->
      <!--                  <span class="text-sm " style="color: #101010">{{t('stat.spareCount')}}</span>-->
      <!--                  <span class="text-lg font-bold">{{ totalMaterialCount }}</span>-->
      <!--                </div>-->
      <!--              </div>-->
      <!--            </el-card>-->
      <!--            <el-card class="stat-card">-->
      <!--              <div class="flex flex-row justify-evenly">-->
      <!--                <div>-->
      <!--                  <Icon icon="fa-solid:yen-sign" size="30" color="orange" />-->
      <!--                </div>-->
      <!--                <div class="flex flex-col items-center">-->
      <!--                  <span class="text-sm " style="color: #101010">{{t('stat.spareAmount')}}</span>-->
      <!--                  <span class="text-lg font-bold">{{ totalMaterialCost }}</span>-->
      <!--                </div>-->
      <!--              </div>-->
      <!--            </el-card>-->
      <!--          </div>-->
      <!--          <div ref="sparePartRef" class="h-[330px]"></div>-->
      <!-- 月度工作量表 -->
      <el-col :span="12" :xs="24">
        <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">月度工作量表</span>
            </div>
          </template>
          <div class="overflow-auto">
            <el-table
              :data="monthData"
              border
              height="420px"
              :disabled-affix="true"
              style="width: 100%"
              :header-cell-style="{ color: '#fff', 'background-color': 'transparent' }"
              :cell-style="{ color: '#fff' }"
              :summary-method="tableSummary"
              show-summary
            >
              <el-table-column prop="month" label="月份" width="50" fixed="left" align="center" />

              <el-table-column label="2025年" align="center">
                <el-table-column
                  prop="y2025_fractures"
                  label="压裂井数"
                  align="center"
                  min-width="50"
                />
                <el-table-column
                  prop="y2025_layers"
                  label="压裂层数"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="y2025_pump_trips"
                  label="泵车台次"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="y2025_oil_wells"
                  label="连油井数"
                  min-width="50"
                  align="center"
                />
              </el-table-column>

              <el-table-column label="2024年" align="center">
                <el-table-column
                  prop="y2024_fractures"
                  label="压裂井数"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="y2024_layers"
                  label="压裂层数"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="y2024_pump_trips"
                  label="泵车台次"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="y2024_oil_wells"
                  label="连油井数"
                  min-width="50"
                  align="center"
                />
              </el-table-column>

              <el-table-column label="同比增长量" align="center">
                <el-table-column
                  prop="diff_fractures"
                  label="压裂井数"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="diff_layers"
                  label="压裂层数"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="diff_pump_trips"
                  label="泵车台次"
                  min-width="50"
                  align="center"
                />
                <el-table-column
                  prop="diff_oil_wells"
                  label="连油井数"
                  min-width="50"
                  align="center"
                />
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      <!-- 月度工作量表结束 -->
    </el-row>
    <ConstructionBriefing />
    <!-- <el-row :gutter="16" class="mb-4">
      <el-col :span="24" :xs="24">

      </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': '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>

  <el-dialog v-model="projectDataDialog" width="45vw" class="custom-scroll-dialog">
    <div class="dialog-scroll-content">
      <el-card class="bg-[#284d72]!" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium" style="color: #b6c8da"
              >国内设备分布及价值（国内RMB）</span
            >
          </div>
        </template>
        <div class="overflow-auto" style="min-height: 260px">
          <el-table
            :data="domesticData"
            border
            :header-cell-style="{ color: '#fff', 'background-color': 'transparent' }"
            :cell-style="{ color: '#fff' }"
            style="width: 100%"
            :summary-method="tableSummary"
            show-summary
          >
            <el-table-column prop="index" label="序号" width="60" align="center" fixed="left" />
            <el-table-column prop="dept" label="项目部" width="120" align="center" fixed="left" />
            <el-table-column prop="count" label="设备数量" min-width="100" align="center" />
            <el-table-column
              prop="orig_value"
              label="原值（万元）"
              min-width="120"
              align="center"
            />
            <el-table-column prop="net_value" label="净值（万元）" min-width="120" align="center" />
            <el-table-column prop="orig_ratio" label="原值占比" min-width="100" align="center" />
          </el-table>
        </div>
      </el-card>
    </div>
  </el-dialog>
  <el-dialog v-model="projectDataDialog2" width="45vw" class="custom-scroll-dialog">
    <div class="dialog-scroll-content">
      <el-card class="bg-[#284d72]!" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium" style="color: #b6c8da"
              >伊拉克设备分布及价值（美元）</span
            >
          </div>
        </template>
        <div class="overflow-auto" style="min-height: 260px">
          <el-table
            :data="iraqTableData"
            border
            :header-cell-style="{ color: '#fff', 'background-color': 'transparent' }"
            :cell-style="{ color: '#fff' }"
            style="width: 100%"
          >
            <el-table-column prop="index" label="序号" width="60" align="center" fixed="left" />
            <el-table-column prop="dept" label="项目部" width="120" align="center" fixed="left" />
            <el-table-column prop="count" label="设备数量" min-width="100" align="center" />
            <el-table-column
              prop="orig_value_usd"
              label="原值（万元）"
              min-width="120"
              align="center"
            />
            <el-table-column
              prop="net_value_usd"
              label="净值（万元）"
              min-width="120"
              align="center"
            />
            <el-table-column prop="orig_ratio" label="原值占比" min-width="100" align="center" />
          </el-table>
        </div>
      </el-card>
    </div>
  </el-dialog>

  <el-dialog v-model="projectDataDialog3" width="45vw" class="custom-scroll-dialog">
    <div class="dialog-scroll-content">
      <el-card class="bg-[#284d72]!" shadow="never">
        <template #header>
          <div class="flex items-center justify-between">
            <span class="text-base font-medium" style="color: #b6c8da"
              >利比亚设备分布及价值（第纳尔）</span
            >
          </div>
        </template>
        <div class="overflow-auto" style="min-height: 260px">
          <el-table
            :data="libyaTableData"
            border
            :header-cell-style="{ color: '#fff', 'background-color': 'transparent' }"
            :cell-style="{ color: '#fff' }"
            :row-class-name="tableRowClass"
            style="width: 100%"
            :summary-method="tableSummary"
          >
            <el-table-column prop="index" label="序号" width="60" align="center" fixed="left" />
            <el-table-column prop="dept" label="项目部" width="120" align="center" fixed="left" />
            <el-table-column prop="count" label="设备数量" min-width="100" align="center" />
            <el-table-column
              prop="orig_value"
              label="原值（万元）"
              min-width="120"
              align="center"
            />
            <el-table-column prop="net_value" label="净值（万元）" min-width="120" align="center" />
            <el-table-column prop="orig_ratio" label="原值占比" min-width="100" align="center" />
          </el-table>
        </div>
      </el-card>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { MemberSummaryRespVO } from '@/api/mall/statistics/member'
import SummaryCard from '@/components/SummaryCard/index.vue'
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 { IotStatApi } from '@/api/pms/stat'
import { ref, onMounted, computed, watch, nextTick, reactive } from 'vue'
import { useLocaleStore } from '@/store/modules/locale'
import WorkloadChart from './rdkb/workload.vue'
import UtilizationChart from './rdkb/utilization.vue'
import AvailabilityChart from './rdkb/availability.vue'
import ExceptionChart from './rdkb/exception.vue'
import ConstructionBriefing from './rdkb/constructionBriefing.vue'

/** 会员统计 */
defineOptions({ name: 'IotRdStat' })

echarts.use([
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LabelLayout,
  TitleComponent,
  ToolboxComponent,
  GridComponent,
  LineChart,
  UniversalTransition,
  GaugeChart,
  BarChart
])

const loading = ref(true) // 加载中
const teamDialogVisible = ref(false)
const teamTableData = ref([])
const currentDeptId = ref('')
const currentDateRange = ref([])
const materialTableData = ref([])
const handleDateChange = () => {
  IotStatApi.getRdRate(rateQueryParams).then((res) => {
    materialTableData.value = res
  })
}
const rateQueryParams = reactive({
  createTime: []
})
const handleDialogClose = () => {
  teamDialogVisible.value = false
  teamTableData.value = [] // 清空表格数据
}

// 格式化利用率为百分比
const formatRate = (row) => {
  return (row.utilizationRate * 100).toFixed(2) + '%'
}
// 数字格式化为千分位，保留两位小数
const formatNumber = (v) => {
  if (v == null || v === '') return '-'
  const n = Number(v)
  if (isNaN(n)) return String(v)
  return n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
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)
  // debugger
  const teamParams = {
    deptId: row.projectDeptId,
    createTime: rateQueryParams.createTime
  }
  IotStatApi.getRdTeamRate(teamParams).then((res) => {
    teamTableData.value = res
  })
}
const dateRange = ref<[Date, Date] | null>(null)
const summary = ref<MemberSummaryRespVO>() // 会员统计数据
const statusChartRef = ref() // 设备数量统计的图表
let statusChartInstance = null
const qxRef = ref(null)
let qxInstance = null
const sparePartRef = ref(null)
let sparePartInstance = null
const maintenanceChartRef = ref(null)
let maintenanceChartInstance = null
const inspectChartRef = ref(null)
let inspectChartInstance = null
const inspectionChartRef = ref(null)
let inspectionChartInstance = null
const { t } = useI18n() // 国际化
const maintenanceChartRef1 = ref(null)

const typeData = ref([])
// 配色（与图表保持一致）
const statusColors = ['#2ed3df', '#34d399', '#ff6b95', '#4aa3ff', '#f59e0b', '#ef4444', '#7dd3fc']

/**
 * 将后端返回的多种可能结构规范化为数组形式：
 * - 如果已经是数组则直接使用
 * - 如果包含 data 或 series 字段且为数组则优先使用
 * - 否则把对象的键值对转换为 {name, value} 数组
 */
const normalizeTypeData = (val) => {
  if (Array.isArray(val)) return val
  if (!val || typeof val !== 'object') return []
  if (Array.isArray(val.data)) return val.data
  if (Array.isArray(val.series)) return val.series
  // plain object with keys -> map to array
  return Object.keys(val).map((k) => ({ name: k, value: val[k] }))
}

const legendData = computed(() => {
  const arr = normalizeTypeData(typeData.value)
  const total = arr.reduce((s, it) => s + (Number(it.value) || 0), 0)
  return arr.map((it, idx) => ({
    name: it.name,
    value: it.value || 0,
    percent: total ? ((Number(it.value) / total) * 100).toFixed(2) : '0.00',
    color: statusColors[idx % statusColors.length]
  }))
})
const orderSevenData = ref({})
const device = ref({
  total: undefined,
  today: undefined
})
const maintain = ref({
  total: undefined,
  today: undefined
})
const by = ref({
  todo: undefined,
  finished: undefined
})
const fill = ref({
  filledCount: undefined,
  unfilledCount: undefined
})
const abnormalDevice = ref({
  total: undefined,
  today: undefined
})
const outliers = ref({
  total: undefined,
  today: undefined
})
const inspect = ref({
  finished: 0,
  todo: 0
})
const sparePartData = ref({
  xAxis: ['扳手', '水杯', '皮带', '螺丝'],
  series: [
    {
      name: '数量',
      type: 'bar',
      data: [10, 20, 15, 25],
      yAxisIndex: 0
    },
    {
      name: '金额',
      type: 'line',
      data: [100, 200, 150, 250],
      yAxisIndex: 1
    }
  ]
})
const sparePartDataEng = ref({
  xAxis: ['spanner', 'cup', 'belt', 'screw'],
  series: [
    {
      name: 'count',
      type: 'bar',
      data: [10, 20, 15, 25],
      yAxisIndex: 0
    },
    {
      name: 'amount',
      type: 'line',
      data: [100, 200, 150, 250],
      yAxisIndex: 1
    }
  ]
})
// 模拟巡检工单数据
const totalInspectionOrders = ref(80)
const completedInspectionOrders = ref(60)

// 计算物料消耗数量及费用
const totalMaterialCount = computed(() => {
  const quantitySeries = sparePartData.value.series.find((item) => item.name === '数量')
  return quantitySeries ? quantitySeries.data.reduce((sum, val) => sum + val, 0) : 0
})

const totalMaterialCost = computed(() => {
  const costSeries = sparePartData.value.series.find((item) => item.name === '金额')
  return costSeries ? costSeries.data.reduce((sum, val) => sum + val, 0) : 0
})

const getStats = () => {
  IotStatApi.getDeviceStatusCount('rd').then((res) => {
    typeData.value = res
    initDeviceStatusCharts()
  })
  IotStatApi.getOrderSeven('rd').then((res) => {
    orderSevenData.value = res
    initQxChart()
  })
  IotStatApi.getDeviceCount('rd').then((res) => {
    device.value = res
  })
  IotStatApi.getMaintainCount('rd').then((res) => {
    maintain.value = res
  })
  IotStatApi.getMaintenanceStatus('rd').then((res) => {
    by.value = res
    initMaintenanceChart()
  })
  const fillQueryParams = reactive({
    startTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // 设置默认开始时间为 7 天前
    endTime: Date.now(), // 设置默认结束时间为当前时间
    createTime: [],
    deptId: null, // 选中的部门ID
    status: null // 填写状态
  })
  IotStatApi.getInspectStatuss(fillQueryParams, 'rd').then((res) => {
    inspect.value = res
    initInspectChart()
  })
  fillQueryParams.deptId = '163'
  IotStatApi.getDeptStatistics(fillQueryParams).then((res) => {
    fill.value = res.totalList[0] || []
  })
  const localeStore = useLocaleStore()
  const lang = localeStore.getCurrentLocale.lang
  if (lang === 'zh-CN') {
    initSparePartChart('数量', '金额', sparePartData)
  } else if (lang === 'en') {
    initSparePartChart('count', 'amount', sparePartDataEng)
  }
  initInspectionChart()

  // 计算近一周时间
  const end = new Date()
  const start = new Date()

  const now = new Date()
  // 构造：今年 1 月 1 日 00:00:00
  const firstDay = new Date(now.getFullYear(), 0, 1, 0, 0, 0, 0)
  // 转时间戳（毫秒），如需秒级时间戳，加 .getTime() / 1000

  start.setTime(firstDay.getTime())

  // 格式化日期为后端需要的格式
  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.getRdRate(rateQueryParams).then((res) => {
    materialTableData.value = res
  })
}

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: {
          formatter: '{value}'
        },
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        position: 'left' // 左侧 Y 轴
      },
      {
        type: 'value',
        axisLabel: {
          formatter: '{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) => {
      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)
}

const initSparePartChart = (count: any, amount: any, spare: {}) => {
  if (!sparePartRef.value) return
  sparePartInstance = echarts.init(sparePartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: [count, amount],
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: spare.value.xAxis,
      axisLabel: {
        color: '#B6C8DA'
      },
      axisLine: {
        lineStyle: {
          color: '#B6C8DA' // X轴线白色半透明
        }
      }
    },
    yAxis: [
      {
        type: 'value',
        name: count,
        position: 'left',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        }
      },
      {
        type: 'value',
        name: amount,
        position: 'right',
        axisLabel: {
          color: '#B6C8DA',
          formatter: '{value}'
        },
        splitLine: {
          show: true, // 显示水平网格线（默认显示）
          lineStyle: {
            // 水平网格线颜色（可设置为纯色或带透明度的颜色）
            color: '#457794', // 浅灰色半透明
            // 可选：设置线条类型（实线/虚线/点线）
            type: 'dashed'
          }
        },
        axisLine: {
          lineStyle: {
            color: '#B6C8DA'
          }
        },
        splitLine: {
          show: false
        }
      }
    ],
    series: spare.value.series.map((item, index) => ({
      name: item.name,
      type: item.type,
      data: item.data,
      yAxisIndex: item.yAxisIndex,
      itemStyle: {
        color: ['#6084fb', '#5aef13'][index]
      }
    }))
  }

  sparePartInstance.setOption(option)
}

// 设备利用率柱状图
const utilizationRef = ref(null)
let utilizationInstance: any = null
const lastHoveredIndex = ref<number | null>(null)

const initUtilizationChart = () => {
  if (!utilizationRef.value) return
  try {
    if (utilizationInstance) {
      utilizationInstance.dispose()
      utilizationInstance = null
    }
  } catch (e) {}
  utilizationInstance = echarts.init(utilizationRef.value)
  const xData = (materialTableData.value as any[]).map(
    (it) => it.projectDeptName || it.dept || it.projectDept
  )
  const seriesData = (materialTableData.value as any[]).map((it) => {
    const v = (it as any).utilizationRate
    // 只保留整数部分（百分比的整数），例如 0.528 -> 52
    return v == null ? 0 : Math.trunc(Number(v) * 100)
  })
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const p = params[0] || params
        return `${p.name}: ${p.data}%`
      }
    },
    xAxis: {
      type: 'category',
      data: xData,
      axisLabel: { color: '#B6C8DA', rotate: 20 }
    },
    yAxis: {
      type: 'value',
      axisLabel: { formatter: '{value}%', color: '#B6C8DA' }
    },
    grid: { left: '3%', right: '4%', bottom: '12%', containLabel: true },
    series: [
      {
        type: 'bar',
        data: seriesData,
        itemStyle: { color: statusColors[1] },
        barWidth: '40%',
        label: { show: true, position: 'top', formatter: '{c}%' }
      }
    ]
  }
  utilizationInstance.setOption(option)
  // 鼠标悬停时展示队伍详情弹窗
  try {
    // 移除旧的监听，防止重复绑定
    if (utilizationInstance.off) utilizationInstance.off('mouseover')
    utilizationInstance.on('mouseover', (params: any) => {
      try {
        if (!params) return
        // 仅处理柱状图系列的悬停
        if (params.componentType !== 'series' || params.seriesType !== 'bar') return
        const idx = params.dataIndex
        if (idx == null) return
        // 防止重复请求
        if (lastHoveredIndex.value === idx && teamDialogVisible.value) return
        lastHoveredIndex.value = idx
        const row = ((materialTableData.value as any[])[idx] || {}) as any
        const teamParams: any = {
          deptId: row.projectDeptId || row.deptId || row.dept || row.projectDept,
          createTime: rateQueryParams.createTime
        }
        teamDialogVisible.value = true
        teamTableData.value = []
        IotStatApi.getRdTeamRate(teamParams).then((res) => {
          teamTableData.value = res
        })
      } catch (e) {}
    })
  } catch (e) {}

  window.addEventListener('resize', () => {
    try {
      utilizationInstance && utilizationInstance.resize()
    } catch (e) {}
  })
}

watch(
  materialTableData,
  () => {
    nextTick(() => initUtilizationChart())
  },
  { deep: true }
)

onMounted(() => {
  initUtilizationChart()
})

onUnmounted(() => {
  try {
    if (utilizationInstance) {
      try {
        if (utilizationInstance.off) utilizationInstance.off('mouseover')
      } catch (e) {}
      utilizationInstance.dispose()
      utilizationInstance = null
    }
  } catch (e) {}
})

const initInspectChart = () => {
  if (!inspectChartRef.value) return
  inspectChartInstance = echarts.init(inspectChartRef.value)
  const completionRate =
    (inspect.value.finished / (inspect.value.finished + inspect.value.todo)) * 100
  // debugger
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color: '#B6C8DA'
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        label: {
          show: false,
          position: 'outside'
        },
        emphasis: {
          label: {
            color: '#B6C8DA',
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        // itemStyle: {
        //   color: ['#e4a317', '#5aef13']
        // },
        data: [
          { name: '完成率', value: completionRate.toFixed(2) },
          { name: '未完成率', value: 100 - completionRate.toFixed(2) }
        ]
      }
    ]
  }
  inspectChartInstance.setOption(option)
}

const initMaintenanceChart = () => {
  if (!maintenanceChartRef.value) return
  maintenanceChartInstance = echarts.init(maintenanceChartRef.value)
  const completionRate = (by.value.finished / (by.value.finished + by.value.todo)) * 100
  // debugger
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'horizontal', // 水平排列图例项
      bottom: '0%', // 放置在底部
      icon: 'circle',
      textStyle: {
        color: '#B6C8DA'
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        label: {
          show: false,
          position: 'outside'
        },
        emphasis: {
          label: {
            color: '#B6C8DA',
            show: true,
            fontSize: 15,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: true
        },
        data: [
          { name: '完成率', value: completionRate.toFixed(2) },
          { name: '未完成率', value: 100 - completionRate.toFixed(2) }
        ]
      }
    ]
  }
  maintenanceChartInstance.setOption(option)
}

const initInspectionChart = () => {
  if (!inspectionChartRef.value) return
  inspectionChartInstance = echarts.init(inspectionChartRef.value)
  const completionRate = (completedInspectionOrders.value / totalInspectionOrders.value) * 100
  const option = {
    series: [
      {
        type: 'pie',
        radius: ['50%', '80%'],
        data: [
          { value: completionRate, name: '完成率' },
          { value: 100 - completionRate, name: '未完成率' }
        ]
      }
    ]
  }
  inspectionChartInstance.setOption(option)
}

/** 初始化图表 */
const initDeviceStatusCharts = () => {
  if (!statusChartRef.value) return
  // dispose old instance
  try {
    if (statusChartInstance) {
      statusChartInstance.dispose()
      statusChartInstance = null
    }
  } catch (e) {
    // ignore
  }
  statusChartInstance = echarts.init(statusChartRef.value)
  const data = normalizeTypeData(typeData.value)
  const option = {
    color: statusColors,
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    series: [
      {
        name: '',
        type: 'pie',
        radius: ['38%', '58%'],
        center: ['50%', '30%'],
        avoidLabelOverlap: false,
        label: { show: false },
        labelLine: { show: false },
        data: data.map((it) => ({ name: it.name, value: it.value }))
      }
    ]
  }
  statusChartInstance.setOption(option)
}

// 月度工作量表数据
const monthData = ref<any[]>([
  {
    month: '1月',
    y2025_fractures: 49,
    y2025_layers: 102,
    y2025_pump_trips: 621,
    y2025_oil_wells: 17,
    y2024_fractures: 23,
    y2024_layers: 42,
    y2024_pump_trips: 347,
    y2024_oil_wells: 9
  },
  {
    month: '2月',
    y2025_fractures: 30,
    y2025_layers: 52,
    y2025_pump_trips: 438,
    y2025_oil_wells: 15,
    y2024_fractures: 14,
    y2024_layers: 41,
    y2024_pump_trips: 46,
    y2024_oil_wells: 11
  },
  {
    month: '3月',
    y2025_fractures: 48,
    y2025_layers: 127,
    y2025_pump_trips: 326,
    y2025_oil_wells: 30,
    y2024_fractures: 42,
    y2024_layers: 58,
    y2024_pump_trips: 321,
    y2024_oil_wells: 17
  },
  {
    month: '4月',
    y2025_fractures: 49,
    y2025_layers: 130,
    y2025_pump_trips: 1203,
    y2025_oil_wells: 45,
    y2024_fractures: 32,
    y2024_layers: 184,
    y2024_pump_trips: 1046,
    y2024_oil_wells: 30
  },
  {
    month: '5月',
    y2025_fractures: 13,
    y2025_layers: 76,
    y2025_pump_trips: 701,
    y2025_oil_wells: 18,
    y2024_fractures: 73,
    y2024_layers: 133,
    y2024_pump_trips: 414,
    y2024_oil_wells: 24
  },
  {
    month: '6月',
    y2025_fractures: 34,
    y2025_layers: 187,
    y2025_pump_trips: 831,
    y2025_oil_wells: 30,
    y2024_fractures: 29,
    y2024_layers: 113,
    y2024_pump_trips: 750,
    y2024_oil_wells: 35
  },
  {
    month: '7月',
    y2025_fractures: 30,
    y2025_layers: 230,
    y2025_pump_trips: 1157,
    y2025_oil_wells: 51,
    y2024_fractures: 24,
    y2024_layers: 47,
    y2024_pump_trips: 326,
    y2024_oil_wells: 17
  },
  {
    month: '8月',
    y2025_fractures: 59,
    y2025_layers: 218,
    y2025_pump_trips: 1163,
    y2025_oil_wells: 12,
    y2024_fractures: 36,
    y2024_layers: 121,
    y2024_pump_trips: 1107,
    y2024_oil_wells: 26
  },
  {
    month: '9月',
    y2025_fractures: 48,
    y2025_layers: 80,
    y2025_pump_trips: 440,
    y2025_oil_wells: 39,
    y2024_fractures: 35,
    y2024_layers: 162,
    y2024_pump_trips: 928,
    y2024_oil_wells: 36
  },
  {
    month: '10月',
    y2025_fractures: 45,
    y2025_layers: 99,
    y2025_pump_trips: 697,
    y2025_oil_wells: 49,
    y2024_fractures: 36,
    y2024_layers: 116,
    y2024_pump_trips: 891,
    y2024_oil_wells: 33
  },
  {
    month: '11月',
    y2025_fractures: null,
    y2025_layers: null,
    y2025_pump_trips: null,
    y2025_oil_wells: null,
    y2024_fractures: 19,
    y2024_layers: 102,
    y2024_pump_trips: 582,
    y2024_oil_wells: 36
  },
  {
    month: '12月',
    y2025_fractures: null,
    y2025_layers: null,
    y2025_pump_trips: null,
    y2025_oil_wells: null,
    y2024_fractures: 51,
    y2024_layers: 186,
    y2024_pump_trips: 971,
    y2024_oil_wells: 32
  }
])

// 计算同比差值（2025 - 2024），保留 null 的情况
monthData.value.forEach((row) => {
  const f2025 = row.y2025_fractures
  const f2024 = row.y2024_fractures
  row.diff_fractures = f2025 == null || f2024 == null ? null : f2025 - f2024

  const l2025 = row.y2025_layers
  const l2024 = row.y2024_layers
  row.diff_layers = l2025 == null || l2024 == null ? null : l2025 - l2024

  const p2025 = row.y2025_pump_trips
  const p2024 = row.y2024_pump_trips
  row.diff_pump_trips = p2025 == null || p2024 == null ? null : p2025 - p2024

  const o2025 = row.y2025_oil_wells
  const o2024 = row.y2024_oil_wells
  row.diff_oil_wells = o2025 == null || o2024 == null ? null : o2025 - o2024
})

// 表格合计方法（稳健实现，避免把图表配置或数据插入此处）
const tableSummary = ({ columns, data }: any) => {
  const sums: any[] = []
  columns.forEach((column: any, index: number) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const property = column.property
    if (!property) {
      sums[index] = ''
      return
    }
    let total = 0
    let hasValue = false
    data.forEach((row: any) => {
      const val = row[property]
      if (val != null && !isNaN(Number(val))) {
        total += Number(val)
        hasValue = true
      }
    })
    // 对原值占比列（orig_ratio）在国内表中不显示合计，留空
    if (data === domesticData.value && property === 'orig_ratio') {
      sums[index] = ''
    } else {
      sums[index] = hasValue ? total : ''
    }
  })
  return sums
}

let projectDataDialog = ref(false)
let projectDataDialog2 = ref(false)
let projectDataDialog3 = ref(false)

// projectDataRowClick
const projectDataRowClick = (row, column, event) => {
  console.log('点击的行数据：', row)

  if (row.dept === '国内') {
    // 显示国内表格
    projectDataDialog.value = true
  } else if (row.dept === '伊拉克') {
    // 显示伊拉克表格
    projectDataDialog2.value = true
  } else if (row.dept === '利比亚') {
    // 显示利比亚表格
    projectDataDialog3.value = true
  }
}

const domesticData = ref<any[]>([
  {
    index: 1,
    dept: '公摊',
    count: 13,
    orig_value: 1506.88,
    net_value: 559.95,
    orig_ratio: '2.77%'
  },
  {
    index: 2,
    dept: '新疆项目部',
    count: 58,
    orig_value: 5118.1,
    net_value: 1182.49,
    orig_ratio: '9.40%'
  },
  {
    index: 3,
    dept: '青海项目',
    count: 33,
    orig_value: 7004.23,
    net_value: 1758.8,
    orig_ratio: '12.86%'
  },
  {
    index: 4,
    dept: '东部项目部',
    count: 49,
    orig_value: 5273.54,
    net_value: 683.58,
    orig_ratio: '9.68%'
  },
  {
    index: 5,
    dept: '西南连油项目部',
    count: 24,
    orig_value: 4059.36,
    net_value: 743.24,
    orig_ratio: '7.45%'
  },
  {
    index: 6,
    dept: '西南压裂项目部',
    count: 47,
    orig_value: 14591.62,
    net_value: 6030.84,
    orig_ratio: '26.79%'
  },
  {
    index: 7,
    dept: '伊拉克 哈法亚连油',
    count: 120,
    orig_value: 694.78,
    net_value: 91.26,
    orig_ratio: '9.07%'
  },
  {
    index: 8,
    dept: '伊拉克 哈法亚压裂',
    count: 132,
    orig_value: 1008.92,
    net_value: 575.91,
    orig_ratio: '13.17%%'
  },
  {
    index: 9,
    dept: '伊拉克 B9增产',
    count: 27,
    orig_value: 304.72,
    net_value: 124.1,
    orig_ratio: '3.98%'
  },
  {
    index: 10,
    dept: '利比亚连油8队',
    count: 22,
    orig_value: 2025.52,
    net_value: 1731.79,
    orig_ratio: '4.85%'
  }
])

// 初始化 国内设备分布饼图相关（放在 domesticData 声明后）
const domesticChartRef = ref(null)
let domesticInstance: any = null

const handleDomesticResize = () => {
  try {
    if (domesticInstance) domesticInstance.resize()
  } catch (e) {}
}

const initDomesticChart = () => {
  if (!domesticChartRef.value) return
  try {
    if (domesticInstance) {
      domesticInstance.dispose()
      domesticInstance = null
    }
  } catch (e) {}
  domesticInstance = echarts.init(domesticChartRef.value)
  const data = domesticData.value.map((it) => ({
    name: it.dept,
    value: Number(it.orig_value) || 0,
    orig_ratio: it.orig_ratio || ''
  }))
  const option = {
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { show: false },
    color: statusColors,
    series: [
      {
        name: '国内设备价值',
        type: 'pie',
        // 使用实心扇形（非环形）
        radius: ['0%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'outside',
          formatter: function (params) {
            const val = Number(params.value) || 0
            const formatted = val.toLocaleString(undefined, {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2
            })
            // 优先使用后端提供的 orig_ratio 字段（如 "22.87%"），若不存在则退回计算值
            const ratio =
              params.data && params.data.orig_ratio
                ? params.data.orig_ratio
                : `${Math.round(params.percent || 0)}%`
            return `${formatted}, ${ratio}`
          },
          color: '#fff',
          fontSize: 12
        },
        labelLine: { length: 18, length2: 6 },
        data,
        color: [
          '#5b9bd5',
          '#ed7d31',
          '#a5a5a5',
          '#ffc000',
          '#4472c4',
          '#70ad47',
          '#255e91',
          '#9e480e',
          '#636363',
          '#997300'
        ]
      }
    ]
  }
  domesticInstance.setOption(option)
  window.addEventListener('resize', handleDomesticResize)
}

// 在 domesticData 变化时重绘
watch(
  domesticData,
  () => {
    nextTick(() => initDomesticChart())
  },
  { deep: true }
)

onMounted(() => {
  // 初始绘制
  initDomesticChart()
})

onUnmounted(() => {
  try {
    if (domesticInstance) {
      domesticInstance.dispose()
      domesticInstance = null
    }
  } catch (e) {}
  try {
    window.removeEventListener('resize', handleDomesticResize)
  } catch (e) {}
})

const iraqData = ref<any[]>([
  {
    index: 1,
    dept: '伊拉克 哈法亚连油',
    count: 120,
    orig_value_usd: 694.78,
    net_value_usd: 94.44,
    orig_ratio: '8.02%'
  },
  {
    index: 2,
    dept: '伊拉克 哈法亚压裂',
    count: 132,
    orig_value_usd: 1008.92,
    net_value_usd: 587.07,
    orig_ratio: '11.65%'
  },
  {
    index: 3,
    dept: '伊拉克 B9增产',
    count: 27,
    orig_value_usd: 304.72,
    net_value_usd: 128.62,
    orig_ratio: '3.52%'
  }
])

const iraqTableData = computed(() => {
  const base = iraqData.value.slice()
  base.push({
    index: '',
    dept: '合计',
    count: 279,
    orig_value: Number(279),
    orig_value_usd: Number(2008.41),
    net_value_usd: Number(810.13),
    orig_ratio: ''
  })
  base.push({
    index: '',
    dept: '折算RMB合计',
    count: '',
    orig_value: Number(61574.3),
    orig_value_usd: Number(14279.83),
    net_value_usd: Number(5760.03),
    orig_ratio: '23.19%'
  })
  return base
})

// 折算RMB合计（数值）
const iraqRmbTotal = ref(14279.83)

const libyaData = ref<any[]>([
  {
    index: 1,
    dept: '利比亚 连油8队',
    count: 22,
    orig_value: 2025.52,
    net_value: 1961.69,
    orig_ratio: ''
  }
])

const libyaRmbTotal = ref(2641.07)
const libyaRmbNet = ref(2557.84)

const libyaTableData = computed(() => {
  const base = libyaData.value.slice()
  base.push({
    index: '',
    dept: '折算RMB合计',
    count: '',
    orig_value: Number(libyaRmbTotal.value),
    net_value: Number(libyaRmbNet.value),
    orig_ratio: '4.29%'
  })
  base.push({
    index: '',
    dept: '国内外合计',
    count: 525,
    orig_value: Number(61574.3),
    net_value: Number(18256.63),
    orig_ratio: ''
  })
  return base
})

// 行样式：合计行与折算RMB合计高亮
const tableRowClass = (row: any) => {
  if (!row) return ''
  if (row.dept === '合计') return 'summary-row'
  if (row.dept && typeof row.dept === 'string' && row.dept.indexOf('折算') !== -1) return 'rmb-row'
  return ''
}

/** 初始化 **/
onMounted(async () => {
  loading.value = true
  await Promise.all([getStats()])
  loading.value = false
})
</script>
<style lang="scss" scoped>
@media (width <= 768px) {
  .page-container {
    padding: 10px;
  }
}

@media (width <= 520px) {
  .status-legend-item {
    min-width: 100%;
  }

  .status-legend {
    justify-content: flex-start;
    max-height: none;
    overflow: visible;
  }
}

::v-deep .el-table,
::v-deep .el-table__expanded-cell {
  background-color: transparent !important;
}

/* 表格内背景颜色 */

::v-deep .el-table tr,
::v-deep .el-table td {
  background-color: transparent !important;
}

::v-deep .el-table__footer {
  color: #fff !important;
}

::v-deep .el-table__footer-wrapper .is-leaf {
  color: #fff !important;
}

.summary {
  .el-col {
    margin-bottom: 1rem;
  }
}

.stat-card {
  width: 48%;
}

.page-container {
  min-height: 100vh;
  padding: 20px;
  background-color: #3a6fa3;
}

.summary {
  margin-bottom: 20px;
}

::v-deep .chart-card {
  background-color: rgb(0 0 0 / 30%);
  border: none;
  border-radius: 8px;
  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%);
  }
}

// 安全生产天数卡片样式
.safety-days-card {
  .safety-days-content {
    position: relative;
    display: flex;
    height: 150px;
    flex-direction: column;
    align-items: center;
    justify-content: center;

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

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

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

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

::v-deep .el-card__header {
  padding-bottom: 0;
  border-bottom: none !important;
}

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

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

  &::-webkit-scrollbar-thumb {
    background-color: rgb(255 255 255 / 20%);
    border-radius: 3px;
  }

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

// 修复表格hover样式
::v-deep .el-table__row:hover > td {
  background-color: rgb(255 255 255 / 5%) !important;
}

.custom-scroll-dialog {
  /* 可选：限制对话框整体最大高度（避免超出屏幕） */
  max-height: 90vh;
  overflow: hidden; /* 隐藏整体溢出，避免出现双重滚动条 */
}

/* 滚动内容容器：核心样式 */
.dialog-scroll-content {
  max-height: 60vh; /* 固定最大高度（可根据需求调整，如500px） */
  padding-right: 8px; /* 避免滚动条遮挡内容（可选） */
  overflow-y: auto; /* 垂直方向溢出时显示滚动条 */
}

/* 优化滚动条样式（可选，提升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时滑块颜色 */
}

.custom-table :deep .el-table__row {
  height: 50px !important; /* 高度根据需求调整 */
}

/* 设备状态图例自适应样式 */
.status-legend {
  display: flex;
  width: 100%;
  max-height: 90px; /* 限制高度，超出显示滚动 */
  padding: 6px 0;
  overflow-y: auto;
  box-sizing: border-box;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
}

.status-legend-item {
  display: flex;
  max-width: 100%;
  min-width: 120px;
  padding: 6px 10px;
  box-sizing: border-box;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.status-legend-left {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.status-legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex: 0 0 12px;
}

.status-legend-name {
  max-width: calc(100% - 60px);
  overflow: hidden;
  color: #fff;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.status-legend-right {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.status-legend-value {
  font-weight: 700;
  color: #fff;
}

.status-legend-percent {
  color: #fff;
}

/* 最外层透明 */
</style>
