<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.DeviceModel.attributeCode')" prop="attributeCode">
        <el-input
          v-model="formData.attributeCode"
          :placeholder="t('DataCollection.DeviceModel.placeholderAttributeCode')"
          :disabled = "formType === 'update'"/>
      </el-form-item>
      <el-form-item :label="t('DataCollection.DeviceModel.attributeName')" prop="attributeName">
        <el-input
          v-model="formData.attributeName"
          :placeholder="t('DataCollection.DeviceModel.placeholderAttributeName')" />
      </el-form-item>
      <el-form-item :label="t('DataCollection.DeviceModel.attributeType')" prop="attributeType">
        <el-select
          v-model="formData.attributeType"
          clearable
          filterable
          :placeholder="t('DataCollection.DeviceModel.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.DeviceModel.dataType')" prop="dataType">
        <el-select
          v-model="formData.dataType"
          :placeholder="t('DataCollection.DeviceModel.placeholderDataType')">
          <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.DeviceModel.address')" prop="address">
        <el-input
          v-model="formData.address"
          :placeholder="t('DataCollection.DeviceModel.placeholderAddress')" />
      </el-form-item>
      <el-form-item :label="t('DataCollection.DeviceModel.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.DeviceModel.ratio')" prop="ratio">
        <el-input-number
          v-model="formData.ratio"
          :placeholder="t('DataCollection.DeviceModel.placeholderRatio')" 
          :min="0.00"
          :decision="2"
          :step="0.01"
          class="!w-full"
          :disabled = "!ratioEnabled"/>
      </el-form-item>
      <el-form-item :label="t('DataCollection.DeviceModel.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          :placeholder="t('DataCollection.DeviceModel.placeholderAttributeRemark')" 
          type="textarea"
          />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('DataCollection.DeviceModel.dialogOk') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('DataCollection.DeviceModel.dialogCancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { DeviceModelAttributeApi } from '@/api/iot/devicemodelattribute'
import { DeviceAttributeTypeApi, DeviceAttributeTypeVO } from '@/api/iot/deviceattributetype'
import { ProductUnitApi, ProductUnitVO } from '@/api/erp/product/unit'

/** 采集设备模型-点位管理 表单 */
defineOptions({ name: 'DeviceModelAttributeForm' })

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

const typeList = ref<DeviceAttributeTypeVO[]>([])
const typeListLoaded = ref(false)
const loadTypeList = async () => {
  if (typeListLoaded.value) {
    return
  }
  try {
    const data = await DeviceAttributeTypeApi.getDeviceAttributeTypePage({ pageNo: 1, pageSize: 10 })
    typeList.value = data?.list ?? []
    typeListLoaded.value = true
  } catch {
    typeList.value = []
  }
}

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
	  id: undefined,
	  attributeCode: undefined,
	  attributeName: undefined,
	  attributeType: undefined,
	  typeName: undefined,
	  dataType: undefined,
	  address: undefined,
	  dataUnit: undefined,
	  ratio: undefined,
	  remark: undefined,
	  deviceModelId: undefined,
	})
const formRules = reactive({
  attributeCode: [{ required: true, message: t('DataCollection.DeviceModel.validatorAttributeCodeRequired'), trigger: 'blur' }],
  attributeName: [{ required: true, message: t('DataCollection.DeviceModel.validatorAttributeNameRequired'), trigger: 'blur' }],
  dataType: [{ required: true, message: t('DataCollection.DeviceModel.validatorDataTypeRequired'), trigger: 'change' }],
  attributeType: [{ required: true, message: '点位类型不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const unitList = ref<ProductUnitVO[]>([]) // 产品单位列表

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)
})

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

  const data: any = {
    attributeCode,
    attributeName,
    attributeType,
    typeName,
    dataType,
    address,
    dataUnit,
    ratio: ratioEnabled.value ? ratio : undefined,
    remark,
    deviceModelId
  }
  if (formType.value === 'update') {
    data.id = id
  }
  return data
}

/** 打开弹窗 */
const open = async (type: string, id: number, modelId: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  await loadTypeList()
  // 产品单位
  unitList.value = await ProductUnitApi.getProductUnitSimpleList()
  formData.value.deviceModelId = modelId
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceModelAttributeApi.getDeviceModelAttribute(id)

	      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 DeviceModelAttributeApi.createDeviceModelAttribute(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceModelAttributeApi.updateDeviceModelAttribute(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

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

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