<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'
import { TableColumnCtx } from 'element-plus'

const { t } = useI18n()

interface ListItem {
  id: number
  deptId: number
  projectId: number
  taskId: number
  createTime: number
  deptName: string
  contractName: string
  taskName: string
  repairStatus: string
  totalConstructionWells: number
  completedWells: number
  technique: string
  wellCategory: string
  designWellDepth: number
  casingPipeSize: string
  wellControlLevel: string
  dailyPowerUsage: number
  dailyFuel: number
  constructionStartDate: number
  constructionEndDate: number
  currentOperation: string
  nextPlan: string
  transitTime: number
  ratedProductionTime: number
  productionTime: 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
  ryNptReason: string
  productionStatus: string
  totalStaffNum: number
  onDutyStaffNum: number
  leaveStaffNum: number
  status: number
  auditStatus: number
  opinion: string
  offDutyStaffNum: number
  remark: string
  nonProductionRate: number
  daySupervisors: string
  nightSupervisors: 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 transitTime = (row: ListItem) => {
  const { ratedProductionTime = 0, productionTime = 0 } = row

  return (
    (ratedProductionTime === 0 ? 0 : (productionTime / ratedProductionTime) * 100).toFixed(2) + '%'
  )
}

const nptFields = [
  'accidentTime',
  'repairTime',
  'selfStopTime',
  'complexityTime',
  'relocationTime',
  'rectificationTime',
  'waitingStopTime',
  'winterBreakTime',
  'partyaDesign',
  'partyaPrepare',
  'partyaResource',
  'otherNptTime'
]

function checkTimeSumEquals24(row: ListItem) {
  const ratedProductionTime = parseFloat(row.ratedProductionTime + '') || 0
  const productionTime = parseFloat(row.productionTime + '') || 0

  const totalNonProductionTime = nptFields.reduce((sum, field) => {
    const val = parseFloat(row[field])
    return sum + (isNaN(val) ? 0 : val)
  }, 0)

  const currentSum = productionTime + totalNonProductionTime

  return Math.abs(currentSum - ratedProductionTime) < 0.01
}

function cellStyle(data: {
  row: ListItem
  column: TableColumnCtx<ListItem>
  rowIndex: number
  columnIndex: number
}) {
  const { row, column } = data

  if (column.property === 'transitTime') {
    const originalValue = Number(row.transitTime ?? 0)

    if (originalValue >= 1)
      return {
        color: 'red',
        fontWeight: 'bold',
        backgroundColor: 'var(--el-color-danger-light-9)'
      }
  }

  if (column.property === 'dailyFuel') {
    const originalValue = row.dailyFuel ?? 0

    if (originalValue > 3500)
      return {
        color: 'blue',
        fontWeight: 'bold',
        backgroundColor: 'var(--el-color-primary-light-9)'
      }
  }

  const timeFields = ['ratedProductionTime', 'productionTime', ...nptFields]
  if (timeFields.includes(column.property)) {
    if (!checkTimeSumEquals24(row)) {
      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="repairStatus"
              fixed="left"
              :label="t('project.status')"
              :real-value="
                (row: ListItem) =>
                  realValue(DICT_TYPE.PMS_PROJECT_TASK_RY_REPAIR_SCHEDULE, row.repairStatus ?? '')
              "
            >
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.PMS_PROJECT_TASK_RY_REPAIR_SCHEDULE"
                  :value="scope.row.repairStatus ?? ''"
                />
              </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="t('project.currentOperation')" prop="currentOperation" />
            <zm-table-column :label="t('project.nextPlan')" prop="nextPlan" />
            <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">工况：</div>
                          <span
                            class="font-medium break-all whitespace-pre-wrap 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
              :label="t('project.transitTime')"
              prop="transitTime"
              cover-formatter
              :real-value="transitTime"
            />
            <zm-table-column label="额定生产时间(H)" prop="ratedProductionTime" />
            <zm-table-column label="生产时间(H)" prop="productionTime" />
            <zm-table-column
              prop="nonProductionRate"
              label="非生产时效"
              cover-formatter
              :real-value="(row) => (Number(row.nonProductionRate ?? 0) * 100).toFixed(2) + '%'"
            />
            <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="其他非生产时间原因" />

            <zm-table-column label="施工区域" prop="location" />
            <zm-table-column label="总施工井数" prop="totalConstructionWells" />
            <zm-table-column label="完工井数" prop="completedWells" />
            <zm-table-column
              prop="technique"
              :label="t('project.technology')"
              :real-value="
                (row: ListItem) =>
                  realValue(DICT_TYPE.PMS_PROJECT_RY_TECHNOLOGY, row.technique ?? '')
              "
            >
              <template #default="scope">
                <dict-tag
                  :type="DICT_TYPE.PMS_PROJECT_RY_TECHNOLOGY"
                  :value="scope.row.technique ?? ''"
                />
              </template>
            </zm-table-column>
            <zm-table-column label="井别" prop="wellCategory" />
            <zm-table-column label="井深(m)" prop="designWellDepth" />
            <zm-table-column label="套生段产管尺寸(mm)" prop="casingPipeSize" />
            <zm-table-column label="井控级别" prop="wellControlLevel" />
            <zm-table-column label="当日">
              <zm-table-column label="用电量(kWh)" prop="dailyPowerUsage" />
              <zm-table-column label="油耗(升)" prop="dailyFuel" />
            </zm-table-column>
            <!-- <zm-table-column label="施工开始日期" prop="constructionStartDate" />
            <zm-table-column label="施工结束日期" prop="constructionEndDate" /> -->

            <zm-table-column prop="contractName" label="项目" />
            <zm-table-column label="跟班干部">
              <zm-table-column prop="daySupervisors" label="白班" />
              <zm-table-column prop="nightSupervisors" label="夜班" />
            </zm-table-column>

            <zm-table-column prop="totalStaffNum" label="全员数量" />
            <zm-table-column
              prop="onDutyStaffNum"
              label="在岗人数"
              cover-formatter
              :real-value="
                (row: ListItem) =>
                  (Number(row.totalStaffNum) || 0) - (Number(row.offDutyStaffNum) || 0)
              "
            />
            <zm-table-column prop="leaveStaffNum" 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>
