<template>
  <div class="source-config">
    <div class="source-config__header">
      <a-button type="primary" @click="showAddModal = true">
        <template #icon><PlusOutlined /></template>
        添加信息源
      </a-button>
    </div>

    <a-table
      :data-source="kbStore.sources"
      :columns="columns"
      :loading="kbStore.isLoading"
      row-key="id"
      size="small"
      :pagination="{ pageSize: 10 }"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'type'">
          <a-tag :color="typeColorMap[record.type] || 'default'">
            {{ typeLabelMap[record.type] || record.type }}
          </a-tag>
        </template>
        <template v-if="column.key === 'status'">
          <a-badge
            :status="record.status === 'active' ? 'success' : 'default'"
            :text="record.status === 'active' ? '正常' : record.status"
          />
        </template>
        <template v-if="column.key === 'last_synced'">
          {{ record.last_synced ? formatTime(record.last_synced) : '从未同步' }}
        </template>
        <template v-if="column.key === 'actions'">
          <a-space>
            <a-button type="link" size="small" @click="handleHealthCheck(record.id)">
              健康检查
            </a-button>
            <a-popconfirm
              title="确定删除此信息源？"
              @confirm="handleRemove(record.id)"
            >
              <a-button type="link" size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:open="showAddModal"
      title="添加信息源"
      @ok="handleAddSource"
      :confirm-loading="kbStore.isLoading"
    >
      <a-form :model="newSource" layout="vertical">
        <a-form-item label="名称" required>
          <a-input v-model:value="newSource.name" placeholder="输入信息源名称" />
        </a-form-item>
        <a-form-item label="类型" required>
          <a-select v-model:value="newSource.type" placeholder="选择信息源类型">
            <a-select-option value="local">本地文档</a-select-option>
            <a-select-option value="feishu">飞书知识库</a-select-option>
            <a-select-option value="confluence">Confluence</a-select-option>
            <a-select-option value="http">HTTP API</a-select-option>
          </a-select>
        </a-form-item>
        <template v-if="newSource.type === 'feishu'">
          <a-form-item label="App ID">
            <a-input v-model:value="newSource.config.app_id" />
          </a-form-item>
          <a-form-item label="App Secret">
            <a-input-password v-model:value="newSource.config.app_secret" />
          </a-form-item>
          <a-form-item label="知识库 ID">
            <a-input v-model:value="newSource.config.wiki_space_id" />
          </a-form-item>
        </template>
        <template v-if="newSource.type === 'confluence'">
          <a-form-item label="Base URL">
            <a-input v-model:value="newSource.config.base_url" placeholder="https://wiki.example.com" />
          </a-form-item>
          <a-form-item label="用户名">
            <a-input v-model:value="newSource.config.username" />
          </a-form-item>
          <a-form-item label="API Token">
            <a-input-password v-model:value="newSource.config.api_token" />
          </a-form-item>
          <a-form-item label="空间 Key">
            <a-input v-model:value="newSource.config.space_key" />
          </a-form-item>
        </template>
        <template v-if="newSource.type === 'http'">
          <a-form-item label="API URL">
            <a-input v-model:value="newSource.config.url" placeholder="https://api.example.com/kb" />
          </a-form-item>
          <a-form-item label="API Key">
            <a-input-password v-model:value="newSource.config.api_key" />
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useKnowledgeStore } from '@/stores/knowledge'

const kbStore = useKnowledgeStore()

const showAddModal = ref(false)
const newSource = reactive({
  name: '',
  type: 'local' as 'local' | 'feishu' | 'confluence' | 'http',
  config: {} as Record<string, string>,
})

const typeColorMap: Record<string, string> = {
  local: 'blue',
  feishu: 'green',
  confluence: 'purple',
  http: 'orange',
}

const typeLabelMap: Record<string, string> = {
  local: '本地文档',
  feishu: '飞书',
  confluence: 'Confluence',
  http: 'HTTP API',
}

const columns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '类型', dataIndex: 'type', key: 'type', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '文档数', dataIndex: 'document_count', key: 'document_count', width: 80 },
  { title: '最近同步', dataIndex: 'last_synced', key: 'last_synced', width: 160 },
  { title: '操作', key: 'actions', width: 180 },
]

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

async function handleAddSource(): Promise<void> {
  if (!newSource.name) {
    message.warning('请输入信息源名称')
    return
  }
  try {
    await kbStore.addSource(newSource.name, newSource.type, { ...newSource.config })
    showAddModal.value = false
    newSource.name = ''
    newSource.type = 'local'
    newSource.config = {}
    message.success('信息源添加成功')
  } catch {
    message.error('添加信息源失败')
  }
}

async function handleRemove(sourceId: string): Promise<void> {
  try {
    await kbStore.removeSource(sourceId)
    message.success('信息源已删除')
  } catch {
    message.error('删除信息源失败')
  }
}

async function handleHealthCheck(sourceId: string): Promise<void> {
  const status = await kbStore.checkHealth(sourceId)
  if (status === 'healthy') {
    message.success('信息源状态正常')
  } else if (status === 'unknown') {
    message.warning('健康检查未实现')
  } else {
    message.error('信息源状态异常')
  }
}
</script>

<style scoped>
.source-config {
  padding: 8px 0;
}

.source-config__header {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>
