<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>
    </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 {ElMessageBox, 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 checkStore = useCheckStore();
const open = async () => {
  resetFormContent()
  dialogVisible.value = true
}

// 清空表单内容
const resetFormContent = () => {
  Object.assign(formContent,{temperature:'',humidity:''})
}


  //定义校验规则
  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)
            emit('openTestDialog2')
            handleClose()
        }
    })
  } catch (err) {
    console.error('验证过程中出现错误', err)
  }

}

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

defineExpose({open})

</script>


<style scoped lang="scss">

</style>