<template>
  <el-dialog title="选择测试内容" v-model='dialogVisible' @close="handleClose" v-bind="dialogSmall" >
    <div>
      <el-form ref="dialogFormRef" :model="formContent" class="form-three select-test-form">
        <el-form-item prop="preTest">
          <div class="test-item-checkbox">
            <span>预检测</span>
            <el-checkbox v-model="formContent.preTest" @change="handleSelectTestItemChange"/>
          </div>
        </el-form-item>
        <el-form-item v-if="checkStore.plan.timeCheck===1" prop="timeTest">
          <div class="test-item-row">
            <div class="test-item-checkbox">
              <span>守时检测</span>
              <el-checkbox v-model="formContent.timeTest" @change="handleTimeTestChange"/>
            </div>
            <div v-if="formContent.timeTest" class="resume-checkbox">
              <span>守时检测是否续检</span>
              <el-checkbox
                  v-model="resumeTimeCheckChecked"
                  :disabled="resumeTimeCheckDisabled"
                  @change="handleResumeTimeCheckChange"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item  v-if="channelsTestShow" prop="channelsTest">
          <div class="test-item-checkbox">
            <span>系数校准</span>
            <el-checkbox v-model="formContent.channelsTest" @change="handleSelectTestItemChange"/>
          </div>
        </el-form-item>
        <el-form-item prop="test">
          <div class="test-item-row">
            <div class="test-item-checkbox">
              <span>正式检测</span>
              <el-checkbox v-model="formContent.test" @change="handleFormalTestChange"/>
            </div>
            <div v-if="formContent.test" class="resume-checkbox">
              <span>正式检测是否续检</span>
              <el-checkbox
                  v-model="resumeFormalChecked"
                  :disabled="resumeFormalDisabled"
                  @change="handleResumeFormalChange"
              />
            </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} from "vue";
import {useCheckStore} from "@/stores/modules/check";
import type {CheckData} from "@/api/check/interface";
import {ElMessage, ElMessageBox} from "element-plus";
import {useAppSceneStore,useModeStore} from "@/stores/modules/mode";


const AppSceneStore = useAppSceneStore()
const emit = defineEmits(['openTestDialog'])
const checkStore = useCheckStore();
const modeStore = useModeStore()
const dialogFormRef = ref()
const channelsTestShow = ref(false)

const dialogVisible = ref(false)
const formContent = reactive<CheckData.SelectTestItem>({preTest: true, timeTest: false, channelsTest: false, test: false})
const resumeFormalChecked = ref(false)
const resumeFormalDisabled = ref(true)
const resumeTimeCheckChecked = ref(false)
const resumeTimeCheckDisabled = ref(true)
const submittedClose = ref(false)
const open = async () => {

  resetFormContent()
  syncSelectTestItems()
  checkStore.setResumeFormal(resumeFormalChecked.value)
  checkStore.setResumeTimeCheck(false)
  dialogVisible.value = true
  if(modeStore.currentMode === '比对式'){
    channelsTestShow.value = false
  }else{
    if(AppSceneStore.currentScene === '1'){
      channelsTestShow.value = true
    }else{
      channelsTestShow.value = false
    }
  }
}

// 清空表单内容
const resetFormContent = () => {
  let hasResult = checkStore.devices.some((device) => device.checkResult === 0)
  Object.assign(formContent, {preTest: !hasResult, channelsTest: false, timeTest: false, test: hasResult})
  resumeFormalChecked.value = formContent.test && allSelectedDevicesHaveFormalState(1)
  resumeFormalDisabled.value = !allSelectedDevicesHaveFormalState(1)
  resumeTimeCheckChecked.value = false
  resumeTimeCheckDisabled.value = true
}

const syncSelectTestItems = () => {
  checkStore.setSelectTestItems({...formContent})
}

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

const getTimeCheckResult = (device: CheckData.Device) => {
  return normalizeNumber(device.timeCheckResult ?? (device as any).Time_Check_Result)
}

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

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

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

