// 日志工具模块
import dayjs from 'dayjs'

type LogLevel = 'debug' | 'info' | 'warn' | 'error'

interface LogEntry {
  timestamp: string
  level: LogLevel
  category: string
  message: string
  data?: any
  duration?: number
}

// 日志存储（用于开发面板显示）
const logStore: LogEntry[] = []
const MAX_LOGS = 100

// 颜色配置
const levelColors: Record<LogLevel, string> = {
  debug: '#909399',
  info: '#409eff',
  warn: '#e6a23c',
  error: '#f56c6c',
}

const levelIcons: Record<LogLevel, string> = {
  debug: '🔍',
  info: 'ℹ️',
  warn: '⚠️',
  error: '❌',
}

// 格式化日志
const formatLog = (level: LogLevel, category: string, message: string, data?: any): LogEntry => {
  return {
    timestamp: dayjs().format('HH:mm:ss.SSS'),
    level,
    category,
    message,
    data,
  }
}

// 添加日志到存储
const addToStore = (entry: LogEntry) => {
  logStore.unshift(entry)
  if (logStore.length > MAX_LOGS) {
    logStore.pop()
  }
}

// 输出到控制台
const printToConsole = (entry: LogEntry) => {
  if (!import.meta.env.DEV) return
  
  const color = levelColors[entry.level]
  const icon = levelIcons[entry.level]
  const prefix = `${icon} [${entry.timestamp}] [${entry.category}]`
  
  const style = `color: ${color}; font-weight: bold;`
  
  if (entry.data !== undefined) {
    console.groupCollapsed(`%c${prefix} ${entry.message}`, style)
    console.log(entry.data)
    if (entry.duration !== undefined) {
      console.log(`⏱️ Duration: ${entry.duration}ms`)
    }
    console.groupEnd()
  } else {
    console.log(`%c${prefix} ${entry.message}`, style)
  }
}

// 创建日志记录器
export const createLogger = (category: string) => {
  return {
    debug: (message: string, data?: any) => {
      const entry = formatLog('debug', category, message, data)
      addToStore(entry)
      printToConsole(entry)
    },
    
    info: (message: string, data?: any) => {
      const entry = formatLog('info', category, message, data)
      addToStore(entry)
      printToConsole(entry)
    },
    
    warn: (message: string, data?: any) => {
      const entry = formatLog('warn', category, message, data)
      addToStore(entry)
      printToConsole(entry)
    },
    
    error: (message: string, data?: any) => {
      const entry = formatLog('error', category, message, data)
      addToStore(entry)
      printToConsole(entry)
    },
    
    // 计时日志
    time: (label: string) => {
      const startTime = performance.now()
      return {
        end: (message?: string, data?: any) => {
          const duration = Math.round(performance.now() - startTime)
          const entry = formatLog('info', category, message || label, data)
          entry.duration = duration
          addToStore(entry)
          printToConsole(entry)
          return duration
        },
      }
    },
  }
}

// API 请求日志器
export const apiLogger = createLogger('API')

// 路由日志器
export const routerLogger = createLogger('Router')

// 状态日志器
export const storeLogger = createLogger('Store')

// 获取日志存储（供开发面板使用）
export const getLogs = () => [...logStore]

// 清空日志
export const clearLogs = () => {
  logStore.length = 0
}

// 导出默认日志器
export const logger = createLogger('App')

export default logger

