<template>
  <Dialog :title="title" v-model="dialogVisible" width="800px">
    <el-form v-loading="formLoading" :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="知识库名称" prop="libName">
        <el-input v-model="form.libName" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="资源类型" prop="libType">
        <el-radio-group v-model="form.libType">
          <el-radio :label="1"> 文件 </el-radio>
          <el-radio :label="2"> 纯图片 </el-radio>
          <el-radio :label="3"> 自主编辑 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <Editor v-model:modelValue="form.remark" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="formLoading" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup>
import * as LibraryApi from '@/api/system/library'

const emit = defineEmits(['success'])
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示

const form = ref()
const rules = ref({
  libName: { required: true, message: '名称不可为空', trigger: 'blur' }
})

const title = ref('')

const formRef = ref()
const formLoading = ref(false)
const formType = ref('create')

const open = (type, val) => {
  dialogVisible.value = true
  formType.value = type
  if (val) {
    title.value = '修改知识库'
    form.value = { ...val }
  } else {
    title.value = '新增知识库'
    form.value = {
      libName: '',
      libType: 1,
      remark: undefined,
      isDefault: false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await LibraryApi.createLibrary(form.value)
      message.success(t('common.createSuccess'))
    } else {
      await LibraryApi.updateLibrary(form.value)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped></style>
