<script lang="ts" setup generic="T">
import { IotRhDailyReportApi } from '@/api/pms/iotrhdailyreport'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { FormInstance, FormRules } from 'element-plus'
import { computed, reactive, ref, watch, nextTick } from 'vue'

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 FormOriginal {
  id: number
  deptId: number
  projectId: number
  taskId: number
  deptName: string
  contractName: string
  taskName: string
  dailyGasInjection: number
  dailyWaterInjection: number
  dailyInjectGasTime: number
  dailyInjectWaterTime: number
  constructionStatus: string

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

  productionStatus: string
  remark: string
  relocationDays: number
  capacity: number
  createTime: number
  opinion: string
  location: string
}

type Form = Partial<FormOriginal>

// 字段白名单
const FORM_KEYS: (keyof FormOriginal)[] = [
  'id',
  'deptId',
  'projectId',
  'taskId',
  'deptName',
  'contractName',
  'taskName',
  'dailyGasInjection',
  'dailyWaterInjection',
  'dailyInjectGasTime',
  'dailyInjectWaterTime',
  'constructionStatus',
  'productionStatus',
  'remark',
  'relocationDays',
  'capacity',
  'createTime',
  'opinion',
  'repairTime',
  'selfStopTime',
  'accidentTime',
  'complexityTime',
  'rectificationTime',
  'waitingStopTime',
  'partyaDesign',
  'partyaPrepare',
  'partyaResource',
  'relocationTime',
  'winterBreakTime',
  'otherNptTime',
  'otherNptReason',
  '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 = {
    dailyGasInjection: 0,
    dailyWaterInjection: 0,
    dailyInjectGasTime: 0,
    dailyInjectWaterTime: 0,
    relocationDays: 0,
    capacity: 0,
    otherNptReason: '',
    opinion: ''
  }
  // 初始化所有非生产时间字段为 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)

async function loadDetail(id: number) {
  loading.value = true
  try {
    const res = await IotRhDailyReportApi.getIotRhDailyReport(id)
    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]
      }
    })

    if (props.type === 'edit' && !props.noValidateStatus && res.status !== 0)
      formType.value = 'readonly'
    if (props.type === 'approval' && !props.noValidateStatus && res.auditStatus !== 10)
      formType.value = 'readonly'
    if (!form.value.capacity) message.error('请维护增压机产能')
  } finally {
    loading.value = false
  }
}

