<template>
    <!-- 基础信息弹出框 -->
  <el-dialog :model-value="dialogVisible" :title="dialogTitle" v-bind="dialogMiddle" @close="close" >
    <div>
        <el-form :model="formContent"  ref='dialogFormRef' :rules='rules' class="form-two">
            <el-form-item label="名称" prop="name" >
                <el-input v-model='formContent.name' placeholder="请输入设备类型名称"/>
            </el-form-item>
            <el-form-item label="工作电源" prop="power" >
                <el-select v-model="formContent.power"  clearable placeholder="请选择工作电源">
                    <el-option
                        v-for="item in dictStore.getDictData('Dev_Power')"
                        :key="item.code"
                        :label="item.name"
                        :value="item.code"
                    />
                </el-select>
            </el-form-item>    
            <el-form-item label="通道数" prop="devChns" >
                <el-select v-model="formContent.devChns"  clearable placeholder="请选择设备通道数">
                    <el-option
                        v-for="item in dictStore.getDictData('Dev_Chns')"
                        :key="item.id"
                        :label="item.name"
                        :value="item.code"
                    />
                </el-select>
            </el-form-item>            
            <el-form-item label="额定电压(V)" prop="devVolt" >
                <el-select v-model="formContent.devVolt"  clearable placeholder="请选择额定电压">
                    <el-option
                        v-for="item in dictStore.getDictData('Dev_Volt')"
                        :key="item.id"
                        :label="item.name"
                        :value="item.code"
                    />
                </el-select>
            </el-form-item>           
            <el-form-item label="额定电流(A)" prop="devCurr" >
                <el-select v-model="formContent.devCurr"  clearable placeholder="请选择额定电流">
                    <el-option
                        v-for="item in dictStore.getDictData('Dev_Curr')"
                        :key="item.id"
                        :label="item.name"
                        :value="item.code"
                    />
                </el-select>
            </el-form-item> 
            <el-form-item label="报告模版名称" prop="reportName" >
                <el-select v-model="formContent.reportName"  clearable placeholder="请选择报告模版">
                    <el-option
                        v-for="item in dictStore.getDictData('Report_Template')"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="设备关联ICD" prop="icd" >
                <el-select v-model="formContent.icd"  clearable placeholder="请选择ICD">
                    <el-option
                        v-for="item in icdOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                    />
                </el-select>
            </el-form-item>
      </el-form>
      </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="save()" >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>

  </template>
  
  <script lang="ts" setup>
  import{  ElMessage, type FormInstance,type FormItemRule } from 'element-plus'
  import type { ProTableInstance } from '@/components/ProTable/interface'
  import { ref,computed, Ref  } from 'vue'
  import { type DevType } from '@/api/device/interface/devType'
   import { type ICD } from '@/api/device/interface/icd'
  import {dialogMiddle} from '@/utils/elementBind'
  import { useDictStore } from '@/stores/modules/dict'
  import {addDevType,updateDevType} from '@/api/device/devType'
  import {getICDAllList} from '@/api/device/icd'
  const dictStore = useDictStore()
  // 定义弹出组件元信息
  const dialogFormRef = ref()
  const icdOptions = ref<ICD.ResICD[]>([])
 function useMetaInfo() {
    const dialogVisible = ref(false)
    const titleType = ref('add')
    const formContent = ref<DevType.ResPqDevType>({
        id: '',     //设备类型ID
        name: '',//设备类型名称
        icd: '',//设备关联的ICD
        power: 'AC/DC 110V-220V',//工作电源
        devVolt: 57.74,   //额定电压（V）
        devCurr: 5,   //额定电流（A）
        devChns: 1,  //设备通道数
        reportName: '',//报告模版名称
        state: 1,
    })
    return { dialogVisible, titleType, formContent }
  }
  
  const { dialogVisible, titleType, formContent } = useMetaInfo()


// 清空formContent
const resetFormContent = () => {
    formContent.value = {
        id: '',     //设备类型ID
        name: '',//设备类型名称
        icd: '',//设备关联的ICD
        power: 'AC/DC 110V-220V',//工作电源
        devVolt: 57.74,   //额定电压（V）
        devCurr: 5,   //额定电流（A）
        devChns: 1,  //设备通道数
        reportName: '',//报告模版名称
        state: 1,
    }
  }
  
  let dialogTitle = computed(() => {
    return titleType.value === 'add' ? '新增设备类型' : '编辑设备类型'
  })




  //定义规则
  const formRuleRef = ref<FormInstance>()
  //定义校验规则
  const rules: Ref<Record<string, Array<FormItemRule>>> = ref({
    name: [{ required: true, message: '设备类型名称必填！', trigger: 'blur' }],
    power: [
    { required: true, message: '工作电源必选！', trigger: 'change' }
  ],
    devChns: [
    { required: true, message: '设备通道数必选！', trigger: 'change' }
  ],
  devVolt: [
    { required: true, message: '额定电压必选！', trigger: 'change' }
  ],
  devCurr: [
    { required: true, message: '额定电流必选！', trigger: 'change' }
  ],
  reportName: [
    { required: true, message: '报告模版名称必选！', trigger: 'change' }
  ],
  icd: [
    { required: true, message: '设备关联ICD必选！', trigger: 'change' }
  ],
  })

  
// 关闭弹窗
const close = () => {
    dialogVisible.value = false
    // 清空dialogForm中的值
    resetFormContent()
    // 重置表单
    dialogFormRef.value?.resetFields()
  }
  
  // 保存数据
  const save = () => {
    try {
        dialogFormRef.value?.validate(async (valid: boolean) => {
        if (valid) {
          if (formContent.value.id) {
              await updateDevType(formContent.value);
            } else {
               await addDevType(formContent.value);
          }
          ElMessage.success({ message: `${dialogTitle.value}成功！` })
          close()
          // 刷新表格
          await props.refreshTable!()
        }
      })
    } catch (err) {
      //error('验证过程中出现错误', err)
    }
  }
  
  // 打开弹窗，可能是新增，也可能是编辑
  const open = async (sign: string, data: DevType.ResPqDevType,icd: ICD.ResICD[]) => {
    // 重置表单
    dialogFormRef.value?.resetFields()
    titleType.value = sign
    dialogVisible.value = true

    icdOptions.value  = icd

    if (data.id) {
      formContent.value = { ...data }
    } else {
      resetFormContent()
    }
  }
  
  // 对外映射
  defineExpose({ open })
  const props = defineProps<{
    refreshTable: (() => Promise<void>) | undefined;
  }>()
  
  </script>