<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <template #title>
      <div class="flex flex-col">
        <div>{{ dialogTitle }}</div>
        <div
          v-if="formType === 'setting' && formData.deviceName"
          class="text-12px leading-16px text-[var(--el-text-color-secondary)]"
        >
          <!-- {{ t('DataCollection.Device.deviceName') + formData.deviceName }} -->
        </div>
      </div>
    </template>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="activeRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <template v-if="formType === 'create' || formType === 'update'">
        <el-form-item :label="t('DataCollection.Device.deviceCode')" prop="deviceCode">
          <el-input
            v-model="formData.deviceCode"
            :disabled="formType === 'update'"
            :placeholder="t('DataCollection.Device.placeholderDeviceCode')"
          />
        </el-form-item>
        <el-form-item :label="t('DataCollection.Device.deviceName')" prop="deviceName">
          <el-input
            v-model="formData.deviceName"
            :placeholder="t('DataCollection.Device.placeholderDeviceName')"
          />
        </el-form-item>
        <el-form-item :label="t('DataCollection.Device.model')" prop="deviceModelId">
          <el-select
            v-model="formData.deviceModelId"
            clearable
            filterable
            :disabled="formType === 'update'"
            :placeholder="t('DataCollection.Device.placeholderModel')"
          >
            <el-option v-for="item in modelList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </template>
      <!-- <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="formData.deviceType" placeholder="请选择设备类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_GATEWAY_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item label="读主题" prop="readTopic">
        <el-input v-model="formData.readTopic" placeholder="请输入读主题" />
      </el-form-item>
      <el-form-item label="写主题" prop="writeTopic">
        <el-input v-model="formData.writeTopic" placeholder="请输入写主题" />
      </el-form-item>
      <el-form-item label="网关" prop="gatewayId">
        <el-input v-model="formData.gatewayId" placeholder="请输入网关" />
      </el-form-item> -->
<!--      <el-form-item label="设备品牌id" prop="deviceBrandId">-->
<!--        <el-input v-model="formData.deviceBrandId" placeholder="请输入设备品牌id" />-->
<!--      </el-form-item>-->
      <!-- <el-form-item label="离线间隔" prop="offLineDuration">
        <el-input v-model="formData.offLineDuration" placeholder="请输入离线间隔" />
      </el-form-item> -->
      <template v-else>
        <el-form-item :label="t('DataCollection.Device.topic')" prop="topic">
          <el-input
            v-model="formData.topic"
            :placeholder="t('DataCollection.Device.placeholderTopic')"
          />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('common.ok') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceApi, DeviceVO } from '@/api/iot/device'
import {DeviceModelApi, DeviceModelVO} from "@/api/iot/devicemodel";

/** 物联设备 表单 */
defineOptions({ name: 'DeviceForm' })

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

const modelList = ref<DeviceModelVO[]>([]) // 列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  deviceType: undefined,
  status: undefined,
  readTopic: undefined,
  writeTopic: undefined,
  gatewayId: undefined,
  deviceBrandId: undefined,
  offLineDuration: undefined,
  lastOnlineTime: undefined,
  remark: undefined,
  isEnable: false,
  deviceModelId: undefined,
  protocol: undefined,
  sampleCycle: undefined,
  url: undefined,
  username: undefined,
  password: undefined,
  topic: undefined,
})
const formRules = reactive({
  create: {
    deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }]
  },
  update: {
    deviceCode: [{ required: true, message: '设备编码不能为空', trigger: 'blur' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }]
  },
  setting: {
    topic: [{ required: true, message: '订阅主题不能为空', trigger: 'blur' }]
  }
})

const activeRules = computed(() => {
  return (formRules as any)[formType.value] ?? {}
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value =
    type === 'setting' ? t('DataCollection.Device.settingDialogTitle') : t('action.' + type)
  formType.value = type
  resetForm()

  try {
    const models = await DeviceModelApi.getDeviceModelList()
    modelList.value = Array.isArray(models) ? models : []
  } catch {
    modelList.value = []
  }

  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.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 { id, deviceCode, deviceName, deviceModelId, sampleCycle, remark, isEnable, topic } = formData.value as any

    if (formType.value === 'create') {
      const data: Partial<DeviceVO> = {
        deviceCode,
        deviceName,
        deviceModelId,
        sampleCycle,
        remark,
        isEnable: false
      }
      await DeviceApi.createDevice(data as DeviceVO)
      message.success(t('common.createSuccess'))
    } else if (formType.value === 'update') {
      const data: any = { id, deviceCode, deviceName, deviceModelId, sampleCycle, isEnable }
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    } else {
      const data: any = { id, deviceCode, deviceName, deviceModelId, isEnable, topic }
      await DeviceApi.updateDevice(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deviceCode: undefined,
    deviceName: undefined,
    deviceType: undefined,
    status: undefined,
    readTopic: undefined,
    writeTopic: undefined,
    gatewayId: undefined,
    deviceBrandId: undefined,
    offLineDuration: undefined,
    lastOnlineTime: undefined,
    remark: undefined,
    isEnable: false,
    deviceModelId: undefined,
    protocol: undefined,
    sampleCycle: undefined,
    url: undefined,
    username: undefined,
    password: undefined,
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
</script>
