<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="标签中文名称" prop="nameCn">
        <el-input v-model="formData.nameCn" placeholder="请输入标签名称" />
      </el-form-item>
      <el-form-item label="标签英文名称" prop="nameEn">
        <el-input v-model="formData.nameEn" placeholder="请输入标签英文名称" />
      </el-form-item>
      <el-form-item label="标签类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_TAG_TYPE)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item v-if="showParentId" label="上级id" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="tagTree"
          :props="{...defaultProps, label: 'nameCn'}"
          check-strictly
          default-expand-all
          placeholder="请选择上级id"
        />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as TagApi from '@/api/menduner/system/tag'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
// import { defaultProps, handleTree } from '@/utils/tree'

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 formRef = ref() // 表单 Ref
const formData = ref({
  id: undefined,
  nameCn: undefined,
  nameEn: undefined,
  type: undefined,
  parentId: 0,
  level: 0
})
const formRules = reactive({
  type: [{ required: true, message: '标签类型不能为空', trigger: 'blur' }],
  nameCn: [{ required: true, message: '标签中文名称不能为空', trigger: 'blur' }],
  nameEn: [{ required: true, message: '标签英文名称不能为空', trigger: 'blur' }],
})

// const showParentId = ref(true)

/** 打开弹窗 */
const open = async (type: string, id?: number, level?: number) => {
  // if (type === 'create' && !parentId) showParentId.value = false
  // else await getTagTree()
  
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id && !level?.toString()) {
    formLoading.value = true
    try {
      formData.value = await TagApi.getTag(id)
      formData.value.type = Number(formData.value.type)
    } finally {
      formLoading.value = false
    }
  }
  // if (parentId) formData.value.parentId = parentId
  // if (level || type === 'create') formData.value.level = level ? Number(level) + 1 : 1

  if (level?.toString()) {
    formData.value.parentId = id
    formData.value.level = Number(level) + 1
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

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

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    nameCn: undefined,
    nameEn: undefined,
    type: undefined,
    parentId: 0,
    level: 0
  }
  formRef.value?.resetFields()
}

/** 获得标签信息树 */
// const tagTree = ref([])
// const getTagTree = async () => {
//   tagTree.value = []
//   const data = await TagApi.getTagPage({})
//   const root: Tree = { id: 0, name: '顶级标签信息', children: [] }
//   root.children = handleTree(data, 'id', 'parentId')
//   tagTree.value.push(root)
// }
</script>