<template>
  <div class="knowledge-base-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">知识库管理</h1>
          <p class="page-desc">创建和管理多个知识库，按类型分类管理文档。</p>
        </div>
        <div class="header-actions">
          <el-select v-model="filterType" placeholder="按类型筛选" clearable style="width: 140px;">
            <el-option v-for="opt in KB_TYPE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新建知识库
          </el-button>
        </div>
      </div>
    </div>

    <div class="kb-grid" v-loading="loading">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="kb in knowledgeBases" :key="kb.id">
          <el-card shadow="hover" class="kb-card" @click="handleViewKb(kb)">
            <div class="kb-header">
              <div class="kb-type-badge" :style="{ backgroundColor: getTypeColor(kb.kbType) }">
                {{ getTypeLabel(kb.kbType) }}
              </div>
              <el-switch
                v-model="kb.isEnabled"
                @click.stop
                @change="handleToggleEnabled(kb)"
                size="small"
              />
            </div>
            <h3 class="kb-name">{{ kb.name }}</h3>
            <p class="kb-desc">{{ kb.description || '暂无描述' }}</p>
            <div class="kb-stats">
              <div class="stat-item">
                <el-icon><Document /></el-icon>
                <span>{{ kb.docCount }} 文档</span>
              </div>
              <div class="stat-item">
                <el-icon><Rank /></el-icon>
                <span>优先级 {{ kb.priority }}</span>
              </div>
            </div>
            <div class="kb-actions" @click.stop>
              <el-button type="primary" link size="small" @click="handleEdit(kb)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" link size="small" @click="handleDelete(kb)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-if="!loading && knowledgeBases.length === 0" description="暂无知识库" />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑知识库' : '新建知识库'"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入知识库名称" />
        </el-form-item>
        <el-form-item label="类型" prop="kb_type">
          <el-select v-model="formData.kb_type" placeholder="请选择类型" style="width: 100%;">
            <el-option v-for="opt in KB_TYPE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入描述（可选）" />
        </el-form-item>
        <el-form-item label="优先级">
          <el-input-number v-model="formData.priority" :min="1" :max="100" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <el-drawer
      v-model="documentDrawer"
      :title="currentKb?.name || '文档管理'"
      size="70%"
      destroy-on-close
    >
      <document-list
        v-if="currentKb"
        :kb-id="currentKb.id"
        @upload-success="handleUploadSuccess"
      />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Document, Rank } from '@element-plus/icons-vue'
import {
  listKnowledgeBases,
  createKnowledgeBase,
  updateKnowledgeBase,
  deleteKnowledgeBase
} from '@/api/knowledge-base'
import { KB_TYPE_OPTIONS, KB_TYPE_MAP } from '@/types/knowledge-base'
import type { KnowledgeBase, KnowledgeBaseCreate, KnowledgeBaseUpdate } from '@/types/knowledge-base'
import DocumentList from './components/DocumentList.vue'

const loading = ref(false)
const knowledgeBases = ref<KnowledgeBase[]>([])
const filterType = ref('')
const dialogVisible = ref(false)
const documentDrawer = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref()
const currentKb = ref<KnowledgeBase | null>(null)
const currentEditId = ref('')

const defaultFormData = (): KnowledgeBaseCreate => ({
  name: '',
  kb_type: 'general',
  description: '',
  priority: 50
})

const formData = ref<KnowledgeBaseCreate>(defaultFormData())

const formRules = {
  name: [{ required: true, message: '请输入知识库名称', trigger: 'blur' }],
  kb_type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

const getTypeLabel = (type: string) => {
  return KB_TYPE_MAP[type]?.label || type
}

const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    product: '#409EFF',
    faq: '#67C23A',
    script: '#E6A23C',
    policy: '#F56C6C',
    general: '#909399'
  }
  return colorMap[type] || '#909399'
}

const loadKnowledgeBases = async () => {
  loading.value = true
  try {
    const res = await listKnowledgeBases({
      kb_type: filterType.value || undefined
    })
    knowledgeBases.value = res.data || []
  } catch (error) {
    ElMessage.error('加载知识库列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  isEdit.value = false
  currentEditId.value = ''
  formData.value = defaultFormData()
  dialogVisible.value = true
}

const handleEdit = (kb: KnowledgeBase) => {
  isEdit.value = true
  currentEditId.value = kb.id
  formData.value = {
    name: kb.name,
    kb_type: kb.kbType as any,
    description: kb.description || '',
    priority: kb.priority
  }
  dialogVisible.value = true
}

const handleDelete = async (kb: KnowledgeBase) => {
  try {
    await ElMessageBox.confirm(
      '删除知识库将同时删除所有关联文档和索引数据，确定要删除吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await deleteKnowledgeBase(kb.id)
    ElMessage.success('删除成功')
    loadKnowledgeBases()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleEnabled = async (kb: KnowledgeBase) => {
  try {
    await updateKnowledgeBase(kb.id, { is_enabled: kb.isEnabled })
    ElMessage.success(kb.isEnabled ? '已启用' : '已禁用')
  } catch (error) {
    kb.isEnabled = !kb.isEnabled
    ElMessage.error('操作失败')
  }
}

const handleViewKb = (kb: KnowledgeBase) => {
  currentKb.value = kb
  documentDrawer.value = true
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    if (isEdit.value) {
      const updateData: KnowledgeBaseUpdate = {
        name: formData.value.name,
        kb_type: formData.value.kb_type,
        description: formData.value.description,
        priority: formData.value.priority
      }
      await updateKnowledgeBase(currentEditId.value, updateData)
      ElMessage.success('保存成功')
    } else {
      await createKnowledgeBase(formData.value)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadKnowledgeBases()
  } catch (error) {
    ElMessage.error(isEdit.value ? '保存失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

const handleUploadSuccess = () => {
  loadKnowledgeBases()
}

watch(filterType, () => {
  loadKnowledgeBases()
})

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

<style scoped>
.knowledge-base-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.title-section {
  flex: 1;
  min-width: 300px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.kb-grid {
  min-height: 200px;
}

.kb-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.kb-card:hover {
  transform: translateY(-4px);
}

.kb-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.kb-type-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.kb-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.kb-desc {
  margin: 0 0 16px 0;
  font-size: 13px;
  color: var(--el-text-color-secondary);
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.kb-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 12px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;
  color: var(--el-text-color-regular);
}

.stat-item .el-icon {
  color: var(--el-text-color-secondary);
}

.kb-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
