import { get } from './request'

export interface KnowledgeItem {
  id: number
  title: string
  category: string
  cover?: string
  content: string
  readCount: number
  createTime: string
}

export interface KnowledgeCategory {
  key: string
  name: string
}

export function getKnowledgeList(pageNum = 1, pageSize = 10, category?: string) {
  return get<{ rows: KnowledgeItem[]; total: number }>('/knowledge/list', { pageNum, pageSize, category })
}

export function getKnowledgeDetail(id: number) {
  return get<KnowledgeItem>(`/knowledge/${id}`)
}

export function getKnowledgeCategories() {
  return get<KnowledgeCategory[]>('/knowledge/categories')
}

const CATEGORY_NAMES: Record<string, string> = {
  industry: '行业规范',
  safety: '安全知识',
  equipment: '设备操作',
}

export function categoryName(key?: string): string {
  if (!key) return '-'
  return CATEGORY_NAMES[key] || key
}

export function summaryOf(content?: string, len = 50): string {
  if (!content) return ''
  const text = content.replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim()
  return text.length > len ? text.slice(0, len) + '...' : text
}
