<template>
    <el-dialog  :title="dialogTitle" v-model='dialogVisible' @close="close" v-bind="dialogBig">
        <el-divider >设备台账信息</el-divider>    
        <div class="form-grid">
            <el-form :model='formContent' ref='dialogFormRef' :rules='rules' :disabled="false">
                <el-row  :gutter="24" >
                    <el-col :span="8">
                        <el-form-item label="设备名称" prop="name">
                            <el-input v-model='formContent.name' placeholder="请输入设备名称"/>
                        </el-form-item>           
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label='设备类型'  prop='devType'>
                            <el-select v-model="formContent.devType"  clearable placeholder="请选择设备类型">
                            <el-option
                            v-for="item in dictStore.getDictData('High_Cate')"
                            :key="item.id"
                            :label="item.name"
                            :value="item.code"
                            />
                        </el-select>
                        </el-form-item>           
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="设备通道数" prop="devChns" placeholder="请输入设备通道">
                            <el-input v-model="formContent.devChns" />
                        </el-form-item>            
                    </el-col>
                </el-row>     
                <el-row  :gutter="24" >
                    <el-col :span="8">
                        <el-form-item label="额定电压(V)" prop="devVolt">
                            <el-input v-model='formContent.devVolt' placeholder="请输入额定电压"/>
                        </el-form-item>           
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="额定电流(A)" prop="devCurr" placeholder="请输入额定电流">
                            <el-input v-model="formContent.devCurr" />
                        </el-form-item>            
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label='生产厂家'  prop='manufacturer'>
                            <el-select v-model="formContent.manufacturer"  clearable placeholder="请选择生产厂家">
                            <el-option
                            v-for="item in dictStore.getDictData('High_Cate')"
                            :key="item.id"
                            :label="item.name"
                            :value="item.code"
                            />
                        </el-select>
                        </el-form-item>           
                    </el-col>
                </el-row>     
                <el-row  :gutter="24" >
                    <el-col :span="8">
                        <el-form-item label="生产日期" prop="createDate">
                            <el-date-picker 
                                v-model="formContent.createDate" 
                                placeholder="请选择生产日期"
                                :disabled-date="disabledDate"
                                />
                          
                        </el-form-item>           
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="出厂编号" prop="createId" placeholder="请输入出厂编号">
                            <el-input v-model="formContent.createId" />
                        </el-form-item>            
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="固件版本" prop="hardwareVersion">
                            <el-input v-model="formContent.hardwareVersion" placeholder="请输入固件版本"/>
                        </el-form-item>            
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="软件版本" prop="softwareVersion">
                            <el-input v-model="formContent.softwareVersion" placeholder="请输入软件版本"/>
                        </el-form-item>            
                    </el-col>
                </el-row>
                <el-row  :gutter="24" >
                    <el-col :span="8">
                        <el-form-item label='通讯协议'  prop='protocol'>
                            <el-select v-model="formContent.protocol"  clearable placeholder="请选择通讯协议">
                            <el-option
                            v-for="item in dictStore.getDictData('Event_Type')"
                            :key="item.id"
                            :label="item.name"
                            :value="item.code"
                            />
                        </el-select>
                        </el-form-item>         
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="IP地址" prop="ip">
                            <!-- <el-input v-model='formContent.ip'/> -->
                            <IPAddress v-model:value="formContent.ip"/>
                        </el-form-item>           
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="端口号" prop="port" placeholder="请输入端口号">
                            <el-input v-model="formContent.port" />
                        </el-form-item>            
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label='是否加密'  prop='encryption'>
                            <el-select v-model="formContent.encryption"  clearable placeholder="请选择是否加密">
                                <el-option label="是" :value="1"></el-option>
                                <el-option label="否" :value="0"></el-option>
                            </el-select>
                        </el-form-item>           
                    </el-col>
                </el-row>       
                <el-row  :gutter="24" >
                    <el-col :span="8">
                        <el-form-item label='设备模式'  prop='pattern'>
                            <el-input v-model='formContent.pattern' disabled/>
                        </el-form-item>           
                    </el-col>
                </el-row> 
                <el-row  :gutter="24" v-if="true">
                    <el-col :span="8">
                        <el-form-item label='样品编号'  prop='sampleID' clearable placeholder="请输入样品编号">
                            <el-input v-model='formContent.sampleID' />
                        </el-form-item>           
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label='送样日期'  prop='arrivedDate' >
                            <el-date-picker 
                                v-model="formContent.arrivedDate" 
                                placeholder="请选择送样日期"
                                :disabled-date="disabledDate"
                                />
                        </el-form-item>           
                    </el-col>
                </el-row>   
            </el-form>            
        </div>        
       

        <template #footer>
            <div >
                <el-button @click='close()'>取 消</el-button>
                <el-button type="primary" @click='save()'>保存</el-button>
            </div>
        </template>
    </el-dialog>


