<!-- 设备分类属性表单 -->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="DeviceAttrModelFormRules"
      label-width="100px"
    >
      <el-form-item label="属性名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入属性名称" />
      </el-form-item>
      <el-form-item label="标识符" prop="code">
        <el-input v-model="formData.code" placeholder="请输入标识符" />
      </el-form-item>
      <!-- 属性配置 -->
      <DeviceAttrModelProperty
        v-model="formData.selectOptions"
      />
      <el-form-item label="是否数采" prop="isCollection">
        <el-radio-group v-model="formData.isCollection">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.RQ_IOT_ISCOLLECTION)"
            :key="dict.value"
            :value="dict.value"
            @click="radioChange(dict.value)"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="物属性" prop="modelAttr">
        <el-select v-model="formData.modelAttr" placeholder="请选择">
          <el-option
            v-for="dict in thingsModelData"
            :key="dict.modelName"
            :label="dict.modelName"
            :value="dict.identifier"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="默认值" prop="defaultValue">
        <el-input v-model="formData.defaultValue" placeholder="请输入默认值" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="formData.description"
          :maxlength="200"
          :rows="3"
          placeholder="请输入属性描述"
          type="textarea"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import DeviceAttrModelProperty from './AttrTemplateModelProperty.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { DeviceAttrModelApi, DeviceAttrModelData } from '@/api/pms/modelattrtemplate'
import { DataSpecsDataType, DeviceAttrModelFormRules } from './config'
import { cloneDeep } from 'lodash-es'
import { isEmpty } from '@/utils/is'
import { defineProps } from 'vue'
import * as ModelTemplateApi from "@/api/pms/modeltemplate";

/** 设备属性 模型数据表单 */
defineOptions({ name: 'AttrTemplateModelForm' })

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<DeviceAttrModelData>({
  deviceCategoryId: -1,
  dataType: DataSpecsDataType.DOUBLE,
  type: DataSpecsDataType.DOUBLE,
  requiredFlag: 0,
  description: '',
  defaultValue: '',
  selectOptions: {
    type: DataSpecsDataType.DOUBLE,
    defaultValue: '',
    requiredFlag: '',
    dataSpecs: {
      dataType: DataSpecsDataType.DOUBLE
    }
  },
  isCollection:1,
  modelAttr:'',
})
const thingsModelData = ref([{
    modelName:'',
    identifier:''
  }]
)


let deviceCategoryName: string;
const radioChange = (event) => {
  if(event==1){
    getAttrList();
  }
  // 在这里添加你的逻辑处理代码
};

const getAttrList = async () => {
  try {
    const data = await DeviceAttrModelApi.getThingsModelAttr(deviceCategoryName);
    thingsModelData.value = data
  } finally {

  }
}

const props = defineProps({
  deviceCategoryId: [String, Number]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number,name?:string) => {

  deviceCategoryName = name;
  if(type=='update'){
    await getAttrList();
  }
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceAttrModelApi.getDeviceAttrModel(id)
      // 情况一：属性初始化
      if (isEmpty(formData.value.selectOptions)) {
        formData.value.type = DataSpecsDataType.DOUBLE
        formData.value.selectOptions = {
          type: DataSpecsDataType.DOUBLE,
          dataSpecs: {
            dataType: DataSpecsDataType.DOUBLE
          }
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open, close: () => (dialogVisible.value = false) })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = cloneDeep(formData.value) as DeviceAttrModelData
    data.deviceCategoryId = props.deviceCategoryId
    data.requiredFlag = formData.value.selectOptions.requiredFlag
    fillExtraAttributes(data)
    if (formType.value === 'create') {
      await DeviceAttrModelApi.createDeviceAttrModel(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceAttrModelApi.updateDeviceAttrModel(data)
      message.success(t('common.updateSuccess'))
    }
  } finally {
    dialogVisible.value = false // 确保关闭弹框
    emit('success')
    formLoading.value = false
  }
}

/** 填写额外的属性 */
const fillExtraAttributes = (data: any) => {
  // 处理不同类型的情况
  // 属性
  removeDataSpecs(data.selectOptions)
  data.type = data.selectOptions.type
  data.selectOptions.identifier = data.code
  data.selectOptions.code = data.code
  data.selectOptions.name = data.name
}
/** 处理 dataSpecs 为空的情况 */
const removeDataSpecs = (val: any) => {
  if (isEmpty(val.dataSpecs)) {
    delete val.dataSpecs
  }
  if (isEmpty(val.dataSpecsList)) {
    delete val.dataSpecsList
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    dataType: DataSpecsDataType.DOUBLE,
    type: DataSpecsDataType.DOUBLE,
    selectOptions: {
      type: DataSpecsDataType.DOUBLE,
      dataSpecs: {
        dataType: DataSpecsDataType.DOUBLE
      }
    },
  }
  formRef.value?.resetFields()
}
</script>