const hasMixedFormalCheckState = () => {
  const checkStates = checkStore.devices.map(device => Number(device.checkState))
  const allCheckStatesEqual = new Set(checkStates).size <= 1
  const allCheckStatesKnown = checkStates.every(state => [0, 1, 2].includes(state))
  return !allCheckStatesEqual || !allCheckStatesKnown
}

const handleSelectTestItemChange = () => {
  syncSelectTestItems()
}

const handleTimeTestChange = (value: string | number | boolean) => {
  if (!Boolean(value)) {
    resumeTimeCheckChecked.value = false
    resumeTimeCheckDisabled.value = true
    checkStore.setResumeTimeCheck(false)
    syncSelectTestItems()
    return
  }

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

  resumeTimeCheckChecked.value = allTimeCheckResultsAreResumable()
  resumeTimeCheckDisabled.value = !allTimeCheckResultsAreResumable()
  checkStore.setResumeTimeCheck(!resumeTimeCheckDisabled.value && resumeTimeCheckChecked.value)
  syncSelectTestItems()
}

const handleFormalTestChange = (value: string | number | boolean) => {
  if (!Boolean(value)) {
    resumeFormalChecked.value = false
    resumeFormalDisabled.value = true
    checkStore.setResumeFormal(false)
    syncSelectTestItems()
    return
  }

  resumeFormalChecked.value = allSelectedDevicesHaveFormalState(1)
  resumeFormalDisabled.value = !allSelectedDevicesHaveFormalState(1)
  checkStore.setResumeFormal(!resumeFormalDisabled.value && resumeFormalChecked.value)
  syncSelectTestItems()
}

const handleResumeTimeCheckChange = (value: string | number | boolean) => {
  resumeTimeCheckChecked.value = !resumeTimeCheckDisabled.value && Boolean(value)
  checkStore.setResumeTimeCheck(formContent.timeTest && resumeTimeCheckChecked.value)
}

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

const handleStart = async () => {
  let count = 0
  for (let key in formContent) {
    if (formContent[key]) {
      count++
    }
  }
  if (count === 0) {
    ElMessage.warning('请选择测试内容！')
  } else {
    if (formContent.test && hasMixedFormalCheckState()) {
      ElMessage.warning('正式检测，所选设备检测状态不一致，请选择同一状态设备')
      return
    }
    if(formContent.channelsTest){
      const factorFlagArray = ref<string[]>([]) // 初始化为空数组
      for (let i = 0; i < checkStore.devices.length; i++) {
        const factorFlag = checkStore.devices[i].factorFlag
        if (factorFlag !== undefined && factorFlag !== null && factorFlag === 0) {
          factorFlagArray.value.push(checkStore.devices[i].deviceName.toString())
        }
      }
      if (factorFlagArray.value.length > 0) {
        const factorFlags = factorFlagArray.value.join(', ')
        ElMessageBox.confirm(
            factorFlags + '设备不支持系数校准，请重新选择',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            },
        )
        return
      }
    }
    checkStore.setCheckType(0)
    checkStore.setSelectTestItems({...formContent})
    checkStore.setResumeFormal(formContent.test && !resumeFormalDisabled.value && resumeFormalChecked.value)
    checkStore.setResumeTimeCheck(formContent.timeTest && !resumeTimeCheckDisabled.value && resumeTimeCheckChecked.value)

  

    submittedClose.value = true
    handleClose()
    
    emit('openTestDialog',checkStore.selectTestItems.test)
  }
}

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

defineExpose({open})

</script>


<style scoped lang="scss">
.test-item-checkbox {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  min-width: 92px;
  white-space: nowrap;
}

.test-item-row {
  display: flex;
  align-items: center;
  column-gap: 80px;
  width: 330px;
}

.resume-checkbox {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  min-width: 150px;
  white-space: nowrap;
}

.select-test-form {
  display: grid;
  grid-template-columns: 330px;
  justify-content: center;
  row-gap: 22px;
  padding: 12px 0 18px;

  :deep(.el-form-item) {
    width: auto !important;
    margin: 0 !important;
  }

  :deep(.el-form-item__content) {
    flex: none;
    justify-content: flex-start;
  }
}
</style>
