<template>
  <div class="kb-view">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="documents" tab="文档管理">
        <DocumentUpload />
      </a-tab-pane>
      <a-tab-pane key="sources" tab="信息源配置">
        <SourceConfig />
      </a-tab-pane>
      <a-tab-pane key="search" tab="检索测试">
        <SearchTest />
      </a-tab-pane>
      <a-tab-pane key="settings" tab="KB 设置">
        <KBSettings />
      </a-tab-pane>
      <a-tab-pane key="history" tab="任务历史">
        <div class="task-history">
          <div class="task-history__toolbar">
            <a-button :loading="kbStore.isLoading" @click="kbStore.fetchDocuments()">
              刷新
            </a-button>
            <span class="task-history__hint">
              文档处理任务列表（{{ kbStore.documents.length }}）
            </span>
          </div>
          <a-table
            :data-source="kbStore.documents"
            :columns="taskColumns"
            :loading="kbStore.isLoading"
            row-key="document_id"
            size="small"
            :pagination="{ pageSize: 15 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-badge
                  :status="taskStatusBadge(record.status)"
                  :text="taskStatusLabel(record.status)"
                />
              </template>
              <template v-if="column.key === 'error'">
                <a-tooltip
                  v-if="record.status === 'failed' && record.error_message"
                  :title="record.error_message"
                >
                  <span class="task-history__error">
                    {{ record.error_message }}
                  </span>
                </a-tooltip>
                <span v-else class="task-history__muted">—</span>
              </template>
              <template v-if="column.key === 'created_at'">
                {{ formatTime(record.created_at) }}
              </template>
            </template>
          </a-table>
          <a-empty
            v-if="!kbStore.isLoading && kbStore.documents.length === 0"
            description="暂无任务记录"
          />
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useKnowledgeStore } from '@/stores/knowledge'
import DocumentUpload from '@/components/kb/DocumentUpload.vue'
import SourceConfig from '@/components/kb/SourceConfig.vue'
import SearchTest from '@/components/kb/SearchTest.vue'
import KBSettings from '@/components/kb/KBSettings.vue'

const kbStore = useKnowledgeStore()
const activeTab = ref('documents')

const taskColumns = [
  { title: '文件名', dataIndex: 'filename', key: 'filename', ellipsis: true },
  { title: '状态', dataIndex: 'status', key: 'status', width: 130 },
  { title: '分块数', dataIndex: 'chunks', key: 'chunks', width: 80 },
  { title: '错误信息', key: 'error', ellipsis: true },
  { title: '时间', dataIndex: 'created_at', key: 'created_at', width: 160 },
]

function taskStatusBadge(status: string): 'processing' | 'success' | 'error' | 'default' {
  switch (status) {
    case 'indexed':
      return 'success'
    case 'failed':
      return 'error'
    case 'pending':
    case 'parsing':
    case 'segmenting':
    case 'vectorizing':
      return 'processing'
    default:
      return 'default'
  }
}

function taskStatusLabel(status: string): string {
  switch (status) {
    case 'pending':
      return '待处理'
    case 'parsing':
      return '解析中'
    case 'segmenting':
      return '分段中'
    case 'vectorizing':
      return '向量化中'
    case 'indexed':
      return '已索引'
    case 'failed':
      return '失败'
    default:
      return status
  }
}

function formatTime(isoStr: string): string {
  try {
    return new Date(isoStr).toLocaleString('zh-CN')
  } catch {
    return isoStr
  }
}

onMounted(() => {
  kbStore.fetchSources()
})
</script>

<style scoped>
.kb-view {
  height: 100%;
  padding: var(--space-4) var(--space-6);
  overflow-y: auto;
  background: var(--bg-primary);
}

.task-history {
  padding: 8px 0;
}

.task-history__toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.task-history__hint {
  color: var(--text-placeholder);
  font-size: 13px;
}

.task-history__error {
  color: var(--color-error, #ff4d4f);
  font-size: 13px;
  cursor: help;
}

.task-history__muted {
  color: var(--text-placeholder);
}
</style>
