<template>
  <div class="edit-kb-dialog">
    <el-dialog v-model="dialogVisible" title="知识库设置" width="500" align-center
      @closed="emit('update:modelValue', false)">
      <el-form ref="formRef" style="max-width: 600px" :model="formData" label-width="auto" class="demo-dynamic">
        <label for="">知识库名称</label>
        <el-form-item prop="name" label="">
          <el-input v-model="formData.name" />
        </el-form-item>
        <label for="">知识库描述</label>
        <el-form-item prop="description" label="">
          <el-input type="textarea" v-model="formData.description" resize="none"
            :autosize="{ minRows: 3, maxRows: 3 }" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, getCurrentInstance, toRaw } from "vue"
import { api } from "@/utils/config"
const { proxy } = getCurrentInstance()

const props = defineProps({ modelValue: Boolean, knowledgeBase: Object })
const emit = defineEmits(['update:modelValue', 'updateKB'])
const formData = ref({ id: null, name: "", description: "" })
let dialogVisible = ref(false)
const handleCancel = () => {
  emit('update:modelValue', false)
}

const handleConfirm = () => {
  emit('update:modelValue', false)
  updateKB(formData.value)
}
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal
}, { immediate: true })
watch(() => props.knowledgeBase, (newVal) => {
  formData.value = JSON.parse(JSON.stringify(newVal))
}, { immediate: true, deep: true })

const updateKB = async (formData) => {
  try {
    const data = await proxy.$http.put(api.knowledgeBase + `/${formData.id}`, {
      "name": formData.name,
      "description": formData.description,
      "tags": formData.tags
    })
    emit('updateKB')
  } catch (e) {
    console.log(e)
  }
}

</script>

<style lang="less" scoped>
.edit-kb-dialog {
  ::v-deep .el-dialog {
    label {
      margin: 20px 0px 10px;
      display: block;
    }
  }

  ::v-deep .el-form {

    .el-textarea__inner,
    .el-input__wrapper {
      background-color: #F1F3F6;
    }
  }
}
</style>