<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="设备配置id" prop="deviceConfigId">
        <el-input v-model="formData.deviceConfigId" placeholder="请输入设备配置id" />
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input v-model="formData.deviceCode" placeholder="请输入设备编号" />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="formData.deviceName" placeholder="请输入设备名称" />
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType">
        <el-radio-group v-model="formData.deviceType">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Siemens系列" prop="siemensSeries">
        <el-radio-group v-model="formData.siemensSeries">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_SIEMENS_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="siemens连接参数" prop="siemensConnectParam">
        <el-input v-model="formData.siemensConnectParam" placeholder="波特率，数据位，停止位，校验位 例如：9600，8，1，N" />
      </el-form-item>
      <el-form-item label="读取方式" prop="readCronType">
        <el-input v-model="formData.readCronType" placeholder="请输入读取方式" />
      </el-form-item>
      <el-form-item label="读取时间间隔" prop="readRepeatValue">
        <el-input v-model="formData.readRepeatValue" placeholder="请输入读取任务时间间隔" />
      </el-form-item>
      <el-form-item label="读取时间间隔单位" prop="readRepeatUnit">
        <el-radio-group v-model="formData.readRepeatUnit">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_DATA_UNIT)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="读取任务时间表达式" prop="readCron">
        <el-input v-model="formData.readCron" placeholder="请输入读取时间表达式" />
      </el-form-item>
      <el-form-item label="写入任务时间间隔" prop="writeCronType">
        <el-input v-model="formData.writeCronType" placeholder="请输入写入方式" />
      </el-form-item>
      <el-form-item label="写入任务时间间隔" prop="writeRepeatValue">
        <el-input v-model="formData.writeRepeatValue" placeholder="请输入写入时间间隔" />
      </el-form-item>
      <el-form-item label="写入任务时间间隔单位" prop="writeRepeatUnit">
        <el-radio-group v-model="formData.writeRepeatUnit">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_DATA_UNIT)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="写入时间表达式" prop="writeCron">
        <el-input v-model="formData.writeCron" placeholder="请输入写入时间表达式" />
      </el-form-item>
      <el-form-item label="是否持久化" prop="localPersistent">
        <el-radio-group v-model="formData.localPersistent">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_1_OR_0)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上传方式" prop="uploadRate">
        <el-radio-group v-model="formData.uploadRate">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_UPLOADING_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上传频率" prop="rateCount">
        <el-input v-model="formData.rateCount" placeholder="请输入上传频率" />
      </el-form-item>
      <el-form-item label="modbus协议类型" prop="modbusProtocol">
        <el-radio-group v-model="formData.modbusProtocol">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_MODBUS_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="modbus模式" prop="modbusPattern">
        <el-radio-group v-model="formData.modbusPattern">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_MODBUS_MOLD)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="modbus串口号" prop="portName">
        <el-radio-group v-model="formData.portName">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_MODBUS_PORT)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="modbus连接参数" prop="modbusConnectParam">
        <el-input v-model="formData.modbusConnectParam" placeholder="波特率，数据位，停止位，校验位 例如：9600，8，1，N）" />
      </el-form-item>
      <el-form-item label="读地址是否连续" prop="modbusReadAddrGap">
        <el-radio-group v-model="formData.modbusReadAddrGap">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_1_OR_0)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="已下发" prop="isUpload">
        <el-radio-group v-model="formData.isUpload">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_1_OR_0)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
       <el-form-item label="组织设备id" prop="orgId">
        <el-input v-model="formData.orgId" placeholder="请输入组织设备id" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-radio-group v-model="formData.isEnable">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, getBoolDictOptions} from '@/utils/dict'
import { GatewayApi } from '@/api/iot/gateway'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceConfigId: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  deviceType: undefined,
  siemensSeries: undefined,
  siemensConnectParam: undefined,
  readCronType: undefined,
  readRepeatValue: undefined,
  readRepeatUnit: undefined,
  readCron: undefined,
  writeCronType: undefined,
  writeRepeatValue: undefined,
  writeRepeatUnit: undefined,
  writeCron: undefined,
  localPersistent: undefined,
  uploadRate: undefined,
  rateCount: undefined,
  modbusProtocol: undefined,
  modbusPattern: undefined,
  portName: undefined,
  modbusConnectParam: undefined,
  modbusReadAddrGap: undefined,
  isUpload: undefined,
  gatewayId: undefined,
  orgId: undefined,
  remark: undefined,
  isEnable: undefined,
})
const formRules = reactive({
  gatewayId: [{ required: true, message: '网关id不能为空', trigger: 'blur' }],
  orgId: [{ required: true, message: '组织设备id不能为空', trigger: 'blur' }],
  isEnable: [{ required: true, message: '是否启用不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number, gatewayId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.gatewayId = gatewayId
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GatewayApi.getDevice(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await GatewayApi.createDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await GatewayApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceConfigId: undefined,
    deviceCode: undefined,
    deviceName: undefined,
    deviceType: undefined,
    siemensSeries: undefined,
    siemensConnectParam: undefined,
    readCronType: undefined,
    readRepeatValue: undefined,
    readRepeatUnit: undefined,
    readCron: undefined,
    writeCronType: undefined,
    writeRepeatValue: undefined,
    writeRepeatUnit: undefined,
    writeCron: undefined,
    localPersistent: undefined,
    uploadRate: undefined,
    rateCount: undefined,
    modbusProtocol: undefined,
    modbusPattern: undefined,
    portName: undefined,
    modbusConnectParam: undefined,
    modbusReadAddrGap: undefined,
    isUpload: undefined,
    gatewayId: undefined,
    orgId: undefined,
    remark: undefined,
    isEnable: undefined,
  }
  formRef.value?.resetFields()
}
</script>
