<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <el-form-item :label="t('DataCollection.Device.attributeCode')" prop="attributeCode">
        <el-input
v-model="formData.attributeCode" :placeholder="t('DataCollection.Device.placeholderAttributeCode')"
          @input="handleAttributeCodeInput" :disabled="formType === 'update'" />
      </el-form-item>
      <el-form-item :label="t('DataCollection.Device.attributeName')" prop="attributeName">
        <el-input v-model="formData.attributeName" :placeholder="t('DataCollection.Device.placeholderAttributeName')" />
      </el-form-item>
      <el-form-item :label="t('DataCollection.Device.attributeType')" prop="attributeType">
        <el-select
v-model="formData.attributeType" clearable filterable
          :placeholder="t('DataCollection.Device.placeholderAttributeType')" @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="t('DataCollection.Device.dataType')" prop="dataType">
        <el-select
v-model="formData.dataType" :placeholder="t('DataCollection.Device.placeholderDataType')"
          :disabled="formType === 'update'">
          <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="t('DataCollection.Device.address')" prop="address">
        <el-input v-model="formData.address" :placeholder="t('DataCollection.Device.placeholderAddress')" />
      </el-form-item>
      <el-form-item :label="t('DataCollection.Device.dataUnit')" prop="dataUnit">
        <el-select
v-model="formData.dataUnit" clearable
          :placeholder="t('DataCollection.DeviceModel.placeholderDataUnit')" class="w-1/1">
          <el-option v-for="unit in unitList" :key="unit.id" :label="unit.name" :value="unit.id" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('DataCollection.Device.ratio')" prop="ratio">
        <el-input-number
v-model="formData.ratio" :placeholder="t('DataCollection.Device.placeholderRatio')" :min="0.00"
          :decision="2" :step="0.01" class="!w-full" />
      </el-form-item>
      <el-form-item :label="t('DataCollection.Device.remark')" prop="remark">
        <el-input
v-model="formData.remark" :placeholder="t('DataCollection.Device.placeholderRemark')"
          type="textarea" />
      </el-form-item>
    </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 { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceApi } from '@/api/iot/device'
import { DeviceAttributeTypeApi, DeviceAttributeTypeVO } from '@/api/iot/deviceattributetype'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'

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 unitList = ref<ProductUnitVO[]>([]) // 产品单位列表
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 number | 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) => {
  const sanitized = (val || '').replace(/[^A-Za-z0-9_]/g, '')
  formData.value.attributeCode = sanitized.replace(/^[0-9]+/, '')
}


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: t('DataCollection.Device.attributeValidatorCodeRequired'), trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        if (/[\u4e00-\u9fa5]/.test(value)) {
          callback(new Error(t('DataCollection.Device.attributeValidatorCodeNoChinese')))
          return
        }
        if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
          callback(new Error('仅支持英文字母、数字和下划线，且必须以字母或下划线开头'))
          return
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
  attributeName: [
    { required: true, message: t('DataCollection.Device.attributeValidatorNameRequired'), trigger: 'blur' }
  ],
  dataType: [
    { required: true, message: t('DataCollection.DeviceModel.validatorDataTypeRequired'), trigger: 'change' }
  ],
  remark: [
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value && value.length > 100) {
          callback(new Error(t('DataCollection.Device.attributeValidatorRemarkTooLong')))
          return
        }
        callback()
      },
      trigger: ['blur', 'change']
    }
  ],
    attributeType: [{ required: true, message: '点位类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

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

  const data: any = {
    attributeCode,
    attributeName,
    attributeType,
    typeName,
    dataType,
    address,
    dataUnit,
    ratio,
    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()
  // 产品单位
  unitList.value = await ProductUnitApi.getProductUnitSimpleList()
  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 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,
    remark: undefined,
    deviceId: undefined
  }
  formRef.value?.resetFields()
}
</script>
