<script lang="ts" setup generic="T">
import { IotRyDailyReportApi } from '@/api/pms/iotrydailyreport'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { FormInstance, FormRules } from 'element-plus'
import { computed, reactive, ref, watch, nextTick } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { calculateDuration, formatT } from '@/utils/formatTime'
import { useDebounceFn } from '@vueuse/core'

interface Props {
  visible: boolean
  type?: 'edit' | 'approval' | 'readonly'
  loadList: () => void
  noValidateStatus?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  type: 'edit',
  noValidateStatus: false
})

const emits = defineEmits(['update:visible'])

// 1. 定义具体的 11 个非生产时间字段
const NON_PROD_FIELDS = [
  { key: 'repairTime', label: '设备故障' },
  { key: 'selfStopTime', label: '设备保养' },
  { key: 'accidentTime', label: '工程质量' },
  { key: 'complexityTime', label: '技术受限' },
  { key: 'rectificationTime', label: '生产组织' },
  { key: 'waitingStopTime', label: '不可抗力' },
  { key: 'partyaDesign', label: '甲方设计' },
  { key: 'partyaPrepare', label: '甲方准备' },
  { key: 'partyaResource', label: '甲方资源' },
  { key: 'relocationTime', label: '生产配合' },
  { key: 'winterBreakTime', label: '待命' },
  { key: 'otherNptTime', label: '其他非生产时间' }
] as const

interface ReportDetail {
  reportDate: number
  startTime: string
  endTime: string
  duration: number
  currentDepth: number
  currentOperation: string
  constructionDetail: string
}

interface FormOriginal {
  id: number
  deptId: number
  projectId: number
  taskId: number
  deptName: string
  contractName: string
  taskName: string
  rigStatus: string
  designWellDepth: string
  currentDepth: number
  dailyPowerUsage: number
  dailyFuel: number
  mudDensity: number
  mudViscosity: number
  lateralLength: number
  wellInclination: number
  azimuth: number
  designWellStruct: string
  personnel: string
  drillingWorkingTime: number
  otherProductionTime: number
  lastCurrentDepth: number

  // 11个非生产时间字段
  repairTime: number
  selfStopTime: number
  accidentTime: number
  complexityTime: number
  rectificationTime: number
  waitingStopTime: number
  partyaDesign: number
  partyaPrepare: number
  partyaResource: number
  relocationTime: number
  winterBreakTime: number
  otherNptTime: number

  // 其他非生产时间原因（仅作为备注字段存在）
  otherNptReason: string
  constructionBrief: string

  reportDetails: ReportDetail[]
  remark: string
  createTime: number
  opinion: string

  auditStatus: number

  nextPlan: string
  location: string
}

type Form = Partial<FormOriginal>

// 字段白名单
const FORM_KEYS: (keyof FormOriginal)[] = [
  'id',
  'deptId',
  'projectId',
  'taskId',
  'deptName',
  'contractName',
  'taskName',
  'rigStatus',
  'designWellDepth',
  'currentDepth',
  'dailyPowerUsage',
  'dailyFuel',
  'mudDensity',
  'mudViscosity',
  'lateralLength',
  'wellInclination',
  'azimuth',
  'designWellStruct',
  'personnel',
  'drillingWorkingTime',
  'otherProductionTime',
  'lastCurrentDepth',
  'constructionBrief',
  'remark',
  'createTime',
  'reportDetails',
  'opinion',
  'repairTime',
  'selfStopTime',
  'accidentTime',
  'complexityTime',
  'rectificationTime',
  'waitingStopTime',
  'partyaDesign',
  'partyaPrepare',
  'partyaResource',
  'relocationTime',
  'winterBreakTime',
  'otherNptTime',
  'otherNptReason',
  'auditStatus',
  'nextPlan',
  'location'
]

const formRef = ref<FormInstance>()
const loading = ref(false)
const formLoading = ref(false)
const formType = ref<'edit' | 'readonly'>('edit')
const message = useMessage()
const { t } = useI18n()

// 初始化表单
const initFormData = (): Form => {
  const base: any = {
    drillingWorkingTime: 0,
    otherProductionTime: 0
  }
  // 初始化所有非生产时间字段为 0
  NON_PROD_FIELDS.forEach((field) => {
    base[field.key] = 0
  })
  return base as Form
}

