<template>
  <el-row :gutter="20">
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <DeptTree2 :deptId="rootDeptId" @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="项目" prop="contractName">
            <el-input
              v-model="queryParams.contractName"
              placeholder="请输入项目"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="任务" prop="taskName">
            <el-input
              v-model="queryParams.taskName"
              placeholder="请输入任务"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.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"
              :shortcuts="rangeShortcuts"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <el-button
              type="primary"
              plain
              @click="openForm('create')"
              v-hasPermi="['pms:iot-ry-daily-report:create']"
            >
              <Icon icon="ep:plus" class="mr-5px" /> 新增
            </el-button>
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['pms:iot-ry-daily-report:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <ContentWrap class="mb-15px">
        <div class="color-legend">
          <div class="legend-item">
            <span class="color-indicator red"></span>
            <span>当日油耗大于15吨&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;红色预警</span>
          </div>
          <div class="legend-item">
            <span class="color-indicator orange"></span>
            <span
              >进尺工作时间+其它生产时间+非生产时间=24H&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;否则橙色预警</span
            >
          </div>
        </div>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap ref="tableContainerRef">
        <div class="table-container">
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="list"
            :stripe="true"
            :style="{ width: '100%' }"
            max-height="600"
            :cell-style="cellStyle"
            show-overflow-tooltip
            border
          >
            <el-table-column :label="t('iotDevice.serial')" width="56px" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              label="日期"
              align="center"
              prop="createTime"
              :formatter="dateFormatter2"
              :min-width="columnWidths.createTime.width"
              resizable
            />
            <el-table-column
              label="施工队伍"
              align="center"
              prop="deptName"
              :min-width="columnWidths.deptName.width"
              resizable
            />
            <el-table-column
              label="项目"
              align="center"
              prop="contractName"
              :min-width="columnWidths.contractName.width"
              resizable
            />
            <el-table-column
              label="任务"
              align="center"
              prop="taskName"
              :min-width="columnWidths.taskName.width"
              resizable
            />
            <el-table-column
              label="设备型号"
              align="center"
              prop="equipmentType"
              :min-width="columnWidths.equipmentType.width"
              resizable
            />
            <el-table-column
              :label="t('project.status')"
              align="center"
              prop="rigStatus"
              :min-width="columnWidths.rigStatus.width"
              resizable
            >
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.PMS_PROJECT_TASK_RY_SCHEDULE"
                  :value="scope.row.rigStatus"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="上井次完井时间"
              align="center"
              prop="latestWellDoneTime"
              :min-width="columnWidths.latestWellDoneTime.width"
              :formatter="dateFormatter2"
              resizable
            />
            <el-table-column align="center" label="井深(m)">
              <el-table-column
                label="设计"
                align="center"
                prop="designWellDepth"
                :min-width="columnWidths.designWellDepth.width"
                resizable
              />
              <el-table-column
                label="当前"
                align="center"
                prop="currentDepth"
                :min-width="columnWidths.currentDepth.width"
                resizable
              />
            </el-table-column>
            <el-table-column align="center" label="进尺(m)">
              <el-table-column
                label="日"
                align="center"
                prop="dailyFootage"
                :min-width="columnWidths.dailyFootage.width"
                resizable
              />
              <el-table-column
                label="月"
                align="center"
                prop="monthlyFootage"
                :min-width="columnWidths.monthlyFootage.width"
                resizable
              />
              <el-table-column
                label="年累计"
                align="center"
                prop="annualFootage"
                :min-width="columnWidths.annualFootage.width"
                resizable
              />
            </el-table-column>

            <el-table-column
              label="总施工井数"
              align="center"
              prop="totalConstructionWells"
              :min-width="columnWidths.totalConstructionWells.width"
              resizable
            />
            <el-table-column
              label="完工井数"
              align="center"
              prop="completedWells"
              :min-width="columnWidths.completedWells.width"
              resizable
            />
            <el-table-column align="center" label="泥浆性能">
              <el-table-column
                label="密度(g/cm³)"
                align="center"
                prop="mudDensity"
                :min-width="columnWidths.mudDensity.width"
                resizable
              />
              <el-table-column
                label="粘度(S)"
                align="center"
                prop="mudViscosity"
                :min-width="columnWidths.mudViscosity.width"
                resizable
              />
            </el-table-column>
            <el-table-column align="center" label="当日">
              <el-table-column
                label="用电量(kWh)"
                align="center"
                prop="dailyPowerUsage"
                :min-width="columnWidths.dailyPowerUsage.width"
                resizable
              />
              <el-table-column
                label="油耗(吨)"
                align="center"
                prop="dailyFuel"
                :min-width="columnWidths.dailyFuel.width"
                resizable
              >
                <template #default="scope">
                  <span :class="{ 'fuel-warning': shouldShowFuelWarning(scope.row) }">
                    {{ scope.row.dailyFuel }}
                  </span>
                </template>
              </el-table-column>
            </el-table-column>

            <el-table-column
              label="施工开始日期"
              align="center"
              prop="constructionStartDate"
              :formatter="dateFormatter"
              :min-width="columnWidths.constructionStartDate.width"
              resizable
            />
            <el-table-column
              label="施工结束日期"
              align="center"
              prop="constructionEndDate"
              :formatter="dateFormatter"
              :min-width="columnWidths.constructionEndDate.width"
              resizable
            />
            <el-table-column
              label="水平段长度(m)"
              align="center"
              prop="lateralLength"
              :min-width="columnWidths.lateralLength.width"
              resizable
            />
            <el-table-column
              label="井斜(°)"
              align="center"
              prop="wellInclination"
              :min-width="columnWidths.wellInclination.width"
              resizable
            />
            <el-table-column
              label="方位(°)"
              align="center"
              prop="azimuth"
              :min-width="columnWidths.azimuth.width"
              resizable
            />
            <el-table-column
              label="设计井身结构"
              align="center"
              prop="designWellStruct"
              :min-width="columnWidths.designWellStruct.width"
              resizable
            />
            <el-table-column
              label="生产动态"
              align="center"
              prop="productionStatus"
              :width="columnWidths.productionStatus.width"
            />
            <el-table-column
              label="进尺工作时间(H)"
              align="center"
              prop="drillingWorkingTime"
              :min-width="columnWidths.drillingWorkingTime.width"
              resizable
            />
            <el-table-column
              label="其它生产时间(H)"
              align="center"
              prop="otherProductionTime"
              :min-width="columnWidths.otherProductionTime.width"
              resizable
            />
            <el-table-column label="非生产时间" align="center">
              <el-table-column
                label="事故(H)"
                align="center"
                prop="accidentTime"
                :min-width="columnWidths.accidentTime.width"
                resizable
              />
              <el-table-column
                label="修理(H)"
                align="center"
                prop="repairTime"
                :min-width="columnWidths.repairTime.width"
                resizable
              />
              <el-table-column
                label="自停(H)"
                align="center"
                prop="selfStopTime"
                :min-width="columnWidths.selfStopTime.width"
                resizable
              />
              <el-table-column
                label="复杂(H)"
                align="center"
                prop="complexityTime"
                :min-width="columnWidths.complexityTime.width"
                resizable
              />
              <el-table-column
                label="搬迁(H)"
                align="center"
                prop="relocationTime"
                :min-width="columnWidths.relocationTime.width"
                resizable
              />
              <el-table-column
                label="整改(H)"
                align="center"
                prop="rectificationTime"
                :min-width="columnWidths.rectificationTime.width"
                resizable
              />
              <el-table-column
                label="等停(H)"
                align="center"
                prop="waitingStopTime"
                :min-width="columnWidths.waitingStopTime.width"
                resizable
              />
              <el-table-column
                label="冬休(H)"
                align="center"
                prop="winterBreakTime"
                :min-width="columnWidths.winterBreakTime.width"
                resizable
              />
            </el-table-column>
            <el-table-column label="操作" align="center" fixed="right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id, scope.row)"
                  v-hasPermi="['pms:iot-ry-daily-report:update']"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['pms:iot-ry-daily-report:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

      <!-- 表单弹窗：添加/修改 -->
      <IotRyDailyReportForm ref="formRef" @success="getList" :row-data="selectedRowData" />
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { dateFormatter, dateFormatter2, rangeShortcuts } from '@/utils/formatTime'
import download from '@/utils/download'
import { IotRyDailyReportApi, IotRyDailyReportVO } from '@/api/pms/iotrydailyreport'
import IotRyDailyReportForm from './IotRyDailyReportForm.vue'
import { DICT_TYPE } from '@/utils/dict'
import { ref, reactive, onMounted, nextTick, watch, onUnmounted } from 'vue'
import DeptTree2 from '@/views/pms/iotrhdailyreport/DeptTree2.vue'

import dayjs from 'dayjs'
import quarterOfYear from 'dayjs/plugin/quarterOfYear'
import { useDebounceFn } from '@vueuse/core'

dayjs.extend(quarterOfYear)

/** 瑞鹰日报 列表 */
defineOptions({ name: 'IotRyDailyReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 添加 selectedRowData 响应式变量
const selectedRowData = ref<Record<string, any> | null>(null)

const rootDeptId = ref(158)

const loading = ref(true) // 列表的加载中
const list = ref<IotRyDailyReportVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
let queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  contractName: undefined,
  projectId: undefined,
  taskName: undefined,
  taskId: undefined,
  projectClassification: '1',
  relocationDays: undefined,
  latestWellDoneTime: [],
  currentDepth: undefined,
  dailyFootage: undefined,
  monthlyFootage: undefined,
  annualFootage: undefined,
  dailyPowerUsage: undefined,
  monthlyPowerUsage: undefined,
  dailyFuel: undefined,
  monthlyFuel: undefined,
  nonProductionTime: [],
  nptReason: undefined,
  constructionStartDate: [],
  constructionEndDate: [],
  productionStatus: undefined,
  nextPlan: undefined,
  rigStatus: undefined,
  personnel: undefined,
  mudDensity: undefined,
  mudViscosity: undefined,
  lateralLength: undefined,
  wellInclination: undefined,
  azimuth: undefined,
  extProperty: undefined,
  sort: undefined,
  remark: undefined,
  status: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  createTime: [
    ...rangeShortcuts[2].value().map((item) => dayjs(item).format('YYYY-MM-DD HH:mm:ss'))
  ]
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 表格引用
const tableRef = ref()
// 表格容器引用
const tableContainerRef = ref()

const columnWidths = ref<
  Record<
    string,
    { label: string; prop: string; width: string; fn?: (row: IotRyDailyReportVO) => string }
  >
>({
  createTime: {
    label: '日期',
    prop: 'createTime',
    width: '120px',
    fn: (row: IotRyDailyReportVO) => dateFormatter2(null, null, row.createTime)
  },
  deptName: {
    label: '施工队伍',
    prop: 'deptName',
    width: '120px'
  },
  contractName: {
    label: '项目',
    prop: 'contractName',
    width: '120px'
  },
  taskName: {
    label: '任务',
    prop: 'taskName',
    width: '120px'
  },
  equipmentType: {
    label: '设备型号',
    prop: 'equipmentType',
    width: '120px'
  },
  rigStatus: {
    label: '施工状态',
    prop: 'rigStatus',
    width: '120px'
  },
  latestWellDoneTime: {
    label: '上井次完井时间',
    prop: 'latestWellDoneTime',
    width: '120px',
    fn: (row: IotRyDailyReportVO) => dateFormatter2(null, null, row.latestWellDoneTime)
  },
  designWellDepth: {
    label: '设计',
    prop: 'designWellDepth',
    width: '120px'
  },
  currentDepth: {
    label: '当前',
    prop: 'currentDepth',
    width: '120px'
  },
  dailyFootage: {
    label: '日',
    prop: 'dailyFootage',
    width: '120px'
  },
  monthlyFootage: {
    label: '月',
    prop: 'monthlyFootage',
    width: '120px'
  },
  annualFootage: {
    label: '年累计',
    prop: 'annualFootage',
    width: '120px'
  },
  totalConstructionWells: {
    label: '总施工井数',
    prop: 'totalConstructionWells',
    width: '120px'
  },
  completedWells: {
    label: '完工井数',
    prop: 'completedWells',
    width: '120px'
  },
  mudDensity: {
    label: '密度(g/cm³)',
    prop: 'mudDensity',
    width: '120px'
  },
  mudViscosity: {
    label: '粘度(S)',
    prop: 'mudViscosity',
    width: '120px'
  },
  dailyPowerUsage: {
    label: '用电量(kWh)',
    prop: 'dailyPowerUsage',
    width: '120px'
  },
  dailyFuel: {
    label: '油耗(吨)',
    prop: 'dailyFuel',
    width: '120px'
  },
  constructionStartDate: {
    label: '施工开始日期',
    prop: 'constructionStartDate',
    width: '120px',
    fn: (row: IotRyDailyReportVO) => dateFormatter(null, null, row.constructionStartDate)
  },
  constructionEndDate: {
    label: '施工结束日期',
    prop: 'constructionEndDate',
    width: '120px',
    fn: (row: IotRyDailyReportVO) => dateFormatter(null, null, row.constructionEndDate)
  },
  lateralLength: {
    label: '水平段长度(m)',
    prop: 'lateralLength',
    width: '120px'
  },
  wellInclination: {
    label: '井斜(°)',
    prop: 'wellInclination',
    width: '120px'
  },
  azimuth: {
    label: '方位(°)',
    prop: 'azimuth',
    width: '120px'
  },
  designWellStruct: {
    label: '设计井身结构',
    prop: 'designWellStruct',
    width: '120px'
  },
  productionStatus: {
    label: '生产动态',
    prop: 'productionStatus',
    width: '120px'
  },
  drillingWorkingTime: {
    label: '进尺工作时间(H)',
    prop: 'drillingWorkingTime',
    width: '120px'
  },
  otherProductionTime: {
    label: '其它生产时间(H)',
    prop: 'otherProductionTime',
    width: '120px'
  },
  accidentTime: {
    label: '事故(H)',
    prop: 'accidentTime',
    width: '120px'
  },
  repairTime: {
    label: '修理(H)',
    prop: 'repairTime',
    width: '120px'
  },
  selfStopTime: {
    label: '修理(H)',
    prop: 'selfStopTime',
    width: '120px'
  },
  complexityTime: {
    label: '复杂(H)',
    prop: 'selfStopTime',
    width: '120px'
  },
  relocationTime: {
    label: '搬迁(H)',
    prop: 'relocationTime',
    width: '120px'
  },
  rectificationTime: {
    label: '整改(H)',
    prop: 'rectificationTime',
    width: '120px'
  },
  waitingStopTime: {
    label: '等停(H)',
    prop: 'waitingStopTime',
    width: '120px'
  },
  winterBreakTime: {
    label: '冬休(H)',
    prop: 'winterBreakTime',
    width: '120px'
  }
})

// 计算文本宽度
const getTextWidth = (text: string, fontSize = 12) => {
  const span = document.createElement('span')
  span.style.visibility = 'hidden'
  span.style.position = 'absolute'
  span.style.whiteSpace = 'nowrap'
  span.style.fontSize = `${fontSize}px`
  span.style.fontFamily = 'PingFang SC'
  span.innerText = text

  document.body.appendChild(span)
  const width = span.offsetWidth
  document.body.removeChild(span)

  return width
}

const calculateColumnWidths = useDebounceFn(() => {
  if (!tableContainerRef.value?.$el) return
  Object.values(columnWidths.value).forEach(({ fn, prop, label, width }) => {
    width =
      Math.min(
        ...[
          Math.max(
            ...[
              getTextWidth(label),
              ...list.value.map((v) => {
                return getTextWidth(fn ? fn(v) : v[prop])
              })
            ]
          ) + (label === '施工状态' ? 30 : 20),
          200
        ]
      ) + 'px'

    columnWidths.value[prop].width = width
  })
}, 1000)

// 检查10个时间字段之和是否为24H
const checkTimeSumEquals24 = (row: any) => {
  // 获取三个字段的值，转换为数字，如果为空则视为0
  const drillingWorkingTime = parseFloat(row.drillingWorkingTime) || 0
  const otherProductionTime = parseFloat(row.otherProductionTime) || 0
  const accidentTime = parseFloat(row.accidentTime) || 0
  const repairTime = parseFloat(row.repairTime) || 0
  const selfStopTime = parseFloat(row.selfStopTime) || 0
  const complexityTime = parseFloat(row.complexityTime) || 0
  const relocationTime = parseFloat(row.relocationTime) || 0
  const rectificationTime = parseFloat(row.rectificationTime) || 0
  const waitingStopTime = parseFloat(row.waitingStopTime) || 0
  const winterBreakTime = parseFloat(row.winterBreakTime) || 0

  // 计算总和
  const sum =
    drillingWorkingTime +
    otherProductionTime +
    accidentTime +
    repairTime +
    selfStopTime +
    complexityTime +
    relocationTime +
    rectificationTime +
    waitingStopTime +
    winterBreakTime

  // 返回是否等于24（允许一定的浮点数误差）
  return Math.abs(sum - 24) < 0.01 // 使用0.01作为误差范围
}

// 单元格样式函数
const cellStyle = ({
  row,
  column,
  rowIndex,
  columnIndex
}: {
  row: any
  column: any
  rowIndex: number
  columnIndex: number
}) => {
  // 处理当日油耗预警
  if (column.property === 'dailyFuel') {
    if (shouldShowFuelWarning(row)) {
      return {
        color: 'red',
        fontWeight: 'bold',
        backgroundColor: '#fff5f5' // 可选：添加背景色突出显示
      }
    }
  }

  // 处理三个时间字段：当日注气时间、当日注水时间、非生产时间
  const timeFields = [
    'drillingWorkingTime',
    'otherProductionTime',
    'accidentTime',
    'repairTime',
    'selfStopTime',
    'complexityTime',
    'relocationTime',
    'rectificationTime',
    'waitingStopTime',
    'winterBreakTime'
  ]
  if (timeFields.includes(column.property)) {
    // 检查10个时间字段之和是否不等于24
    if (!checkTimeSumEquals24(row)) {
      return {
        color: 'orange',
        fontWeight: 'bold'
      }
    }
  }
  // 默认返回空对象，不应用特殊样式
  return {}
}

// 可伸缩列配置

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await IotRyDailyReportApi.getIotRyDailyReportPage(queryParams)
    list.value = data.list
    total.value = data.total
    // 获取数据后计算列宽
    nextTick(() => {
      calculateColumnWidths()
    })
  } finally {
    loading.value = false
  }
}

// 在 cellStyle 函数附近添加油耗预警判断函数
const shouldShowFuelWarning = (row: any): boolean => {
  const dailyFuel = parseFloat(row.dailyFuel)
  return !isNaN(dailyFuel) && dailyFuel > 15
}

// 计算列宽度

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, row?: any) => {
  // 保存当前行数据
  if (row) {
    selectedRowData.value = {
      deptName: row.deptName,
      contractName: row.contractName,
      taskName: row.taskName,
      designWellDepth: row.designWellDepth,
      designWellStruct: row.designWellStruct,
      totalConstructionWells: row.totalConstructionWells,
      completedWells: row.completedWells
    }
  } else {
    selectedRowData.value = null
  }

  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await IotRyDailyReportApi.deleteIotRyDailyReport(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 响应式变量存储选中的部门
const selectedDept = ref<{ id: number; name: string }>()
/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  // 记录选中的部门信息
  selectedDept.value = { id: row.id, name: row.name }
  queryParams.deptId = row.id
  await getList()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotRyDailyReportApi.exportIotRyDailyReport(queryParams)
    download.excel(data, '瑞鹰日报.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// 声明 ResizeObserver 实例
let resizeObserver: ResizeObserver | null = null

const route = useRoute()

/** 初始化 **/
onMounted(() => {
  if (Object.keys(route.query).length > 0) {
    queryParams = {
      ...queryParams,
      ...route.query,
      deptId: Number(route.query.deptId) as any
    }
    handleQuery()
  } else getList()
  // 创建 ResizeObserver 监听表格容器尺寸变化
  if (tableContainerRef.value?.$el) {
    resizeObserver = new ResizeObserver(() => {
      // 使用防抖避免频繁触发
      clearTimeout((window as any).resizeTimer)
      ;(window as any).resizeTimer = setTimeout(() => {
        calculateColumnWidths()
      }, 100)
    })
    resizeObserver.observe(tableContainerRef.value.$el)
  }
})

onUnmounted(() => {
  // 清除 ResizeObserver
  if (resizeObserver && tableContainerRef.value?.$el) {
    resizeObserver.unobserve(tableContainerRef.value.$el)
    resizeObserver = null
  }

  // 清除定时器
  if ((window as any).resizeTimer) {
    clearTimeout((window as any).resizeTimer)
  }
})

// 监听列表数据变化重新计算列宽
watch(
  list,
  () => {
    nextTick(calculateColumnWidths)
  },
  { deep: true }
)
</script>

<style scoped>
/* 表格容器样式，确保水平滚动 */
.table-container {
  width: 100%;
  overflow-x: auto;
}

/* 确保表格单元格内容不换行 */

/* :deep(.el-table .cell) {
  white-space: nowrap;
} */

/* 确保表格列标题不换行 */

/* :deep(.el-table th > .cell) {
  white-space: nowrap;
} */

/* 调整表格最小宽度，确保内容完全显示 */
:deep(.el-table) {
  min-width: 100%;
}

/* 强制显示所有内容，防止省略号 */

/* :deep(.el-table td.el-table__cell),
:deep(.el-table th.el-table__cell) {
  overflow: visible !important;
} */

/* :deep(.el-table .cell) {
  overflow: visible !important;
  text-overflow: clip !important;
} */

/* 设计井身结构文本样式 - 多行显示并添加省略号 */
.design-well-struct-text {
  display: -webkit-box;
  max-height: 3em; /* 两行文本的高度 */
  overflow: hidden;
  line-height: 1.5;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}

/* 确保设计井身结构列不参与自动调整 */
:deep(.el-table__header-wrapper .el-table__cell.fixed-width),
:deep(.el-table__body-wrapper .el-table__cell.fixed-width) {
  flex-shrink: 0;
  flex-grow: 0;
}

/* 颜色说明区域样式 */
.color-legend {
  display: flex;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-left: 4px solid #e6f7ff;
  border-radius: 4px;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.color-indicator {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.color-indicator.red {
  background-color: red;
}

.color-indicator.orange {
  background-color: orange;
}
</style>

<style>
/* 设计井身结构 tooltip 样式 - 保留换行符 */
.design-well-struct-tooltip {
  max-width: 500px;
  line-height: 1.5;
  white-space: pre-line;
}
.color-indicator.red {
  background-color: red;
}

/* 当日油耗预警样式 */
.fuel-warning {
  color: red !important;
  font-weight: bold;
  animation: pulse 1.5s infinite;
}

/* 确保表格中的预警样式不被覆盖 */
:deep(.el-table .cell .fuel-warning) {
  color: red !important;
  font-weight: bold !important;
}
</style>
