<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="点位编码" prop="attributeCode">
        <el-input
          v-model="formData.attributeCode"
          placeholder="请输入点位编码"
          @input="handleAttributeCodeInput"
          :disabled = "formType === 'update'"
        />
      </el-form-item>
      <el-form-item label="点位名称" prop="attributeName">
        <el-input v-model="formData.attributeName" placeholder="请输入点位名称" />
      </el-form-item>
      <el-form-item label="点位类型" prop="attributeType">
        <el-select
          v-model="formData.attributeType"
          clearable
          filterable
          placeholder="请选择点位类型"
          @change="handleAttributeTypeChange"
        >
          <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType">
        <el-select v-model="formData.dataType" placeholder="请选择数据类型">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.IOT_DEVICE_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="寄存器地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入寄存器地址" />
      </el-form-item>
      <el-form-item label="单位" prop="dataUnit">
        <el-input v-model="formData.dataUnit" placeholder="请输入单位" />
      </el-form-item>
      <el-form-item label="倍率" prop="ratio">
        <el-input v-model="formData.ratio" placeholder="请输入倍率" :disabled="!ratioEnabled" />
      </el-form-item>
      <el-form-item label="顺序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入顺序" @input="handleSortInput" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          placeholder="请输入备注"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">保 存</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceApi } from '@/api/iot/device'
import { DeviceAttributeTypeApi, DeviceAttributeTypeVO } from '@/api/iot/deviceattributetype'

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 typeList = ref<DeviceAttributeTypeVO[]>([])
const loadTypeList = async () => {
  if (typeList.value.length > 0) {
    return
  }
  try {
    const data = await DeviceAttributeTypeApi.getDeviceAttributeTypePage({ pageNo: 1, pageSize: 10 })
    typeList.value = data?.list ?? []
  } catch {
    typeList.value = []
  }
}

const formData = ref({
  id: undefined as number | undefined,
  attributeCode: undefined as string | undefined,
  attributeName: undefined as string | undefined,
  attributeType: undefined as number | undefined,
  typeName: undefined as string | undefined,
  dataType: undefined as string | undefined,
  address: undefined as string | undefined,
  dataUnit: undefined as string | undefined,
  ratio: undefined as string | undefined,
  sort: undefined as string | undefined,
  remark: undefined as string | undefined,
  deviceId: undefined as number | undefined
})

const ratioEnabledTypes = new Set([
  'uint8',
  'uint16',
  'uint32',
  'uint64',
  'int8',
  'int16',
  'int32',
  'float32',
  'float64'
])

const ratioEnabled = computed(() => {
  const v = formData.value.dataType
  if (!v) return false
  return ratioEnabledTypes.has(v)
})

watch(
  () => formData.value.dataType,
  () => {
    if (!ratioEnabled.value) {
      formData.value.ratio = undefined
    }
  }
)

const handleAttributeCodeInput = (val: string) => {
  formData.value.attributeCode = val?.replace(/[\u4e00-\u9fa5]/g, '')
}

const handleSortInput = (val: string) => {
  formData.value.sort = val?.replace(/\D/g, '')
}

const handleAttributeTypeChange = (val: number | string) => {
  const matched = typeList.value.find(
    (item) => item.id === val || String(item.id) === String(val)
  )
  formData.value.typeName = matched?.name
}

const formRules = reactive({
  attributeCode: [
    { required: true, message: '点位编码不能为空', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        if (/[\u4e00-\u9fa5]/.test(value)) {
          callback(new Error('点位编码不允许输入中文'))
          return
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
  attributeName: [{ required: true, message: '点位名称不能为空', trigger: 'blur' }],
  sort: [
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        if (!/^\d+$/.test(value)) {
          callback(new Error('顺序只能输入数字'))
          return
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
  remark: [
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value && value.length > 100) {
          callback(new Error('备注不能超过100字'))
          return
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ]
})
const formRef = ref() // 表单 Ref

const buildSubmitData = () => {
  const {
    id,
    attributeCode,
    attributeName,
    attributeType,
    typeName,
    dataType,
    address,
    dataUnit,
    ratio,
    sort,
    remark,
    deviceId
  } = formData.value

  const parsedSort =
    sort === undefined || sort === null || sort === ''
      ? undefined
      : Number.isNaN(Number(sort))
        ? undefined
        : Number(sort)
  const data: any = {
    attributeCode,
    attributeName,
    attributeType,
    typeName,
    dataType,
    address,
    dataUnit,
    ratio: ratioEnabled.value ? ratio : undefined,
    sort: parsedSort,
    remark,
    deviceId
  }
  if (formType.value === 'update') {
    data.id = id
  }
  return data
}

/** 打开弹窗 */
const open = async (type: string, id?: number, deviceId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.deviceId = deviceId
  await loadTypeList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceApi.getDeviceAttribute(id)
      if (!(formData.value as any)?.deviceId) {
        ;(formData.value as any).deviceId = deviceId
      }

      const currentSort = (formData.value as any)?.sort
      if (currentSort !== undefined && currentSort !== null) {
        ;(formData.value as any).sort = String(currentSort)
      }

      const currentType = (formData.value as any)?.attributeType
      if (currentType !== undefined && currentType !== null && currentType !== '') {
        const matched = typeList.value.find(
          (item) =>
            item.id === currentType ||
            String(item.id) === String(currentType) ||
            item.name === currentType ||
            item.code === currentType
        )
        if (matched) {
          ;(formData.value as any).attributeType = matched.id
          ;(formData.value as any).typeName = matched.name
        }
      }
    } 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 = buildSubmitData()
    if (formType.value === 'create') {
      await DeviceApi.createDeviceAttribute(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceApi.updateDeviceAttribute(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    attributeCode: undefined,
    attributeName: undefined,
    attributeType: undefined,
    typeName: undefined,
    dataType: undefined,
    address: undefined,
    dataUnit: undefined,
    ratio: undefined,
    sort: undefined,
    remark: undefined,
    deviceId: undefined
  }
  formRef.value?.resetFields()
}
</script>