</template>
  <script setup lang='ts'>

  import IPAddress from '@/components/IpAddress/index.vue'
  import { dialogBig } from '@/utils/elementBind'
  import { type Device } from '@/api/device/interface'
  import { ElMessage, type FormItemRule } from 'element-plus'
  import { addPqDev, updatePqDev } from '@/api/device/device.ts'
  import { computed, type Ref, ref } from 'vue';
  import { useDictStore } from '@/stores/modules/dict'
  import { CirclePlus, Delete } from '@element-plus/icons-vue'
  // 使用 dayjs 库格式化
  import dayjs from 'dayjs';
  const dictStore = useDictStore()
  // 定义弹出组件元信息
  const dialogFormRef = ref()
  const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
  function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<Device.ResPqDev>({
      id: '',
      name: '',
      pattern:'模拟式',
      devType:'',
      devChns:0,
      devVolt:0,
      devCurr:0,
      manufacturer: '',
      createDate: '',
      createId: '', 
      hardwareVersion: '',
      softwareVersion: '',
      protocol: '',
      ip: '',
      port: 0,
      encryption: 1,
      reCheckNum:0,
      state: 1,
    })
    return { dialogVisible, titleType, formContent }
  }
  
  const { dialogVisible, titleType, formContent } = useMetaInfo()
  // 清空formContent
  const resetFormContent = () => {
    formContent.value = {
        id: '',
        name: '',
        pattern:'模拟式',
        devType:'',
        devChns:0,
        devVolt:0,
        devCurr:0,
        manufacturer: '',
        createDate: '',
        createId: '', 
        hardwareVersion: '',
        softwareVersion: '',
        protocol: '',
        ip: '',
        port: 0,
        encryption: 1,
        reCheckNum:0,
        state: 1,
    }
  }
  
  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增被检设备' : '编辑被检设备'
  })
  


  // 定义表单校验规则
  const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    devType: [{ required: true, message: '设备类型必选！', trigger: 'change' }],
    pattern: [{ required: true, message: '设备模式必填！', trigger: 'blur' }],
    name: [{ required: true, message: '设备名称必填！', trigger: 'blur' }],
    devChns: [{ required: true, message: '设备通道数必填！', trigger: 'blur' },
                // 指定正则，此处是数字正则
              { pattern: /^[1-9]\d*$/, message: '设备通道数为大于1的整数', trigger: 'blur' }],
    devVolt: [{ required: true, message: '额定电压必填！', trigger: 'blur' },
                { pattern: /^\d+(\.\d+)?$/, message: '额定电压格式错误', trigger: 'blur' }],
    devCurr: [{ required: true, message: '额定电流必填！', trigger: 'blur' },
                { pattern: /^\d+(\.\d+)?$/, message: '额定电流格式错误', trigger: 'blur' }],
    createDate: [{ required: true, message: '生产日期必填！', trigger: 'blur' }],
    createId: [{ required: true, message: '出厂编号必填！', trigger: 'blur' }],
    hardwareVersion: [{ required: true, message: '固件版本必填！', trigger: 'blur' }],
    softwareVersion: [{ required: true, message: '软件版本必填！', trigger: 'blur' }],
    ip:[{ required: true, message: 'IP地址必填！', trigger: 'blur' } ,
        { pattern: /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, message: 'IP地址格式错误', trigger: 'blur' }],
    port:[{ required: true, message: '端口号必填！', trigger: 'blur' },
          { pattern: /^\d+$/, message: '端口号格式错误', trigger: 'blur' }],
    manufacturer: [{ required: true, message: '生产厂家必选！', trigger: 'change' }],
    encryption: [{ required: true, message: '是否加密必选！', trigger: 'change' }],
    protocol: [{ required: true, message: '通讯协议必选！', trigger: 'change' }],
  })
  
  // 关闭弹窗
  const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          formContent.value.createDate = dayjs(formContent.value.createDate).format('YYYY-MM-DD');
          if (formContent.value.arrivedDate) 
          {
            formContent.value.arrivedDate = dayjs(formContent.value.arrivedDate).format('YYYY-MM-DD');
          }
          //console.log('1111'+formContent.value.arrivedDate)
          if (formContent.value.id) {
                const result = await updatePqDev(formContent.value);
                if(result.code != 'A0000'){
                  ElMessage.error({ message: result.message})
                }else{
                  ElMessage.success({ message: `${dialogTitle.value}成功！` })
                }
            } else {
                const result = await addPqDev(formContent.value);
               if(result.code != 'A0000'){
                  ElMessage.error({ message: result.message})
                }else{
                  ElMessage.success({ message: `${dialogTitle.value}成功！` })
                }
          }
          close()
          // 刷新表格
          await props.refreshTable!()
        }
      })
    } catch (err) {
      console.error('验证过程中出现错误', err)
    }
  }
  
  // 打开弹窗，可能是新增，也可能是编辑
  const open = (sign: string, data: Device.ResPqDev) => {
    titleType.value = sign
    dialogVisible.value = true
    if (data.id) {
      
      formContent.value = { ...data }
    } else {
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  


  </script>