<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="设备分类" prop="deviceCategoryId">
            <el-tree-select
              v-model="formData.deviceCategoryId"
              :data="deviceCategoryTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              value-key="deviceCategoryId"
              placeholder="请选择设备分类"
              @node-click="handleDeviceCategoryTreeNodeClick"
              clearable
              filterable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="formData.name" maxlength="32" placeholder="请输入模板名称" />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">
          <el-form-item label="模板编码" prop="code">
            <el-input v-model="formData.code" maxlength="50" placeholder="请输入模板编码" />
          </el-form-item>
        </el-col>-->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div v-show="showButton">
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>

    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { CommonStatusEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import * as ProductClassifyApi from '@/api/pms/productclassify'
import * as DeviceTemplateApi from '@/api/pms/modeltemplate'
import { FormRules } from 'element-plus'
import { useTreeStore } from '@/store/modules/attrTemplateTreeStore';
import {ModelAttrTemplateVO} from "@/api/pms/modeltemplate";

defineOptions({ name: 'DeviceTemplateForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const treeStore = useTreeStore();
const localDeviceCategoryId = ref(null);  // 通过store存储的设备分类id 由父组件传递过来
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  name: '',
  deviceCategoryId: localDeviceCategoryId.value,
  code: '',
  id: undefined,
  remark: '',
  status: CommonStatusEnum.ENABLE,
})
const formData1 = ref({
  name: '',
  deviceCategoryId: localDeviceCategoryId.value,
  code: '',
  id: undefined,
  remark: '',
  status: CommonStatusEnum.ENABLE,
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }],
  deviceCategoryId: [{ required: true, message: '所属设备分类不能为空', trigger: 'blur' }],

})
const formRef = ref() // 表单 Ref
const deviceCategoryTree = ref()  // 设备分类树
const showButton = ref(true);

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  // 获取store中的设备分类id
  localDeviceCategoryId.value = treeStore.selectedId;
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceTemplateApi.getModelTemplate(id)
    } finally {
      formLoading.value = false
    }
  }
  // 获得 设备分类树
  await getDeviceCategoryTree()
  // 加载 设备分类 树
  // deviceCategoryList.value = handleTree(await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList())
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'node-click']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceTemplateApi.ModelAttrTemplateVO
    if (formType.value === 'create') {
      await DeviceTemplateApi.createModelTemplate(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceTemplateApi.updateModelTemplate(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 获得 设备分类 树 **/
const getDeviceCategoryTree = async () => {
  deviceCategoryTree.value = []
  const res = await ProductClassifyApi.IotProductClassifyApi.getSimpleProductClassifyList()
  let categoryTree: Tree = { id: 0, name: '顶级设备分类', children: [] }
  categoryTree.children = handleTree(res)
  deviceCategoryTree.value.push(categoryTree)
}

/** 处理 设备分类 树 被点击 */
const handleDeviceCategoryTreeNodeClick = async (row: { [key: string]: any }) => {
  emit('node-click', row)
  isRepated(row.id);
  localDeviceCategoryId.value = row.id
}

const isRepated = async(id)=>{
  showButton.value=true;
  formData1.value = await DeviceTemplateApi.getAttrTemplateByModelCategoryId(id);
  if(formData1.value){
    message.error(t('form.repeatDevice'))
    showButton.value=false;
  }else{
    showButton.value=true;
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: '',
    deviceCategoryId: localDeviceCategoryId.value,
    code: '',
    id: undefined,
    remark: '',
    status: CommonStatusEnum.ENABLE,
  }
  formRef.value?.resetFields()
}
</script>