const form = ref<Form>(initFormData())

const isApproval = computed(() => props.type === 'approval')
const isEdit = computed(() => props.type === 'edit')
const isMainFieldDisabled = computed(() => formType.value === 'readonly' || isApproval.value)
const isConstructionBriefDisabled = computed(() => formType.value === 'readonly')

const wellOptions = ref<{ label: string; value: number }[]>([])

async function loadDetail(id: number) {
  loading.value = true
  try {
    const res = await IotRyDailyReportApi.getIotRyDailyReport(id)

    wellOptions.value = Object.entries(res.wellNamePair).map(([value, label]) => ({
      label: String(label),
      value: Number(value)
    }))

    form.value = initFormData()
    // 按需赋值
    FORM_KEYS.forEach((key) => {
      if (
        Object.prototype.hasOwnProperty.call(res, key) &&
        res[key] !== null &&
        res[key] !== undefined
      ) {
        // @ts-ignore
        form.value[key] = res[key]
      }
    })

    form.value.reportDetails = (res.reportDetails ? (res.reportDetails as any[]) : []).map(
      (item) => ({
        reportDate: item.reportDate ?? res.createTime,
        startTime: formatT(item.startTime),
        endTime: formatT(item.endTime),
        duration: item.duration,
        currentDepth: item.currentDepth,
        currentOperation: item.currentOperation,
        constructionDetail: item.constructionDetail
      })
    )

    if (!form.value.reportDetails.length) {
      addProductionStatusRow()
    }

    if (props.type === 'edit') {
      form.value.currentDepth = form.value.reportDetails.at(-1)?.currentDepth
    }

    if (props.type === 'edit' && !props.noValidateStatus && res.status !== 0)
      formType.value = 'readonly'
    if (props.type === 'approval' && !props.noValidateStatus && res.auditStatus !== 10)
      formType.value = 'readonly'
  } finally {
    loading.value = false
  }
}

const addProductionStatusRow = () => {
  if (!form.value.reportDetails) {
    form.value.reportDetails = []
  }
  form.value.reportDetails.push({
    reportDate: form.value.createTime ?? dayjs().valueOf(),
    startTime: '',
    endTime: '',
    duration: 0,
    currentDepth: 0,
    currentOperation: '',
    constructionDetail: ''
  })
}

const removeProductionStatusRow = (index: number) => {
  if (index === 0) {
    message.warning('至少填写一条生产动态')
    return
  }
  form.value.reportDetails?.splice(index, 1)
}

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

function handleOpenForm(id: number, type: 'edit' | 'readonly') {
  formType.value = type
  form.value.reportDetails = []
  emits('update:visible', true)
  loadDetail(id).then(() => {
    nextTick(() => formRef.value?.clearValidate())
  })
}

defineExpose({ handleOpenForm })

// --- 运行时效 ---
// const transitTime = computed(() => {
//   const cap = form.value.capacity
//   const gas = form.value.dailyGasInjection ?? 0
//   if (!cap) return { original: 0, value: '0%' }
//   const original = gas / cap
//   return { original, value: (original * 100).toFixed(2) + '%' }
// })

// --- 核心校验逻辑 ---

// 计算所有非生产时间总和
const sumNonProdTimes = () => {
  let sum = 0
  NON_PROD_FIELDS.forEach((field) => {
    sum += (form.value[field.key as keyof FormOriginal] as number) || 0
  })

  return sum
}

// 24小时平衡校验器
const validateTotalTime =
  (isNon: boolean = false) =>
  (_rule: any, _value: any, callback: any) => {
    const drillingTime = form.value.drillingWorkingTime || 0
    const otherTime = form.value.otherProductionTime || 0

    const nonProdSum = sumNonProdTimes()

    let total = 0
    let msg = ''

    total = parseFloat((drillingTime + otherTime + nonProdSum).toFixed(2))
    msg = `进尺(${drillingTime})+其他(${otherTime})+非生产(${nonProdSum})=${total}H，必须为24H`

    if (Math.abs(total - 24) > 0.01) {
      if (!isNon) callback(new Error(msg))
      else callback(new Error())
    } else {
      callback()
    }
  }

const validateOtherReason = (_rule: any, value: any, callback: any) => {
  const time = form.value.otherNptTime || 0
  if (time > 0 && !value) {
    callback(new Error('填写了其他时间，必须说明原因'))
  } else {
    callback()
  }
}

