<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { cloneDeep, isEmpty } from 'lodash-es'
import { ref } from 'vue'
import DialogBox from '@/components/dialog-box/index.vue'
import api from '@/servers/finyx/api/index'



// 定义组件属性，默认 confirmText 为 '确定'
const props = withDefaults(defineProps<{}>(), {})

// 定义组件事件，允许触发 submitHandle 事件
const emit = defineEmits(['refresh'])

// 定义一个响应式变量 dialogVisible，用于控制对话框的显示和隐藏
const dialogVisible = ref<boolean>(false)
// 定义一个响应式变量 formData，用于存储表单数据
const formData = ref<any>({})
// 定义一个响应式变量 formDataRef，用于引用表单实例
const formDataRef = ref<any>(null)

// 定义一个响应式变量 loading，用于控制按钮的加载状态
const loading = ref<boolean>(false)

// 关闭对话框的方法
const close = () => {
  dialogVisible.value = false
  formDataRef.value.resetFields()
  formData.value = {}
}
const title = ref<string>('新建知识库')
// 关闭对话框的方法
const open = (query?: any) => {
  dialogVisible.value = true
  title.value = '新建知识库'
  if (!isEmpty(query)) {
    title.value = '编辑知识库'
    formData.value = cloneDeep(query)
  }
}

// 提交表单的方法
const submitHandle = async () => {
  await formDataRef.value.validate()
  try {
    loading.value = true
    let datasetId: string = ''
    if (title.value === '新建知识库') {
      const data: any = await api.zhishiku.save5({
        ...formData.value,
      })
      datasetId = data?.id
    } else {
      await api.zhishiku.update5(formData.value)
      datasetId = formData.value.id
    }
    ElMessage.success(`${title.value}成功！`)
    emit('refresh', { id: datasetId, name: formData.value.name })
    close()
  } catch (e) {
    console.error(e)
    ElMessage.error(`${title.value}失败！`)
  } finally {
    loading.value = false;
  }
}

// 校验知识库名称是否存在（模拟异步请求）
const checkNameExists = async (name) => {
  // 这里应替换为实际的API请求
  return new Promise(async (resolve) => {
    try {
      await api.zhishiku.checkName({ name, id: formData.value?.id })
      resolve(false)
    } catch (e) {
      resolve(true)
    }
  })
}

const nameRules = [
  { required: true, message: '知识库名称不能为空', trigger: 'blur' },
  {
    validator: async (rule, value, callback) => {
      // 检查特殊符号
      const invalidChars = /[*？"<>/]/
      // const invalidChars = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/.test(value)
      if (invalidChars.test(value)) {
        return callback(new Error('知识库名称不能包含特殊符号：*？"<>/'))
      }
      // 检查名称重复（异步验证）
      if (value) {
        try {
          const exists = await checkNameExists(value)
          if (exists) {
            callback(new Error('知识库名称已存在'))
          } else {
            callback()
          }
        } catch (err) {
          callback(err)
        }
      } else {
        callback()
      }
    },
    trigger: 'blur'
  }
]

// 暴露 open 和 closeDialog 方法给外部使用
defineExpose({ open, close })
</script>

<template>
  <dialog-box
    :dialogVisible="dialogVisible"
    :title="title"
    width="500"
    @close="dialogVisible = false"
  >
    <el-form ref="formDataRef" :model="formData" label-width="auto">
      <el-form-item :rules="nameRules" label="知识库名称" prop="name">
        <el-input
          v-model="formData.name"
          maxlength="30"
          placeholder="请输入知识库名称"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="知识库描述" prop="des">
        <el-input
          v-model="formData.des"
          :rows="6"
          maxlength="500"
          placeholder="请输入知识库描述"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer res_el-dialog__footer">
        <el-button :loading="loading" @click.prevent="close"> 取消 </el-button>
        <el-button :loading="loading" type="primary" @click="submitHandle()">
          {{ title.value === '新建知识库' ? '创建' : '保存' }}
        </el-button>
      </span>
    </template>
  </dialog-box>
</template>

<style lang="scss" scoped></style>
