<!-- 设备分类属性表单 -->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="DeviceAttrModelFormRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="属性名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入属性名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="日报取值" prop="dailyReport">
            <el-radio-group v-model="formData.dailyReport">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.RQ_IOT_ISCOLLECTION)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <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-col>
        <el-col :span="12">
          <el-form-item label="是否累计:" prop="isSum">
            <el-radio-group v-model="formData.isSum">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.RQ_IOT_SUM)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="累加值" prop="defaultValue" v-show="formData.isSum === 1">
            <!--            <el-input v-model="formData.defaultValue" placeholder="请选择累加值" />-->
            <el-select v-model="formData.defaultValue" placeholder="请选择累加值" clearable>
              <el-option
                v-for="dict in nonSumList"
                :key="dict.name"
                :label="dict.name"
                :value="dict.id"
                :track-by="dict.id"
              />
            </el-select>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="是否累加" prop="sumId" v-show="formData.isSum === 1">
            <el-radio-group v-model="formData.sumId">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.RQ_IOT_MODEL_PLUS)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="标识符" prop="code" v-if="formData.isSum === 1">
            <el-radio-group v-model="formData.code">
              <el-radio
                v-for="dict in getStrDictOptions(DICT_TYPE.RQ_IOT_MODEL_TEMPLATE_ATTR)"
                :key="dict.value"
                :value="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="填写阈值" prop="threshold" v-else>
            <el-input v-model="formData.threshold" placeholder="请输入阈值" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <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-col>
      </el-row>




      <!-- 属性配置 -->
      <DeviceAttrModelProperty
        v-model="formData.selectOptions"
      />
      <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,getStrDictOptions } 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 nonSumList = ref<DeviceAttrModelData[]>([]) // 列表的数据
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:'',
  isSum:1
})
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 uniqueNonSumList = computed(() => {
  // 根据id去重
  const uniqueMap = new Map();
  nonSumList.value.forEach(item => {
    if (!uniqueMap.has(item.id)) {
      uniqueMap.set(item.id, item);
    }
  });
  return Array.from(uniqueMap.values());
});
/** 打开弹窗 */
const open = async (type: string, id?: number,name?:string,list?:[]) => {
  nonSumList.value = [];
  if(list.value.length>0){
    // 处理传入的列表，确保不重复
    const tempMap = new Map();
    list.value.forEach((item: any) => {
      if (!tempMap.has(item.id)) {
        tempMap.set(item.id, item);
      }
    });
    nonSumList.value = Array.from(tempMap.values());
  }
  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 {
      const result = await DeviceAttrModelApi.getDeviceAttrModel(id);
      formData.value = {
        ...result,
        // 确保defaultValue是数值类型的id，以便正确匹配
        defaultValue: result.defaultValue ? Number(result.defaultValue) : ''
      };
      // 情况一：属性初始化
      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
    console.log(JSON.stringify(data))
    data.deviceCategoryId = props.deviceCategoryId
    data.requiredFlag = formData.value.selectOptions.requiredFlag
    // 处理空值，确保空值能正确提交

    if (data.defaultValue === undefined) {
      data.defaultValue = '';
    }
    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>
