
<template>
  <div class="kb-container">
    <div class="header-section">
      <div class="title-info">
        <h2>知识库管理</h2>
        <p class="subtitle">管理所有知识库和相关内容</p>
      </div>
      <div class="action-buttons">
        <el-select v-model="queryParams.status" placeholder="所有状态" clearable style="width: 120px; margin-right: 12px" @change="handleSearch">
          <el-option label="正常" value="normal" />
          <el-option label="已禁用" value="disabled" />
        </el-select>
        <el-input
          v-model="queryParams.keyword"
          placeholder="搜索知识库名称..."
          style="width: 240px; margin-right: 12px"
          clearable
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        />
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon> 查询
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新建知识库
        </el-button>
      </div>
    </div>

    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="知识库名称" min-width="200">
          <template #default="{ row }">
            <div class="kb-name-cell">
              <el-icon class="kb-icon" :size="24" :style="{ color: getIconColor(row.name) }"><Collection /></el-icon>
              <div class="kb-info">
                <div class="name">{{ row.name }}</div>
                <div class="desc">{{ row.description || '暂无描述' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="父集合表名" min-width="150" prop="collection_name_parent" show-overflow-tooltip>
          <template #default="{ row }">
            <span class="collection-name parent">{{ row.collection_name_parent }}</span>
          </template>
        </el-table-column>

        <el-table-column label="子集合表名" min-width="150" prop="collection_name_children" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.collection_name_children" class="collection-name child">{{ row.collection_name_children }}</span>
            <span v-else class="empty-cell">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="document_count" label="文档数量" width="100" />

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" effect="light" round>{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_by" label="创建人" width="100" />
        
        <el-table-column prop="created_time" label="创建时间" width="160">
            <template #default="{ row }">
                {{ formatTime(row.created_time) }}
            </template>
        </el-table-column>

        <el-table-column prop="updated_by" label="修改人" width="100" />

        <el-table-column prop="updated_time" label="修改时间" width="160">
            <template #default="{ row }">
                {{ formatTime(row.updated_time) }}
            </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="查看" placement="top">
                <el-button link type="primary" @click="handleView(row)">
                    <el-icon><View /></el-icon>
                </el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
                <el-button link type="primary" @click="handleEdit(row)">
                    <el-icon><Edit /></el-icon>
                </el-button>
            </el-tooltip>
            <el-tooltip :content="syncingStates[row.id] ? '转换中' : (row.is_synced ? '已同步' : '同步到Milvus')" placement="top">
                <el-button link type="warning" @click="handleSync(row)" :disabled="row.is_synced || syncingStates[row.id]">
                    <el-icon :class="{'is-loading': syncingStates[row.id]}"><Refresh /></el-icon>
                </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
                <el-button link type="danger" @click="handleDelete(row)">
                    <el-icon><Delete /></el-icon>
                </el-button>
            </el-tooltip>
            <el-dropdown @command="(cmd) => handleCommand(cmd, row)" trigger="click">
                <el-button link type="info">
                    <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="toggleStatus">
                            {{ row.status === 'disabled' ? '启用' : '禁用' }}
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <div class="pagination-info">
            显示 {{ (pagination.page - 1) * pagination.pageSize + 1 }} 到 
            {{ Math.min(pagination.page * pagination.pageSize, pagination.total) }} 条，
            共 {{ pagination.total }} 条记录
        </div>
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Create/Edit Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建知识库' : '编辑知识库'"
      width="700px"
      @close="resetForm"
      class="kb-dialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="110px" class="kb-form">
        <div class="form-section">
            <div class="section-title">基本信息</div>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="知识库名称" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入知识库名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <template v-if="dialogType === 'create'">
            <el-form-item label="父集合名称" prop="collection_name_parent">
                <el-checkbox v-model="formData.enable_parent_collection" style="margin-bottom: 8px">
                    创建父集合
                </el-checkbox>
                <el-input
                    v-model="formData.collection_name_parent"
                    placeholder="父集合名(英文)"
                    :disabled="!formData.enable_parent_collection"
                />
            </el-form-item>
            <el-form-item label="子集合名称" prop="collection_name_children">
                <el-input v-model="formData.collection_name_children" placeholder="子集合名(英文)" />
            </el-form-item>
        </template>
        <template v-else>
            <el-form-item label="父集合名称">
                <el-input v-model="formData.collection_name_parent" disabled />
            </el-form-item>
            <el-form-item label="子集合名称" v-if="formData.collection_name_children">
                <el-input v-model="formData.collection_name_children" disabled />
            </el-form-item>
        </template>
                </el-col>
            </el-row>
            
            <el-form-item label="描述" prop="description">
                <el-input 
                    v-model="formData.description" 
                    type="textarea" 
                    rows="3" 
                    placeholder="请输入关于此知识库的详细描述..." 
                />
            </el-form-item>
            
            <el-row :gutter="20">
                <el-col :span="12" v-if="dialogType === 'create'">
                    <el-form-item label="向量维度" prop="dimension">
                        <el-input-number v-model="formData.dimension" :min="1" :step="1" style="width: 100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="状态" prop="status">
                        <template v-if="dialogType === 'create'">
                            <!-- 新建时状态固定为禁用，仅同步成功后才启用 -->
                            <el-tag type="warning" effect="plain">默认禁用（同步到 Milvus 后自动启用）</el-tag>
                        </template>
                        <template v-else>
                            <el-radio-group v-model="formData.status">
                                <el-radio-button label="normal">正常</el-radio-button>
                                <el-radio-button label="disabled">禁用</el-radio-button>
                            </el-radio-group>
                        </template>
                    </el-form-item>
                </el-col>
            </el-row>
        </div>

        <div class="form-section">
            <div class="section-header">
                <div class="section-title">元数据字段定义</div>
                <div class="section-desc">定义文档的额外属性，用于精确检索过滤</div>
            </div>
            
            <div class="metadata-fields-container">
                <div v-for="(field, index) in formData.metadata_fields" :key="index" class="metadata-field-card">
                    <div class="field-header">
                        <span class="field-index">字段 {{ index + 1 }}</span>
                        <el-button 
                            v-if="formData.metadata_fields.length > 1"
                            type="danger" 
                            link 
                            :icon="Delete"
                            @click="removeMetadataField(index)"
                            size="small"
                        >删除</el-button>
                    </div>
                    <el-row :gutter="15">
                        <el-col :span="6">
                            <el-form-item label-width="0" style="margin-bottom: 12px;">
                                <el-select 
                                    v-model="field.field_zh_name" 
                                    placeholder="中文名称" 
                                    filterable
                                    allow-create
                                    default-first-option
                                    @change="(val) => handleFieldChange(val, index)"
                                >
                                    <el-option 
                                        v-for="opt in availableFields"
                                        :key="opt.value"
                                        :label="opt.label" 
                                        :value="opt.value" 
                                        :disabled="getDisabledOptions(index).includes(opt.value)"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label-width="0" style="margin-bottom: 12px;">
                                <el-input v-model="field.field_en_name" placeholder="英文标识 (如: year)" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label-width="0" style="margin-bottom: 12px;">
                                <el-select v-model="field.field_type" placeholder="类型">
                                    <el-option label="文本" value="text" />
                                    <el-option label="数字" value="num" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label-width="0" style="margin-bottom: 12px;">
                                <el-input v-model="field.remark" placeholder="备注说明" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                
                <div class="add-field-btn">
                    <el-button type="primary" plain :icon="Plus" @click="addMetadataField" style="width: 100%">添加元数据字段</el-button>
                </div>
            </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- View Dialog -->
    <el-dialog
      v-model="viewDialogVisible"
      title="知识库详情"
      width="800px"
      class="view-dialog"
    >
      <el-descriptions :column="2" border class="detail-descriptions">
        <el-descriptions-item label="知识库名称" label-class-name="desc-label">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="父集合名称" label-class-name="desc-label">{{ viewData.collection_name_parent }}</el-descriptions-item>
        <el-descriptions-item label="子集合名称" label-class-name="desc-label">{{ viewData.collection_name_children || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态" label-class-name="desc-label">
            <el-tag :type="getStatusType(viewData.status)" effect="plain">
                {{ getStatusText(viewData.status) }}
            </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="文档数量" label-class-name="desc-label">{{ viewData.document_count }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" label-class-name="desc-label">{{ formatTime(viewData.created_time) }}</el-descriptions-item>
        <el-descriptions-item label="修改时间" label-class-name="desc-label">{{ formatTime(viewData.updated_time) }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2" label-class-name="desc-label">{{ viewData.description || '暂无描述' }}</el-descriptions-item>
      </el-descriptions>

      <div class="view-content-section">
        <div class="section-title">
            <el-icon><Menu /></el-icon> Milvus Schema 定义
        </div>
        <el-table :data="viewSchema" border stripe size="small" style="width: 100%">
            <el-table-column prop="name" label="字段名称" width="150" />
            <el-table-column prop="type" label="数据类型" width="150" />
            <el-table-column prop="desc" label="说明" />
        </el-table>
      </div>

      <div class="view-content-section">
        <div class="section-title">
            <el-icon><List /></el-icon> 元数据字段 (Metadata)
        </div>
        <el-table v-if="viewMetadata.length > 0" :data="viewMetadata" border stripe size="small" style="width: 100%">
            <el-table-column prop="field_zh_name" label="中文名称" width="150" />
            <el-table-column prop="field_en_name" label="英文标识" width="150" />
            <el-table-column prop="field_type" label="类型" width="100">
                <template #default="{ row }">
                    <el-tag size="small" type="info">{{ row.field_type === 'text' ? '文本' : '数字' }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
        </el-table>
        <div v-else class="empty-text">暂无元数据字段定义</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Search, Plus, Collection, View, Edit, Delete, MoreFilled, Refresh, Menu, List } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
    getKnowledgeBases, 
    getKnowledgeBaseMetadata,
    createKnowledgeBase, 
    updateKnowledgeBase, 
    updateKnowledgeBaseStatus, 
    deleteKnowledgeBase,
    syncKnowledgeBase,
    type KnowledgeBase 
} from '@/api/knowledge-base'
import dayjs from 'dayjs'

// Query Parameters
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  keyword: '',
  status: ''
})

// Table Data
const loading = ref(false)
const syncingStates = ref<Record<string, boolean>>({})
const tableData = ref<KnowledgeBase[]>([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// Dialog
const dialogVisible = ref(false)
const dialogType = ref<'create' | 'edit'>('create')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const formData = reactive({
  id: '',
  name: '',
  collection_name_parent: '',
  collection_name_children: '',
  description: '',
  dimension: 768,
  status: 'disabled',
  enable_parent_collection: true,
  metadata_fields: [{ field_zh_name: '', field_en_name: '', field_type: 'text', remark: '' }]
})

// View Dialog
const viewDialogVisible = ref(false)
const viewData = ref<KnowledgeBase>({} as KnowledgeBase)
const viewMetadata = ref<any[]>([])
const viewSchema = ref<any[]>([])

// 可选字段列表
const availableFields = [
    { label: "文件名称", value: "文件名称" },
    { label: "标准编号", value: "标准编号" },
    { label: "发布单位", value: "发布单位" },
    { label: "文件类型", value: "文件类型" },
    { label: "专业领域", value: "专业领域" },
    { label: "时效性", value: "时效性" },
    { label: "文档层级信息", value: "文档层级信息" },
    { label: "文件URL", value: "文件URL" },
    { label: "施工方案类型适配", value: "施工方案类型适配" }
]

// 计算每个字段下拉框的禁用选项
const getDisabledOptions = (currentIndex: number) => {
    // 获取所有已被选中的字段名
    const selectedValues = formData.metadata_fields
        .map((f, idx) => idx !== currentIndex ? f.field_zh_name : null)
        .filter(v => v !== null && v !== '')
    
    return selectedValues
}

const validateParentCollection = (rule: any, value: any, callback: any) => {
    if (!formData.enable_parent_collection) {
        callback()
        return
    }
    if (!value) {
        callback(new Error('请输入父集合名称'))
        return
    }
    const pattern = /^[a-zA-Z_][a-zA-Z0-9_]*$/
    if (!pattern.test(value)) {
        callback(new Error('必须以字母或下划线开头，只能包含字母、数字和下划线'))
        return
    }
    callback()
}

const validateChildCollection = (rule: any, value: any, callback: any) => {
    if (!value) {
        callback(new Error('请输入子集合名称'))
        return
    }
    if (value === formData.collection_name_parent && formData.enable_parent_collection) {
        callback(new Error('子集合名称不能与父集合名称相同'))
        return
    }
    callback()
}

const rules: FormRules = {
  name: [{ required: true, message: '请输入知识库名称', trigger: 'blur' }],
  collection_name_parent: [
    { validator: validateParentCollection, trigger: 'blur' }
  ],
  collection_name_children: [
    { required: true, message: '请输入子集合名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '必须以字母或下划线开头，只能包含字母、数字和下划线', trigger: 'blur' },
    { validator: validateChildCollection, trigger: 'blur' }
  ],
  dimension: [{ required: true, message: '请输入维度', trigger: 'blur' }]
}

// Methods
const loadData = async () => {
  loading.value = true
  try {
    const res = await getKnowledgeBases({
        page: pagination.page,
        page_size: pagination.pageSize,
        keyword: queryParams.keyword,
        status: queryParams.status
    })
    tableData.value = res.data
    pagination.total = res.meta?.total || 0
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  loadData()
}

const handleSelectionChange = (val: KnowledgeBase[]) => {
  // console.log(val)
}

const handleFieldChange = (val: string, index: number) => {
    // 自动映射中英文名称和类型
    const map: Record<string, any> = {
        '文件名称': { en: 'file_name', type: 'text' },
        '标准编号': { en: 'standard_number', type: 'text' },
        '发布单位': { en: 'issuing_authority', type: 'text' },
        '文件类型': { en: 'document_type', type: 'text' },
        '专业领域': { en: 'professional_field', type: 'text' },
        '时效性': { en: 'validity', type: 'text' },
        '文档层级信息': { en: 'hierarchy', type: 'text' },
        '文件URL': { en: 'file_url', type: 'text' },
        '施工方案类型适配': { en: 'plan_type_list', type: 'text' }
    }
    
    if (map[val]) {
        formData.metadata_fields[index].field_en_name = map[val].en
        formData.metadata_fields[index].field_type = map[val].type
    }
}

const handleAdd = () => {
  dialogType.value = 'create'
  formData.id = ''
  formData.name = ''
  formData.collection_name_parent = ''
  formData.collection_name_children = ''
  formData.description = ''
  formData.dimension = 768
  formData.status = 'normal'
  formData.enable_parent_collection = true
  formData.metadata_fields = [{ field_zh_name: '', field_en_name: '', field_type: 'text', remark: '' }]
  dialogVisible.value = true
}
const handleEdit = async (row: KnowledgeBase) => {
  dialogType.value = 'edit'
  formData.id = row.id
  formData.name = row.name
  formData.collection_name_parent = row.collection_name_parent
  formData.collection_name_children = row.collection_name_children || ''
  formData.description = row.description || ''
  formData.status = row.status
  
  // 加载元数据字段，允许编辑
  try {
      const res = await getKnowledgeBaseMetadata(row.id)
      if (res.code === 0 && res.data) {
          // res.data.metadata_fields 是从 t_samp_metadata 获取的
          if (res.data.metadata_fields && res.data.metadata_fields.length > 0) {
              formData.metadata_fields = res.data.metadata_fields
          } else {
              formData.metadata_fields = [{ field_zh_name: '', field_en_name: '', field_type: 'text', remark: '' }]
          }
      }
  } catch (error) {
      console.error("加载元数据失败", error)
      formData.metadata_fields = [{ field_zh_name: '', field_en_name: '', field_type: 'text', remark: '' }]
  }
  
  dialogVisible.value = true
}

const handleSync = async (row: KnowledgeBase) => {
    if (syncingStates.value[row.id]) return
    
    try {
        syncingStates.value[row.id] = true
        await syncKnowledgeBase(row.id)
        ElMessage.success('同步成功，Milvus集合已创建')
        loadData()
    } catch (error) {
        // error handled by request interceptor
    } finally {
        syncingStates.value[row.id] = false
    }
}

const handleView = async (row: KnowledgeBase) => {
    viewData.value = row
    viewMetadata.value = []
    viewSchema.value = [
        { name: 'pk', type: 'INT64', desc: '主键' },
        { name: 'text', type: 'VARCHAR', desc: '内容 (Max: 65535)' },
        { name: 'dense', type: 'FLOAT_VECTOR', desc: '向量列 (Dim: 768)' },
        { name: 'sparse', type: 'BM25', desc: '关键字检索' },
        { name: 'document_id', type: 'VARCHAR', desc: '文档ID' },
        { name: 'parent_id', type: 'VARCHAR', desc: '父段ID' },
        { name: 'index', type: 'INT64', desc: '索引序号' },
        { name: 'tag_list', type: 'VARCHAR', desc: '标签' },
        { name: 'permission', type: 'JSON', desc: '权限' },
        { name: 'metadata', type: 'JSON', desc: '元数据' },
        { name: 'is_deleted', type: 'BOOL/INT64', desc: '删除标志' },
        { name: 'created_by', type: 'VARCHAR', desc: '创建人' },
        { name: 'created_time', type: 'INT64', desc: '创建时间' },
        { name: 'updated_by', type: 'VARCHAR', desc: '修改人' },
        { name: 'updated_time', type: 'INT64', desc: '修改时间' }
    ]

    try {
        const res = await getKnowledgeBaseMetadata(row.id)
        if (res.code === 0 && res.data) {
            if (res.data.metadata_fields && res.data.metadata_fields.length > 0) {
                viewMetadata.value = res.data.metadata_fields
            }
            // 如果有动态 Schema 也可以合并到 viewSchema 中，但目前是固定的
        }
    } catch (error) {
        console.error("加载详情失败", error)
    }
    
    viewDialogVisible.value = true
}

const handleDelete = (row: KnowledgeBase) => {
  // 预先检查，提升用户体验
  if (row.document_count > 0) {
      ElMessage.warning(`知识库 "${row.name}" 中仍有 ${row.document_count} 条文档，请先清空文档后再删除`)
      return
  }

  ElMessageBox.confirm(
    `确定要删除知识库 "${row.name}" 吗？此操作不可恢复，且会删除对应的Milvus集合。`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await deleteKnowledgeBase(row.id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        // error handled by request interceptor
      }
    })
    .catch(() => {})
}

const handleCommand = async (command: string, row: KnowledgeBase) => {
    if (command === 'toggleStatus') {
        const newStatus = row.status === 'disabled' ? 'normal' : 'disabled'
        try {
            await updateKnowledgeBaseStatus(row.id, newStatus)
            ElMessage.success('状态更新成功')
            loadData()
        } catch (error) {
            console.error(error)
        }
    }
}

const addMetadataField = () => {
    formData.metadata_fields.push({ field_zh_name: '', field_en_name: '', field_type: 'text', remark: '' })
}

const removeMetadataField = (index: number) => {
    formData.metadata_fields.splice(index, 1)
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'create') {
          await createKnowledgeBase({
            name: formData.name,
              collection_name_parent: formData.enable_parent_collection ? formData.collection_name_parent : undefined,
            collection_name_children: formData.collection_name_children,
            description: formData.description,
            dimension: formData.dimension,
            metadata_fields: formData.metadata_fields.filter(f => f.field_zh_name && f.field_en_name)
          })
          ElMessage.success('创建成功')
        } else {
          await updateKnowledgeBase(formData.id, {
            name: formData.name,
            description: formData.description,
            status: formData.status,
            metadata_fields: formData.metadata_fields.filter(f => f.field_zh_name && f.field_en_name)
          })
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// Helpers
const getStatusType = (status: string) => {
  const map: Record<string, string> = {
    normal: 'success',
    test: 'info',
    disabled: 'danger'
  }
  return map[status] || 'info'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    normal: '正常',
    test: '测试',
    disabled: '已禁用'
  }
  return map[status] || status
}

const formatTime = (time: string) => {
    if (!time) return '-'
    return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 为图标生成随机颜色或基于名称的固定颜色
const getIconColor = (name: string) => {
    const colors = ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
    let hash = 0
    for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash)
    }
    const index = Math.abs(hash) % colors.length
    return colors[index]
}

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

<style scoped>
.kb-container {
  padding: 20px;
}

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

.title-info h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 8px 0 0;
  color: #909399;
  font-size: 14px;
}

.table-card {
  border-radius: 8px;
}

.kb-name-cell {
  display: flex;
  align-items: flex-start;
  padding: 8px 0;
}

.kb-icon {
  margin-right: 12px;
  margin-top: 4px;
}

.kb-info {
  flex: 1;
}

.kb-info .name {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
  margin-bottom: 4px;
}

.kb-info .desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.sub-collection {
    color: #909399;
    font-size: 12px;
    margin-top: 4px;
}

.collection-name {
    font-family: Consolas, Monaco, monospace;
    font-size: 13px;
}

.collection-name.parent {
    color: #409eff;
    font-weight: 500;
}

.collection-name.child {
    color: #67c23a;
}

.empty-cell {
    color: #c0c4cc;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-info {
    color: #909399;
    font-size: 13px;
}

.kb-dialog :deep(.el-dialog__body) {
    padding: 20px 30px;
}

.kb-form {
    padding-right: 10px;
}

.form-section {
    margin-bottom: 24px;
}

.section-title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 16px;
    padding-left: 10px;
    border-left: 3px solid #409eff;
}

.section-header {
    display: flex;
    align-items: baseline;
    margin-bottom: 16px;
}

.section-desc {
    font-size: 12px;
    color: #909399;
    margin-left: 10px;
}

.metadata-field-card {
    background-color: #f8f9fa;
    border-radius: 4px;
    border: 1px solid #e4e7ed;
    padding: 12px 16px;
    margin-bottom: 12px;
}

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

.field-index {
    font-size: 12px;
    font-weight: 600;
    color: #606266;
    background-color: #e6e8eb;
    padding: 2px 6px;
    border-radius: 2px;
}

.add-field-btn {
    margin-top: 10px;
}

.metadata-fields-container {
    padding: 0 5px;
}

.delete-btn {
    margin-left: 10px;
}

/* Detail View Styles */
:deep(.detail-descriptions .desc-label) {
    width: 120px;
    background-color: #f9fafc !important;
    font-weight: 600;
    color: #606266;
}

.view-content-section {
    margin-top: 24px;
}

.view-content-section .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: 600;
    margin-bottom: 12px;
    font-size: 15px;
    color: #303133;
    border-left: 4px solid #409EFF;
    padding-left: 10px;
}

.empty-text {
    color: #909399;
    font-size: 13px;
    padding: 10px 0;
    text-align: center;
    background-color: #f8f9fa;
    border-radius: 4px;
}
</style>
