<template>
  <ContentPage>
    <template #search>
      <div style="display: flex; gap: 8px">
        <el-input v-model="query.keyword" placeholder="请输入名称或描述" style="width: 200px;" clearable @clear="loadData" @keyup.enter="loadData" />
        <el-button type="primary" @click="() => { query.page = 1; loadData() }">查询</el-button>
        <el-button @click="showCreateDialog" style="border: 1px solid var(--ios-primary); color: var(--ios-primary);">新建知识库</el-button>
      </div>
    </template>

    <el-table :data="knowledgeBases" v-loading="loading" style="width: 100%; height: 100%">
      <el-table-column type="index" label="序号" width="60" :index="indexMethod" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="名称" width="200" />
      <el-table-column prop="description" label="描述" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="primary" link icon="Upload" @click="showUploadDialog(scope.row)">上传文档</el-button>
          <el-button type="primary" link icon="Document" @click="showDocsDialog(scope.row)">文档管理</el-button>
          <el-button type="danger" link icon="Delete" @click="deleteKb(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" :image-size="300" :image="emptyStateMoney" />
      </template>
    </el-table>

    <template #pagination>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:page-size="query.size"
        v-model:current-page="query.page"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="loadData"
        @current-change="loadData"
      />
    </template>
  </ContentPage>

  <!-- Create Dialog -->
  <el-dialog v-model="createDialogVisible" title="新建知识库" width="500px">
      <el-form :model="createForm" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="createForm.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="createForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate" :loading="createLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- Upload Dialog -->
    <el-dialog
      v-model="uploadDialogVisible"
      :title="`上传文档至: ${currentKb?.name}`"
      width="500px"
      @close="handleDialogClose"
    ><el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        action="#"
        :auto-upload="true"
        :http-request="handleUpload"
        :limit="1"
        :on-exceed="handleExceed"
        :show-file-list="true"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 PDF, Word, TXT, Markdown 等格式文件
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <el-dialog v-model="docsDialogVisible" :title="`文档列表: ${currentKb?.name}`" width="900px">
      <div style="display: flex; justify-content: flex-end; margin-bottom: 12px;">
        <el-button type="warning" @click="rebuildCurrentKb" :loading="rebuildLoading">重建向量</el-button>
      </div>
      <el-table :data="documents" v-loading="docsLoading" style="width: 100%;">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="originalName" label="文件名" min-width="240" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="120" />
        <el-table-column prop="chunkCount" label="分片数" width="100" />
        <el-table-column prop="createTime" label="上传时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button type="danger" link icon="Delete" @click="deleteDoc(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
</template>

<script setup>
import ContentPage from '@/components/ContentPage.vue'
import { ref, onMounted, reactive } from 'vue'
import { knowledgeApi } from '@/api/knowledge'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Plus, Delete, Upload, Document, Search } from '@element-plus/icons-vue'
import emptyStateMoney from '@/assets/img/empty.svg'

const loading = ref(false)
const knowledgeBases = ref([])
const total = ref(0)
const createDialogVisible = ref(false)
const createLoading = ref(false)
const uploadDialogVisible = ref(false)
const currentKb = ref(null)
const uploadRef = ref()
const docsDialogVisible = ref(false)
const docsLoading = ref(false)
const documents = ref([])
const rebuildLoading = ref(false)

const query = reactive({
  page: 1,
  size: 10,
  keyword: '',
})

const createForm = reactive({
  name: '',
  description: ''
})

const loadData = async () => {
  loading.value = true
  try {
    const res = await knowledgeApi.getKnowledgeBases(query)
    knowledgeBases.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

function indexMethod(index) {
  return (query.page - 1) * query.size + index + 1
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  return new Date(timeStr).toLocaleString()
}

const showCreateDialog = () => {
  createForm.name = ''
  createForm.description = ''
  createDialogVisible.value = true
}

const handleCreate = async () => {
  if (!createForm.name) {
    ElMessage.warning('请输入名称')
    return
  }
  createLoading.value = true
  try {
    await knowledgeApi.createKnowledgeBase(createForm)
    ElMessage.success('创建成功')
    createDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error(error)
    ElMessage.error('创建失败')
  } finally {
    createLoading.value = false
  }
}

const deleteKb = (row) => {
  ElMessageBox.confirm(`确定要删除知识库 "${row.name}" 吗?`, '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await knowledgeApi.deleteKnowledgeBase(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error(error)
    }
  })
}

const showUploadDialog = (row) => {
  currentKb.value = row
  uploadDialogVisible.value = true
}

const showDocsDialog = async (row) => {
  currentKb.value = row
  docsDialogVisible.value = true
  await loadDocuments(row.id)
}

const loadDocuments = async (kbId) => {
  docsLoading.value = true
  try {
    const res = await knowledgeApi.listDocuments(kbId)
    documents.value = res || []
  } catch (error) {
    console.error(error)
    ElMessage.error('加载文档失败')
  } finally {
    docsLoading.value = false
  }
}

const handleUpload = async (options) => {
  const loadingInstance = ElLoading.service({ text: '正在上传并处理文档...' })
  try {
    if (!currentKb.value?.id) {
      throw new Error('知识库ID为空')
    }

    const res = await knowledgeApi.uploadDocument(currentKb.value.id, options.file)
    options?.onSuccess?.(res, options.file)
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    if (docsDialogVisible.value) {
      loadDocuments(currentKb.value.id)
    }
  } catch (error) {
    options?.onError?.(error)
    console.error(error)
    ElMessage.error('上传失败')
  } finally {
    loadingInstance.close()
    uploadRef.value?.clearFiles()
  }
}

const handleExceed = (files) => {
  uploadRef.value?.clearFiles()
  const file = files[0]
  uploadRef.value?.handleStart(file)
  uploadRef.value?.submit()
}

const handleDialogClose = () => {
  uploadRef.value?.clearFiles()
}

const deleteDoc = (doc) => {
  if (!currentKb.value?.id) return
  ElMessageBox.confirm(`确定要删除文档 "${doc.originalName}" 吗?`, '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await knowledgeApi.deleteDocument(currentKb.value.id, doc.id)
      ElMessage.success('删除成功')
      loadDocuments(currentKb.value.id)
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  })
}

const rebuildCurrentKb = () => {
  if (!currentKb.value?.id) return
  ElMessageBox.confirm('将重新解析所有文档并重建向量库，确定继续吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    rebuildLoading.value = true
    try {
      await knowledgeApi.rebuildVectorStore(currentKb.value.id)
      ElMessage.success('重建完成')
      loadDocuments(currentKb.value.id)
    } catch (error) {
      console.error(error)
      ElMessage.error('重建失败')
    } finally {
      rebuildLoading.value = false
    }
  })
}

onMounted(() => {
  loadData()
})
</script>