const validateLastCurrentDepth = (_rule: any, value: any, callback: any) => {
  if (value && value < (form.value.lastCurrentDepth ?? 0)) {
    callback(new Error(`当前深度需大于等于上一次填报深度 ${form.value.lastCurrentDepth}`))
  } else {
    callback()
  }
}

// 动态构建校验规则
const rules = reactive<FormRules>({
  currentDepth: [
    { required: true, message: '请输入当前深度', trigger: ['change', 'blur'] },
    { validator: validateLastCurrentDepth, trigger: ['change', 'blur'] }
  ],
  // productionStatus: [{ required: true, message: '请输入生产动态', trigger: ['blur', 'change'] }],
  reportDetails: [{ required: true, message: '请填写生产动态', type: 'array' }],
  constructionBrief: [
    {
      required: !isMainFieldDisabled.value,
      message: '请填写施工简报',
      type: 'string',
      trigger: ['blur', 'change']
    }
  ],

  // 生产时间绑定校验
  drillingWorkingTime: [
    { required: true, message: '请输入进尺工作时间', trigger: ['blur', 'change'] },
    { validator: validateTotalTime(), trigger: ['blur', 'change'] }
  ],
  otherProductionTime: [{ validator: validateTotalTime(), trigger: ['blur', 'change'] }],
  otherNptReason: [{ validator: validateOtherReason, trigger: ['blur', 'change'] }]
})

// 关键步骤：为每一个非生产时间字段都绑定 validateTotalTime 规则
// 这样当总和不对时，所有时间字段下面都会出现红色错误提示
NON_PROD_FIELDS.forEach((field) => {
  rules[field.key] = [{ validator: validateTotalTime(true), trigger: ['blur', 'change'] }]
})

// 监听所有时间字段
const allTimeKeys = [
  'drillingWorkingTime',
  'otherProductionTime',
  ...NON_PROD_FIELDS.map((f) => f.key)
]

// 当任一时间变化时，触发所有时间字段的校验更新
watch(
  () => allTimeKeys.map((key) => form.value[key as keyof FormOriginal]),
  () => {
    if (!isMainFieldDisabled.value) {
      nextTick(() => {
        // 传入数组，同时校验所有字段
        formRef.value?.validateField(allTimeKeys)
      })
    }
  },
  { deep: true }
)

// --- 提交 ---
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    formLoading.value = true
    const submitData: any = {}
    FORM_KEYS.forEach((key) => (submitData[key] = form.value[key]))
    submitData.fillOrderCreateTime = form.value.createTime
    submitData.projectClassification = '1'
    if (props.type === 'edit' && props.noValidateStatus) {
      submitData.editFlag = 'Y'
    }

    await IotRyDailyReportApi.createIotRyDailyReport(submitData)
    message.success(t('common.updateSuccess'))
    emits('update:visible', false)
    props.loadList()
  } catch (error) {
    console.warn('校验失败')
  } finally {
    formLoading.value = false
  }
}

const handleAudit = async (auditStatus: 20 | 30) => {
  if (!formRef.value) return
  try {
    formLoading.value = true

    await formRef.value.validateField('constructionBrief')

    await IotRyDailyReportApi.approvalIotRyDailyReport({
      id: form.value.id!,
      auditStatus,
      opinion: form.value.opinion!,
      constructionBrief: form.value.constructionBrief
    })
    message.success(auditStatus === 20 ? '通过成功' : '拒绝成功')
    emits('update:visible', false)
    props.loadList()
  } catch (error) {
    console.warn(error)
  } finally {
    formLoading.value = false
  }
}

const orange = computed(() => {
  const drillingTime = form.value.drillingWorkingTime || 0
  const otherTime = form.value.otherProductionTime || 0

  const nonProdSum = sumNonProdTimes()

  let total = 0

  total = parseFloat((drillingTime + otherTime + nonProdSum).toFixed(2))

  if (Math.abs(total - 24) > 0.01) return true
  return false
})

const acalculateDuration = (row: any) => {
  calculateDuration(row)
  inputCurrentDepth()
}

