<script setup lang="ts">
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { DICT_TYPE, realValue } from '@/utils/dict'
import { formatT } from '@/utils/formatTime'
import dayjs from 'dayjs'

const { t } = useI18n()

interface ListItem {
  createTime: number
  deptName: string
  taskName: string
  rigStatus: string
  equipmentType: string
  latestWellDoneTime: number
  designWellDepth: number
  currentDepth: number
  dailyFootage: number
  monthlyFootage: number
  annualFootage: number
  totalConstructionWells: number
  completedWells: number
  mudDensity: number
  mudViscosity: number
  dailyPowerUsage: number
  dailyFuel: number
  lateralLength: number
  wellInclination: number
  azimuth: number
  designWellStruct: string
  productionStatus: string
  contractName: string
  drillingWorkingTime: number
  otherProductionTime: number
  nonProductionRate: number
  accidentTime: number
  repairTime: number
  selfStopTime: number
  complexityTime: number
  relocationTime: number
  rectificationTime: number
  waitingStopTime: number
  winterBreakTime: number
  partyaDesign: number
  partyaPrepare: number
  partyaResource: number
  otherNptTime: number
  otherNptReason: string
}

const props = defineProps({
  list: {
    type: Array as PropType<ListItem[]>,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  },
  total: {
    type: Number,
    default: 0
  },
  pageNo: {
    type: Number,
    default: 0
  },
  pageSize: {
    type: Number,
    default: 0
  },
  showAction: {
    type: Boolean,
    default: true
  },
  isIndex: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:pageNo', 'update:pageSize', 'sizeChange', 'currentChange'])

const { list, loading, total, pageNo, pageSize, showAction, isIndex } = toRefs(props)

const { ZmTable, ZmTableColumn } = useTableComponents<ListItem>()

const getReportDetailsDuration = (reportDetails: any[] = []) =>
  Number(reportDetails.reduce((sum, item) => sum + Number(item.duration || 0), 0).toFixed(2))

const formatReportDetailTime = (time?: number[] | string) =>
  Array.isArray(time) ? formatT(time) : time || ''

const getReportDetailsTimeRange = (row: any) => {
  const reportDetails = row.reportDetails || []
  const first = reportDetails[0]
  const last = reportDetails.at(-1)
  if (!first || !last) return ''

  const startDate = first.reportDate ?? row.createTime
  const endDate = last.endDateTime ?? last.reportDate ?? row.createTime
  const startTime = formatReportDetailTime(first.startTime)
  const endTime = formatReportDetailTime(last.endTime)

  return `${dayjs(startDate).format('YYYY-MM-DD')} ${startTime} - ${dayjs(endDate).format(
    'YYYY-MM-DD'
  )} ${endTime}`
}

const cellStyle = ({ row, column }: { row: ListItem; column: any }) => {
  // 1. 红色预警：当日油耗大于 9000 升
  if (column.property === 'dailyFuel') {
    const dailyFuel = Number(row.dailyFuel || 0)
    if (dailyFuel > 9000) {
      return {
        color: 'red',
        fontWeight: 'bold',
        backgroundColor: 'var(--el-color-danger-light-9)'
      }
    }
  }

  // 2. 橙色预警：进尺工作时间 + 其它生产时间 + 非生产时间 != 24H
  // 定义所有非生产时间(NPT)的字段名
  const nptFields = [
    'accidentTime',
    'repairTime',
    'selfStopTime',
    'complexityTime',
    // 'relocationTime',
    'rectificationTime',
    'waitingStopTime',
    'winterBreakTime',
    'partyaDesign',
    'partyaPrepare',
    'partyaResource',
    'otherNptTime'
  ]
  // 定义所有需要进行时间校验高亮的列（进尺 + 其它 + NPT明细）
  const timeCheckCols = ['drillingWorkingTime', 'otherProductionTime', ...nptFields]

  if (timeCheckCols.includes(column.property)) {
    const drilling = Number(row.drillingWorkingTime || 0)
    const other = Number(row.otherProductionTime || 0)
    // 计算非生产时间总和
    const nptTotal = nptFields.reduce((sum, field) => {
      return sum + Number(row[field as keyof ListItem] || 0)
    }, 0)

    const totalTime = drilling + other + nptTotal

    // 如果总时长不等于 24 (使用 0.01 误差范围处理浮点数计算)
    if (Math.abs(totalTime - 24) > 0.01) {
      return {
        color: 'orange',
        fontWeight: 'bold',
        backgroundColor: 'var(--el-color-warning-light-9)'
      }
    }
  }

  return {}
}

function handleSizeChange(val: number) {
  emits('sizeChange', val)
}

function handleCurrentChange(val: number) {
  emits('currentChange', val)
}
</script>

<template>
  <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4">
    <div class="flex-1 relative">
      <el-auto-resizer class="absolute">
        <template #default="{ width, height }">
          <zm-table
            :data="list"
            :loading="loading"
            :width="width"
            :max-height="height"
            :height="height"
            show-border
            :cell-style="cellStyle"
          >
            <zm-table-column
              type="index"
              :label="t('monitor.serial')"
              :width="60"
              fixed="left"
              v-if="isIndex"
            />
            <zm-table-column
              label="日期"
              prop="createTime"
              fixed="left"
              cover-formatter
              :real-value="(row: ListItem) => dayjs(row.createTime).format('YYYY-MM-DD')"
            />
            <zm-table-column label="施工队伍" prop="deptName" fixed="left" />
            <zm-table-column label="任务" prop="taskName" fixed="left" />
            <zm-table-column
              prop="rigStatus"
              fixed="left"
              :label="t('project.status')"
              :real-value="
                (row: ListItem) =>
                  realValue(DICT_TYPE.PMS_PROJECT_TASK_RY_SCHEDULE, row.rigStatus ?? '')
              "
            >
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.PMS_PROJECT_TASK_RY_SCHEDULE"
                  :value="scope.row.rigStatus ?? ''"
                />
              </template>
            </zm-table-column>
            <zm-table-column prop="auditStatus" label="审批状态" v-if="!isIndex">
              <template #default="scope">
                <el-tag v-if="scope.row.auditStatus === 0" type="info">
                  {{ '待提交' }}
                </el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 10">
                  {{ '待审批' }}
                </el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 20" type="success">
                  {{ '审批通过' }}
                </el-tag>
                <el-tag v-else-if="scope.row.auditStatus === 30" type="danger">
                  {{ '审批拒绝' }}
                </el-tag>
              </template>
            </zm-table-column>
            <zm-table-column label="井深(m)">
              <zm-table-column label="设计" prop="designWellDepth" />
              <zm-table-column label="当前" prop="currentDepth" />
            </zm-table-column>
            <zm-table-column label="进尺(m)">
              <zm-table-column label="日" prop="dailyFootage" />
              <zm-table-column label="月" prop="monthlyFootage" />
              <zm-table-column label="年" prop="annualFootage" />
            </zm-table-column>
            <zm-table-column
              prop="reportDetails"
              label="生产动态"
              width="320"
              :show-overflow-tooltip="false"
            >
              <template #default="{ row }">
                <div v-if="row.reportDetails && row.reportDetails.length > 0" class="py-2">
                  <el-popover placement="right" trigger="hover" width="320" popper-class="!p-0">
                    <template #reference>
                      <el-badge
                        :value="row.reportDetails.length"
                        type="primary"
                        class="max-w-full translate-y-0.5"
                      >
                        <div
                          class="w-72 flex flex-col bg-gray-200/80 hover:bg-blue-100 transition-colors relative group cursor-pointer px-2 py-0.5 rounded gap-y-2"
                        >
                          <div class="flex items-center gap-x-2">
                            <div class="flex items-center">
                              <div class="i-carbon-calendar mr-1 -translate-y-[0.5px]"></div>
                              <div class="font-medium mr-2">
                                {{ getReportDetailsTimeRange(row) }}
                              </div>
                            </div>

                            <div class="ml-auto group-hover:text-blue-600 font-medium">
                              {{ getReportDetailsDuration(row.reportDetails) }} H
                            </div>
                          </div>

                          <!-- <div class="flex items-center">
                            <div class="font-medium flex-shrink-0">结束井深(m)：</div>
                            <span
                              class="font-medium truncate group-hover:text-blue-600 transition-colors"
                              >{{ row.reportDetails[0].currentDepth || '-' }} m
                            </span>
                          </div>

                          <div class="flex items-center">
                            <div class="font-medium flex-shrink-0">工况：</div>
                            <el-tooltip
                              effect="dark"
                              :content="row.reportDetails[0].currentOperation"
                              placement="top"
                              popper-class="max-w-100"
                            >
                              <span
                                class="font-medium truncate group-hover:text-blue-600 transition-colors"
                              >
                                {{ row.reportDetails[0].currentOperation || '-' }}
                              </span>
                            </el-tooltip>
                          </div>

                          <div class="flex items-center">
                            <div class="font-medium flex-shrink-0">详细描述：</div>
                            <el-tooltip
                              effect="dark"
                              :content="row.reportDetails[0].constructionDetail"
                              placement="top"
                              popper-class="max-w-100"
                            >
                              <span
                                class="font-medium truncate group-hover:text-blue-600 transition-colors"
                              >
                                {{ row.reportDetails[0].constructionDetail || '-' }}
                              </span>
                            </el-tooltip>
                          </div> -->
                        </div>
                      </el-badge>
                    </template>
                    <el-scrollbar max-height="480px" view-class="!p-3 flex flex-col gap-y-2">
                      <div
                        v-for="(item, index) in row.reportDetails"
                        :key="index"
                        class="flex flex-col bg-gray-200/80 hover:bg-blue-100 transition-colors relative group cursor-pointer p-2 rounded gap-y-2"
                      >
                        <div class="flex items-center gap-x-2">
                          <div class="flex items-center">
                            <div class="i-carbon-calendar mr-1 -translate-y-[0.5px]"></div>
                            <div class="font-medium mr-2">{{
                              dayjs(item.reportDate).format('YYYY-MM-DD')
                            }}</div>
                            <div class="flex items-center">
                              <span>{{ formatT(item.startTime) }}</span>
                              <span class="mx-1">-</span>
                              <span>{{ formatT(item.endTime) }}</span>
                            </div>
                          </div>

                          <div class="ml-auto group-hover:text-blue-600 font-medium">
                            {{ item.duration }} H
                          </div>
                        </div>

                        <div class="flex items-center">
                          <div class="font-medium flex-shrink-0">结束井深(m)：</div>
                          <span
                            class="font-medium truncate group-hover:text-blue-600 transition-colors"
                            >{{ item.currentDepth || '-' }} m
                          </span>
                        </div>

                        <div class="flex items-center">
                          <div class="font-medium flex-shrink-0">工况：</div>
                          <span class="font-medium group-hover:text-blue-600 transition-colors">
                            {{ item.currentOperation || '-' }}
                          </span>
                        </div>

                        <div class="flex items-center">
                          <div class="font-medium flex-shrink-0">详细描述：</div>
                          <span
                            class="font-medium break-all whitespace-pre-wrap group-hover:text-blue-600 transition-colors"
                          >
                            {{ item.constructionDetail || '-' }}
                          </span>
                        </div>
                      </div>
                    </el-scrollbar>
                  </el-popover>
                </div>
                <span v-else class="text-gray-300">-</span>
              </template>
            </zm-table-column>
            <zm-table-column prop="constructionBrief" label="当日施工简报" />
            <zm-table-column prop="nextPlan" label="下步计划" />
            <zm-table-column prop="drillingWorkingTime" label="进尺工作时间(H)" />
            <zm-table-column prop="otherProductionTime" label="其它生产时间(H)" />
            <zm-table-column
              prop="nonProductionRate"
              label="非生产时效"
              cover-formatter
              :real-value="(row) => (Number(row.nonProductionRate ?? 0) * 100).toFixed(2) + '%'"
            />
            <zm-table-column label="设备型号" prop="equipmentType" />
            <zm-table-column
              label="上井次完井时间"
              prop="latestWellDoneTime"
              cover-formatter
              :real-value="
                (row: ListItem) =>
                  row.latestWellDoneTime ? dayjs(row.latestWellDoneTime).format('YYYY-MM-DD') : ''
              "
            />
            <zm-table-column label="施工区域" prop="location" />
            <zm-table-column label="总施工井数" prop="totalConstructionWells" />
            <zm-table-column label="完工井数" prop="completedWells" />
            <zm-table-column label="泥浆性能">
              <zm-table-column label="密度(g/cm³)" prop="mudDensity" />
              <zm-table-column label="粘度(S)" prop="mudViscosity" />
            </zm-table-column>
            <zm-table-column label="当日">
              <zm-table-column label="用电量(kWh)" prop="dailyPowerUsage" />
              <zm-table-column label="油耗(升)" prop="dailyFuel" />
            </zm-table-column>
            <zm-table-column label="水平段长度(m)" prop="lateralLength" />
            <zm-table-column label="井斜(°)" prop="wellInclination" />
            <zm-table-column label="方位(°)" prop="azimuth" />
            <zm-table-column label="设计井身结构" prop="designWellStruct" />

            <zm-table-column prop="contractName" label="项目" />

            <zm-table-column label="非生产时间">
              <zm-table-column prop="accidentTime" label="工程质量" />
              <zm-table-column prop="repairTime" label="设备故障" />
              <zm-table-column prop="selfStopTime" label="设备保养" />
              <zm-table-column prop="complexityTime" label="技术受限" />
              <zm-table-column prop="relocationTime" label="生产配合" />
              <zm-table-column prop="rectificationTime" label="生产组织" />
              <zm-table-column prop="waitingStopTime" label="不可抗力" />
              <zm-table-column prop="winterBreakTime" label="待命" />
              <zm-table-column prop="partyaDesign" label="甲方设计" />
              <zm-table-column prop="partyaPrepare" label="甲方准备" />
              <zm-table-column prop="partyaResource" label="甲方资源" />
              <zm-table-column prop="otherNptTime" label="其它非生产时间" />
            </zm-table-column>
            <zm-table-column
              prop="otherNptReason"
              label="其他非生产时间原因"
              :action="!showAction"
            />

            <zm-table-column label="操作" :width="120" fixed="right" action v-if="showAction">
              <template #default="scope">
                <slot name="action" :row="scope.row"></slot>
              </template>
            </zm-table-column>
          </zm-table>
        </template>
      </el-auto-resizer>
    </div>
    <div class="h-8 mt-2 flex items-center justify-end">
      <el-pagination
        size="default"
        v-show="total > 0"
        :current-page="pageNo"
        :page-size="pageSize"
        :background="true"
        :page-sizes="[10, 20, 30, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped></style>