function handleOpenForm(id: number, type: 'edit' | 'readonly') {
  formType.value = type
  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 field = rule.field

    const gasTime = form.value.dailyInjectGasTime || 0
    const waterTime = form.value.dailyInjectWaterTime || 0
    const nonProdSum = sumNonProdTimes()

    let total = 0
    let msg = ''

    if (gasTime === 0 && waterTime > 0) {
      total = parseFloat((waterTime + nonProdSum).toFixed(2))
      msg = `注水(${waterTime})+非生产(${nonProdSum})=${total}H，必须为24H`
    } else {
      total = parseFloat((gasTime + nonProdSum).toFixed(2))
      msg = `注气(${gasTime})+非生产(${nonProdSum})=${total}H，必须为24H`
    }

    if (Math.abs(total - 24) > 0.01) {
      if (!isNon) {
        if (field === 'dailyInjectWaterTime' && waterTime === 0) {
          callback()
        } else if (field === 'dailyInjectGasTime' && gasTime === 0 && waterTime !== 0) {
          callback()
        } else 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 rules = reactive<FormRules>({
  dailyGasInjection: [{ required: true, message: '请输入当日注气量', trigger: ['blur', 'change'] }],
  dailyWaterInjection: [
    { required: true, message: '请输入当日注水量', trigger: ['blur', 'change'] }
  ],
  constructionStatus: [{ required: true, message: '请输入施工状态', trigger: ['blur', 'change'] }],
  productionStatus: [{ required: true, message: '请输入生产动态', trigger: ['blur', 'change'] }],

  // 生产时间绑定校验
  dailyInjectGasTime: [
    { required: true, message: '请输入当日注气时间', trigger: ['blur', 'change'] },
    { validator: validateTotalTime(), trigger: ['blur', 'change'] }
  ],
  dailyInjectWaterTime: [{ 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 = [
  'dailyInjectGasTime',
  'dailyInjectWaterTime',
  ...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

    await IotRhDailyReportApi.createIotRhDailyReport(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 IotRhDailyReportApi.approvalIotRhDailyReport({
      id: form.value.id!,
      auditStatus,
      opinion: form.value.opinion!
    })
    message.success(auditStatus === 20 ? '通过成功' : '拒绝成功')
    emits('update:visible', false)
    props.loadList()
  } catch (error) {
    console.warn(error)
  } finally {
    formLoading.value = false
  }
}
</script>

<template>
  <el-drawer
    :model-value="visible"
    @update:model-value="emits('update:visible', $event)"
    header-class="mb-0!"
    size="50%"
  >
    <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"
              >
                >120% 红色预警
              </span>
            </div>
            <!-- 可以显示一个总计提示，辅助用户 -->
            <!-- <div class="text-gray-600 dark:text-gray-400">
              <span class="font-bold text-gray-800 dark:text-gray-200">时间校验：</span>
              (注气 > 0 ? 注气 : 注水) + 所有非生产时间 = 24H
            </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="taskName">
          <el-input v-model="form.taskName" disabled />
        </el-form-item>
        <el-form-item label="搬迁安装天数(D)" prop="relocationDays"
          ><el-input v-model="form.relocationDays" disabled
        /></el-form-item>
        <el-form-item label="运行时效" prop="transitTime">
          <el-input
            :model-value="transitTime.value"
            disabled
            :class="{ 'warning-input': transitTime.original > 1.2 }"
          />
        </el-form-item>
        <el-form-item label="施工状态" prop="constructionStatus">
          <el-select
            v-model="form.constructionStatus"
            placeholder="请选择施工状态"
            :disabled="isMainFieldDisabled"
            clearable
          >
            <el-option
              v-for="(dict, index) in getStrDictOptions(DICT_TYPE.PMS_PROJECT_TASK_SCHEDULE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="当日注气量(方)" prop="dailyGasInjection">
          <el-input-number
            class="!w-full"
            :min="0"
            v-model="form.dailyGasInjection"
            :controls="false"
            align="left"
            :disabled="isMainFieldDisabled"
          />
        </el-form-item>
        <el-form-item label="当日注水量(方)" prop="dailyWaterInjection">
          <el-input-number
            class="!w-full"
            :min="0"
            v-model="form.dailyWaterInjection"
            :controls="false"
            align="left"
            :disabled="isMainFieldDisabled"
          />
        </el-form-item>
        <el-form-item class="col-span-2" label="施工区域" prop="location">
          <el-input v-model="form.location" disabled />
        </el-form-item>
        <el-form-item class="col-span-2" label="生产动态" prop="productionStatus">
          <el-input
            v-model="form.productionStatus"
            type="textarea"
            autosize
            maxlength="1000"
            :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 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="dailyInjectGasTime">
          <el-input-number
            class="!w-full"
            :min="0"
            :max="24"
            v-model="form.dailyInjectGasTime"
            :controls="false"
            align="left"
            placeholder="注气+非生产=24H"
            :disabled="isMainFieldDisabled"
          />
        </el-form-item>
        <el-form-item label="当日注水时间(H)" prop="dailyInjectWaterTime">
          <el-input-number
            class="!w-full"
            :min="0"
            :max="24"
            v-model="form.dailyInjectWaterTime"
            :controls="false"
            align="left"
            placeholder="注气=0时，注水+非生产=24H"
            :disabled="isMainFieldDisabled"
          />
        </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"
          />
        </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>
