<template>
  <el-dialog title='填写实验室环境' v-model='dialogVisible' @close='handleClose' v-bind='dialogSmall'>
    <div>
      <el-form ref='dialogFormRef' :model='formContent' :rules='rules'>
        <el-form-item label='温度(℃)' prop='temperature' :label-width='110'>
          <el-input v-model='formContent.temperature' placeholder='请输入温度' maxlength='32' show-word-limit />
        </el-form-item>
        <el-form-item label='相对湿度(%)' prop='humidity' :label-width='110'>
          <el-input v-model='formContent.humidity' placeholder='请输入湿度' maxlength='32' show-word-limit />
        </el-form-item>
        <el-form-item label='正式检测是否续检' :label-width='130'>
          <el-checkbox v-model='resumeFormalChecked' :disabled='resumeFormalDisabled' @change='handleResumeFormalChange' />
        </el-form-item>
        <el-form-item v-if='showTimeCheck' label='守时检测' prop='timeTest' :label-width='130'>
          <div class='time-check-row'>
            <el-checkbox v-model='timeTestChecked' @change='handleTimeTestChange' />
            <div class='resume-time-check'>
              <span class='resume-time-check-label'>守时检测是否续检</span>
              <el-checkbox
                v-model='resumeTimeCheckChecked'
                :disabled='resumeTimeCheckDisabled'
                @change='handleResumeTimeCheckChange'
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
        <span class='dialog-footer'>
          <el-button @click='handleClose'>取消</el-button>
          <el-button type='primary' @click='handleStart'>确定</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang='tsx' name='selectTestItemPopup'>
import { dialogSmall } from '@/utils/elementBind'
import { reactive, Ref, ref } from 'vue'
import type { Device } from '@/api/device/interface/device.ts'
import { ElMessage } from 'element-plus'
import type { FormItemRule } from 'element-plus'
import { useCheckStore } from '@/stores/modules/check'

const emit = defineEmits(['openTestDialog2'])
const dialogFormRef = ref()


const dialogVisible = ref(false)
const formContent = reactive<Device.ResTH>({ temperature: 0, humidity: 0 })
const resumeFormalChecked = ref(false)
const resumeFormalDisabled = ref(true)
const showTimeCheck = ref(false)
const timeTestChecked = ref(false)
const resumeTimeCheckChecked = ref(false)
const resumeTimeCheckDisabled = ref(true)
const submittedClose = ref(false)
const checkStore = useCheckStore()
const open = async () => {
  resetFormContent()
  if (!syncPopupSelectionState()) {
    return
  }
  dialogVisible.value = true
}

// 清空表单内容
const resetFormContent = (resetStore = false) => {
  Object.assign(formContent, { temperature: '22', humidity: '50' })
  resumeFormalChecked.value = false
  resumeFormalDisabled.value = true
  showTimeCheck.value = false
  timeTestChecked.value = false
  resumeTimeCheckChecked.value = false
  resumeTimeCheckDisabled.value = true
  if (resetStore) {
    checkStore.setResumeFormal(false)
    checkStore.setResumeTimeCheck(false)
    checkStore.setSelectTestItems({
      ...checkStore.selectTestItems,
      timeTest: false,
    })
  }
}

const syncResumeTimeCheckSelection = (selected: boolean) => {
  const normalizedSelected = showTimeCheck.value && timeTestChecked.value && !resumeTimeCheckDisabled.value && selected
  resumeTimeCheckChecked.value = normalizedSelected
  checkStore.setResumeTimeCheck(normalizedSelected)
}

const syncTimeTestSelection = (selected: boolean) => {
  const normalizedSelected = showTimeCheck.value && selected
  timeTestChecked.value = normalizedSelected
  checkStore.setSelectTestItems({
    ...checkStore.selectTestItems,
    timeTest: normalizedSelected,
  })
  if (!normalizedSelected) {
    syncResumeTimeCheckSelection(false)
  }
}

const normalizeNumber = (value: unknown) => {
  if (value === null || value === undefined || value === '') {
    return null
  }
  const num = Number(value)
  return Number.isFinite(num) ? num : null
}

const allSelectedDevicesHaveState = (state: number) => {
  return checkStore.devices.length > 0 && checkStore.devices.every(device => normalizeNumber(device.checkState) === state)
}

const hasOnlyKnownFormalStates = () => {
  return checkStore.devices.length > 0 && checkStore.devices.every(device => [0, 1, 2].includes(normalizeNumber(device.checkState) as number))
}

const hasMixedFormalStates = () => {
  const states = checkStore.devices.map(device => normalizeNumber(device.checkState))
  return new Set(states).size > 1
}