const inputCurrentDepth = useDebounceFn(function inputCurrentDepth() {
  const details = form.value.reportDetails

  if (Array.isArray(details) && details.length > 0) {
    const latestDetail = details.reduce((prev, current) => {
      const currentFullTime = dayjs(current.reportDate)
        .hour(parseInt(current.endTime.split(':')[0]))
        .minute(parseInt(current.endTime.split(':')[1]))
        .valueOf()

      const prevFullTime = dayjs(prev.reportDate)
        .hour(parseInt(prev.endTime.split(':')[0]))
        .minute(parseInt(prev.endTime.split(':')[1]))
        .valueOf()

      return currentFullTime >= prevFullTime ? current : prev
    })

    form.value.currentDepth = latestDetail.currentDepth
  }
}, 300)
</script>

<template>
  <el-drawer
    :model-value="visible"
    @update:model-value="emits('update:visible', $event)"
    header-class="mb-0!"
    size="100%"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <template #header>
      <span class="text-xl font-bold text-[var(--el-text-color-primary)]">
        {{ type === 'edit' ? '编辑日报' : '审批日报' }}
      </span>
    </template>

    <el-form
      ref="formRef"
      label-position="top"
      size="default"
      :rules="rules"
      :model="form"
      v-loading="loading"
      require-asterisk-position="right"
      :disabled="formType === 'readonly' && type !== 'approval'">
      <!-- 顶部提示区 -->
      <div class="flex flex-col gap-3 text-sm mb-4">
        <div
          class="rounded-md border border-blue-100 bg-blue-50/80 p-3 dark:border-blue-900/30 dark:bg-blue-900/10">
          <div class="flex flex-col gap-2.5">
            <div class="flex items-center justify-between">
              <div class="text-gray-600 dark:text-gray-400">
                <span class="font-bold text-gray-800 dark:text-gray-200"> 油量消耗：</span>
                当日油耗
              </div>
              <span
                class="inline-flex items-center rounded border border-red-200 bg-red-100 px-2 py-0.5 text-xs font-medium text-red-600 dark:bg-red-900/20 dark:border-red-800 dark:text-red-400">
                >9000升 红色预警
              </span>
            </div>
            <div class="flex items-center justify-between">
              <div class="text-gray-600 dark:text-gray-400">
                <span class="font-bold text-gray-800 dark:text-gray-200">时间平衡：</span>
                进尺 + 其它生产 + 非生产 = 24H
              </div>
              <span
                class="inline-flex items-center rounded border border-orange-200 bg-orange-100 px-2 py-0.5 text-xs font-medium text-orange-600 dark:bg-orange-900/20 dark:border-orange-800 dark:text-orange-400">
                ≠24H 橙色预警
              </span>
            </div>
          </div>
        </div>
        <div
          v-if="isEdit && form.opinion"
          class="flex gap-3 rounded-md border border-yellow-200 bg-yellow-50 p-3 dark:border-yellow-800 dark:bg-yellow-900/10">
          <Icon
            icon="ep:warning-filled"
            class="mt-0.5 shrink-0 text-base text-yellow-600 dark:text-yellow-500" />
          <div class="flex flex-col">
            <h4 class="mb-1 font-bold text-yellow-800 dark:text-yellow-500">审核意见</h4>
            <p class="leading-relaxed text-gray-600 dark:text-gray-400">{{ form.opinion }}</p>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-2 gap-4">
        <!-- 基础信息 -->
        <div class="col-span-2 flex items-center gap-2 mt-2">
          <div class="bg-[var(--el-color-primary)] w-1 h-5 rounded-full"></div>
          <div class="text-lg font-medium text-[var(--el-text-color-primary)]">基础信息</div>
        </div>
        <el-form-item label="施工队伍" prop="deptName"
          ><el-input v-model="form.deptName" disabled
        /></el-form-item>
        <el-form-item label="项目" prop="contractName"
          ><el-input v-model="form.contractName" disabled
        /></el-form-item>
        <el-form-item label="任务井" prop="taskId">
          <el-select
            v-model="form.taskId"
            placeholder="请选择任务井"
            :options="wellOptions"
            :disabled="form.auditStatus !== 20 && form.auditStatus !== 30" />
        </el-form-item>
        <el-form-item label="施工区域" prop="location">
          <el-input v-model="form.location" disabled />
        </el-form-item>
        <el-form-item label="施工状态" prop="rigStatus">
          <el-select
            v-model="form.rigStatus"
            placeholder="请选择施工状态"
            :disabled="isMainFieldDisabled">
            <el-option
              v-for="(dict, index) in getStrDictOptions(DICT_TYPE.PMS_PROJECT_TASK_RY_SCHEDULE)"
              :key="index"
              :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设计井深(m)" prop="designWellDepth">
          <el-input v-model="form.designWellDepth" placeholder="" disabled />
        </el-form-item>
        <el-form-item label="当前井深(m)" prop="currentDepth">
          <el-input-number
            :min="0"
            v-model="form.currentDepth"
            placeholder="请输入当前井深(m)"
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="当日用电量(kWh)" prop="dailyPowerUsage">
          <el-input-number
            :min="0"
            v-model="form.dailyPowerUsage"
            placeholder="请输入当日用电量(kWh)"
            clearable
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="当日油耗(升)" prop="dailyFuel">
          <el-input-number
            :min="0"
            v-model="form.dailyFuel"
            placeholder="请输入当日油耗(升)"
            clearable
            :class="{ 'warning-input': (form.dailyFuel ?? 0) > 9000 }"
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="泥浆密度(g/cm³)" prop="mudDensity">
          <el-input-number
            :min="0"
            v-model="form.mudDensity"
            placeholder="请输入泥浆性能-密度(g/cm³)"
            clearable
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="泥浆粘度(S)" prop="mudViscosity">
          <el-input-number
            :min="0"
            v-model="form.mudViscosity"
            placeholder="请输入泥浆性能-粘度(S)"
            clearable
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="水平段长度(m)" prop="lateralLength">
          <el-input-number
            :min="0"
            v-model="form.lateralLength"
            placeholder="请输入水平段长度(m)"
            clearable
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="井斜(°)" prop="wellInclination">
          <el-input-number
            :min="0"
            v-model="form.wellInclination"
            placeholder="请输入井斜(°)"
            clearable
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="方位(°)" prop="azimuth">
          <el-input-number
            :min="0"
            v-model="form.azimuth"
            placeholder="请输入方位(°)"
            clearable
            :disabled="isMainFieldDisabled"
            :controls="false"
            align="left"
            class="w-full!" />
        </el-form-item>
        <el-form-item label="设计井身结构" prop="designWellStruct">
          <el-input
            v-model="form.designWellStruct"
            placeholder=""
            type="textarea"
            disabled
            autosize />
        </el-form-item>
        <el-form-item label="人员情况" prop="personnel">
          <el-input
            v-model="form.personnel"
            placeholder="请输入人员情况"
            type="textarea"
            :max-length="1000"
            autosize
            :disabled="isMainFieldDisabled" />
        </el-form-item>
        <el-form-item class="col-span-2" label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            autosize
            maxlength="1000"
            :disabled="isMainFieldDisabled" />
        </el-form-item>

        <div class="col-span-2">
          <div class="flex items-center justify-between mb-6">
            <div class="flex items-center gap-2">
              <div class="bg-[var(--el-color-primary)] w-1 h-5 rounded-full"></div>
              <div class="text-lg font-medium text-[var(--el-text-color-primary)]">生产动态</div>
            </div>
            <el-button
              type="primary"
              link
              :icon="Plus"
              @click="addProductionStatusRow"
              :disabled="isMainFieldDisabled">
              添加一行
            </el-button>
          </div>
          <el-form-item prop="reportDetails">
            <ZmTable :data="form.reportDetails!" :loading="false" class="mb-4">
              <ZmTableColumn label="日期" :width="180" prop="reportDate">
                <template #default="{ row, $index }">
                  <el-form-item
                    v-if="$index >= 0"
                    class="mb-0!"
                    :prop="`reportDetails.${$index}.reportDate`"
                    :rules="{
                      required: true,
                      message: '请选择日期',
                      trigger: ['change', 'blur'],
                      type: 'number'
                    }">
                    <el-date-picker
                      v-model="row.reportDate"
                      placeholder="选择日期"
                      clearable
                      class="w-full!"
                      value-format="x"
                      :disabled="isMainFieldDisabled"
                      @change="inputCurrentDepth()" />
                  </el-form-item>
                </template>
              </ZmTableColumn>

              <ZmTableColumn :width="130" label="开始时间" prop="startTime">
                <template #default="{ row, $index }">
                  <el-form-item
                    v-if="$index >= 0"
                    class="mb-0!"
                    :prop="`reportDetails.${$index}.startTime`"
                    :rules="{
                      required: true,
                      message: '请选择开始时间',
                      trigger: ['change', 'blur']
                    }">
                    <el-time-picker
                      v-model="row.startTime"
                      placeholder="选择开始时间"
                      clearable
                      format="HH:mm"
                      value-format="HH:mm"
                      class="w-full!"
                      @change="acalculateDuration(row)"
                      :disabled="isMainFieldDisabled" />
                  </el-form-item>
                </template>
              </ZmTableColumn>
              <ZmTableColumn :width="130" label="结束时间" prop="endTime">
                <template #default="{ row, $index }">
                  <el-form-item
                    v-if="$index >= 0"
                    class="mb-0!"
                    :prop="`reportDetails.${$index}.endTime`"
                    :rules="{
                      required: true,
                      message: '请选择结束时间',
                      trigger: ['change', 'blur']
                    }">
                    <el-time-picker
                      v-model="row.endTime"
                      placeholder="选择结束时间"
                      clearable
                      format="HH:mm"
                      value-format="HH:mm"
                      class="w-full!"
                      @change="acalculateDuration(row)"
                      :disabled="isMainFieldDisabled" />
                  </el-form-item>
                </template>
              </ZmTableColumn>
              <ZmTableColumn :width="80" label="时长(H)" prop="duration" />

              <ZmTableColumn label="工况" :width="200">
                <template #default="{ row, $index }">
                  <el-form-item
                    v-if="$index >= 0"
                    :prop="`reportDetails.${$index}.currentOperation`"
                    :rules="{ required: true, message: '请输入工况', trigger: ['change', 'blur'] }"
                    class="mb-0!">
                    <el-input
                      v-model="row.currentOperation"
                      type="textarea"
                      :autosize="{ minRows: 1 }"
                      show-word-limit
                      :maxlength="1000"
                      placeholder="请输入工况"
                      :disabled="isMainFieldDisabled" />
                  </el-form-item>
                </template>
              </ZmTableColumn>

              <ZmTableColumn label="结束井深(m)" :width="200">
                <template #default="{ row, $index }">
                  <el-form-item
                    v-if="$index >= 0"
                    :prop="`reportDetails.${$index}.currentDepth`"
                    :rules="[
                      {
                        required: true,
                        message: '请输入结束井深',
                        trigger: ['blur']
                      },
                      { validator: validateLastCurrentDepth, trigger: ['change', 'blur'] }
                    ]"
                    class="mb-0!">
                    <el-input-number
                      v-model="row.currentDepth"
                      :min="0"
                      :controls="false"
                      class="!w-full"
                      align="left"
                      placeholder="请输入结束井深"
                      :disabled="isMainFieldDisabled"
                      @input="() => inputCurrentDepth()">
                      <template #suffix> m </template>
                    </el-input-number>
                  </el-form-item>
                </template>
              </ZmTableColumn>

              <ZmTableColumn label="详细描述" min-width="200" align="center">
                <template #default="{ row, $index }">
                  <el-form-item
                    v-if="$index >= 0"
                    :prop="`reportDetails.${$index}.constructionDetail`"
                    :rules="{ required: true, message: '请输入详细描述', trigger: 'blur' }"
                    class="mb-0!">
                    <el-input
                      v-model="row.constructionDetail"
                      type="textarea"
                      :autosize="{ minRows: 1 }"
                      show-word-limit
                      :maxlength="1000"
                      placeholder="请输入详细描述"
                      :disabled="isMainFieldDisabled" />
                  </el-form-item>
                </template>
              </ZmTableColumn>

              <ZmTableColumn label="操作" width="80" fixed="right" align="center">
                <template #default="{ $index }">
                  <el-button
                    link
                    type="danger"
                    :icon="Delete"
                    @click="removeProductionStatusRow($index)"
                    :disabled="isMainFieldDisabled">
                    删除
                  </el-button>
                </template>
              </ZmTableColumn>
            </ZmTable>
          </el-form-item>
        </div>

        <el-form-item class="col-span-2" label="当日施工简报" prop="constructionBrief">
          <el-input
            v-model="form.constructionBrief"
            type="textarea"
            :autosize="{ minRows: 2 }"
            show-word-limit
            resize="none"
            :maxlength="1000"
            placeholder="请输入当日施工简报"
            :disabled="isConstructionBriefDisabled" />
        </el-form-item>

        <el-form-item class="col-span-2" label="下步计划" prop="nextPlan">
          <el-input
            v-model="form.nextPlan"
            type="textarea"
            :autosize="{ minRows: 2 }"
            show-word-limit
            resize="none"
            :maxlength="1000"
            placeholder="请输入下步计划"
            :disabled="isMainFieldDisabled" />
        </el-form-item>

        <!-- 时间信息 -->
        <div class="col-span-2 flex items-center gap-2 mt-4">
          <div class="bg-[var(--el-color-primary)] w-1 h-5 rounded-full"></div>
          <div class="text-lg font-medium text-[var(--el-text-color-primary)]"
            >生产与非生产时间</div
          >
        </div>

        <el-form-item label="进尺工作时间(H)" prop="drillingWorkingTime">
          <el-input-number
            class="!w-full"
            :min="0"
            :max="24"
            v-model="form.drillingWorkingTime"
            :controls="false"
            align="left"
            placeholder="进尺+其他+非生产=24H"
            :disabled="isMainFieldDisabled"
            :class="{ 'orange-input': orange }" />
        </el-form-item>
        <el-form-item label="其它生产时间(H)" prop="otherProductionTime">
          <el-input-number
            class="!w-full"
            :min="0"
            :max="24"
            v-model="form.otherProductionTime"
            :controls="false"
            align="left"
            placeholder="请输入其它生产时间(H)"
            :disabled="isMainFieldDisabled"
            :class="{ 'orange-input': orange }" />
        </el-form-item>

        <!-- 循环渲染11个具体非生产时间 -->
        <el-form-item
          v-for="field in NON_PROD_FIELDS"
          :key="field.key"
          :label="field.label + '(H)'"
          :prop="field.key">
          <el-input-number
            class="!w-full"
            :min="0"
            :max="24"
            v-model="form[field.key as keyof FormOriginal]"
            :controls="false"
            align="left"
            :disabled="isMainFieldDisabled"
            :class="{ 'orange-input': orange }" />
        </el-form-item>

        <!-- 其他非生产原因 -->
        <el-form-item class="col-span-2" label="其他非生产原因" prop="otherNptReason">
          <el-input
            v-model="form.otherNptReason"
            placeholder="请输入其他非生产原因"
            :disabled="isMainFieldDisabled" />
        </el-form-item>

        <!-- 审批意见 -->
        <div v-if="isApproval" class="col-span-2 mt-4 border-t pt-4">
          <el-form-item label="审批意见" prop="opinion">
            <el-input
              v-model="form.opinion"
              placeholder="请输入审批意见"
              maxlength="1000"
              type="textarea"
              :autosize="{ minRows: 3 }"
              :disabled="formType === 'readonly'" />
          </el-form-item>
        </div>
      </div>
    </el-form>

    <template #footer>
      <div v-if="isEdit">
        <el-button
          size="default"
          type="primary"
          @click="submitForm"
          :loading="formLoading"
          :disabled="formType === 'readonly'"
          >确 定
        </el-button>
        <el-button size="default" @click="emits('update:visible', false)">取 消</el-button>
      </div>
      <div v-if="isApproval">
        <el-button
          size="default"
          type="primary"
          @click="handleAudit(20)"
          :loading="formLoading"
          :disabled="formType === 'readonly'"
          >审批通过
        </el-button>
        <el-button
          size="default"
          type="danger"
          @click="handleAudit(30)"
          :loading="formLoading"
          :disabled="formType === 'readonly'"
          >审批拒绝
        </el-button>
        <el-button size="default" @click="emits('update:visible', false)">取 消</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped>
:deep(.warning-input) {
  .el-input__inner {
    color: red !important;
    -webkit-text-fill-color: red !important;
  }
}

:deep(.blue-input) {
  .el-input__inner {
    color: blue !important;
    -webkit-text-fill-color: blue !important;
  }
}

:deep(.orange-input) {
  .el-input__inner {
    color: orange !important;
    -webkit-text-fill-color: orange !important;
  }
}
</style>