const allTimeCheckResultsAreNewRun = () => {
  return checkStore.devices.length > 0 && checkStore.devices.every(device => {
    const result = normalizeNumber(device.timeCheckResult)
    return result !== null && result <= 2
  })
}

const allTimeCheckResultsAreResumable = () => {
  return checkStore.devices.length > 0 && checkStore.devices.every(device => normalizeNumber(device.timeCheckResult) === 3)
}

const syncPopupSelectionState = () => {
  if (!hasOnlyKnownFormalStates() || hasMixedFormalStates()) {
    ElMessage.warning('正式检测，所选设备检测状态不一致，请选择同一状态设备')
    return false
  }

  const planTimeCheckEnabled = normalizeNumber(checkStore.plan.timeCheck) === 1

  if (allSelectedDevicesHaveState(1)) {
    resumeFormalChecked.value = true
    resumeFormalDisabled.value = false
    checkStore.setResumeFormal(true)
  } else {
    resumeFormalChecked.value = false
    resumeFormalDisabled.value = true
    checkStore.setResumeFormal(false)
  }

  showTimeCheck.value = planTimeCheckEnabled
  if (!showTimeCheck.value) {
    syncTimeTestSelection(false)
    syncResumeTimeCheckSelection(false)
    return true
  }

  if (allTimeCheckResultsAreNewRun()) {
    syncTimeTestSelection(false)
    resumeTimeCheckDisabled.value = true
    syncResumeTimeCheckSelection(false)
    return true
  }

  if (allTimeCheckResultsAreResumable()) {
    syncTimeTestSelection(true)
    resumeTimeCheckDisabled.value = false
    syncResumeTimeCheckSelection(true)
    return true
  }

  syncTimeTestSelection(false)
  resumeTimeCheckDisabled.value = true
  syncResumeTimeCheckSelection(false)
  return true
}

const handleTimeTestChange = (value: string | number | boolean) => {
  const selected = Boolean(value)
  if (!selected) {
    syncTimeTestSelection(false)
    resumeTimeCheckDisabled.value = true
    syncResumeTimeCheckSelection(false)
    return
  }

  if (!allTimeCheckResultsAreNewRun() && !allTimeCheckResultsAreResumable()) {
    ElMessage.warning('守时检测中的设备不能与守时结果为符合、不符合、未检的设备混检')
    syncTimeTestSelection(false)
    resumeTimeCheckDisabled.value = true
    syncResumeTimeCheckSelection(false)
    return
  }

  syncTimeTestSelection(true)
  resumeTimeCheckDisabled.value = !allTimeCheckResultsAreResumable()
  if (resumeTimeCheckDisabled.value) {
    syncResumeTimeCheckSelection(false)
  } else {
    syncResumeTimeCheckSelection(true)
  }
}

const handleResumeFormalChange = (value: string | number | boolean) => {
  const selected = !resumeFormalDisabled.value && Boolean(value)
  resumeFormalChecked.value = selected
  checkStore.setResumeFormal(selected)
}

const handleResumeTimeCheckChange = (value: string | number | boolean) => {
  syncResumeTimeCheckSelection(Boolean(value))
}


//定义校验规则
const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
  temperature: [{ required: true, message: '温度必填！', trigger: 'blur' },
    // 指定正则，此处是数字正则
    {
      pattern: /^(?:(?:-50)|-?[1-4][0-9]|-?[0-9]|[1-4][0-9]|50)(\.[0-9]+)?$/,
      message: '温度必须为 -50 到 50 之间的合法数字',
      trigger: 'blur',
    }],
  humidity: [{ required: true, message: '湿度必填！', trigger: 'blur' },
    {
      pattern: /^(?:100(?:\.0+)?|\d{1,2}(?:\.\d+)?|0?\.\d+)$/,
      message: '湿度必须为 0 到 100 之间的合法数字',
      trigger: 'blur',
    },
  ],

})


const handleStart = () => {
  try {
    dialogFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        checkStore.setTemperature(formContent.temperature)
        checkStore.setHumidity(formContent.humidity)
        checkStore.setResumeFormal(!resumeFormalDisabled.value && resumeFormalChecked.value)
        checkStore.setResumeTimeCheck(showTimeCheck.value && !resumeTimeCheckDisabled.value && resumeTimeCheckChecked.value)
        emit('openTestDialog2')
        submittedClose.value = true
        dialogVisible.value = false
      }
    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }

}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  // 清空dialogForm中的值
  resetFormContent(!submittedClose.value)
  submittedClose.value = false
  dialogFormRef.value?.resetFields()
}

defineExpose({ open })

</script>


<style scoped lang='scss'>
.time-check-row {
  display: flex;
  align-items: center;
  gap: 28px;
}

.resume-time-check {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.resume-time-check-label {
  color: var(--el-text-color-regular);
  margin-left: 50%;
}
</style>
