// 本地存储工具函数

// 存储键名常量
const STORAGE_KEYS = {
  LLM_CONFIGS: 'llm_configs',
  SENSITIVE_WORDS: 'sensitive_words',
  SENSITIVE_PERSONS: 'sensitive_persons',
  TEXT_PROCESS_CONFIG: 'text_process_config',
  LLM_FEATURES: 'llm_features',
}

// 生成唯一ID
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2)
}

// 获取当前时间戳
const getCurrentTime = () => {
  return new Date().toISOString()
}

// 通用存储操作
const storage = {
  // 获取数据
  get<T>(key: string, defaultValue: T): T {
    try {
      const item = localStorage.getItem(key)
      return item ? JSON.parse(item) : defaultValue
    } catch (error) {
      console.error(`Error getting data from localStorage for key ${key}:`, error)
      return defaultValue
    }
  },

  // 设置数据
  set<T>(key: string, value: T): void {
    try {
      localStorage.setItem(key, JSON.stringify(value))
    } catch (error) {
      console.error(`Error setting data to localStorage for key ${key}:`, error)
    }
  },

  // 删除数据
  remove(key: string): void {
    try {
      localStorage.removeItem(key)
    } catch (error) {
      console.error(`Error removing data from localStorage for key ${key}:`, error)
    }
  },
}

// 大模型配置相关操作
export const llmConfigStorage = {
  // 获取所有配置
  getAll() {
    return storage.get(STORAGE_KEYS.LLM_CONFIGS, [] as any[])
  },

  // 根据ID获取配置
  getById(id: string) {
    const configs = this.getAll()
    return configs.find((config: any) => config.id === id)
  },

  // 创建配置
  create(config: any) {
    const configs = this.getAll()
    const newConfig = {
      ...config,
      id: generateId(),
      created_time: getCurrentTime(),
      updated_time: getCurrentTime(),
    }
    configs.push(newConfig)
    storage.set(STORAGE_KEYS.LLM_CONFIGS, configs)
    return newConfig
  },

  // 更新配置
  update(id: string, updates: any) {
    const configs = this.getAll()
    const index = configs.findIndex((config: any) => config.id === id)
    if (index !== -1) {
      configs[index] = {
        ...configs[index],
        ...updates,
        updated_time: getCurrentTime(),
      }
      storage.set(STORAGE_KEYS.LLM_CONFIGS, configs)
      return configs[index]
    }
    return null
  },

  // 删除配置
  delete(id: string) {
    const configs = this.getAll()
    const filteredConfigs = configs.filter((config: any) => config.id !== id)
    storage.set(STORAGE_KEYS.LLM_CONFIGS, filteredConfigs)
    return true
  },

  // 搜索配置
  search(params: { name?: string; provider?: string; is_enabled?: string }) {
    let configs = this.getAll()

    if (params.name) {
      configs = configs.filter((config: any) => config.name.toLowerCase().includes(params.name!.toLowerCase()))
    }

    if (params.provider) {
      configs = configs.filter((config: any) => config.provider === params.provider)
    }

    if (params.is_enabled) {
      const enabled = params.is_enabled === 'true'
      configs = configs.filter((config: any) => config.is_enabled === enabled)
    }

    return configs
  },
}

// 敏感词相关操作
export const sensitiveWordStorage = {
  // 获取所有敏感词
  getAll() {
    return storage.get(STORAGE_KEYS.SENSITIVE_WORDS, [] as any[])
  },

  // 根据ID获取敏感词
  getById(id: string) {
    const words = this.getAll()
    return words.find((word: any) => word.id === id)
  },

  // 创建敏感词
  create(word: any) {
    const words = this.getAll()
    const newWord = {
      ...word,
      id: generateId(),
      created_time: getCurrentTime(),
    }
    words.push(newWord)
    storage.set(STORAGE_KEYS.SENSITIVE_WORDS, words)
    return newWord
  },

  // 更新敏感词
  update(id: string, updates: any) {
    const words = this.getAll()
    const index = words.findIndex((word: any) => word.id === id)
    if (index !== -1) {
      words[index] = { ...words[index], ...updates }
      storage.set(STORAGE_KEYS.SENSITIVE_WORDS, words)
      return words[index]
    }
    return null
  },

  // 删除敏感词
  delete(id: string) {
    const words = this.getAll()
    const filteredWords = words.filter((word: any) => word.id !== id)
    storage.set(STORAGE_KEYS.SENSITIVE_WORDS, filteredWords)
    return true
  },

  // 搜索敏感词
  search(params: { word?: string; level?: string }) {
    let words = this.getAll()

    if (params.word) {
      words = words.filter((word: any) => word.word.toLowerCase().includes(params.word!.toLowerCase()))
    }

    if (params.level) {
      words = words.filter((word: any) => word.level === params.level)
    }

    return words
  },

  // 批量导入
  batchImport(words: string[], level: string) {
    const existingWords = this.getAll()
    const newWords = words.map((word) => ({
      id: generateId(),
      word: word.trim(),
      level,
      replacement: '***',
      is_enabled: true,
      created_time: getCurrentTime(),
    }))

    const allWords = [...existingWords, ...newWords]
    storage.set(STORAGE_KEYS.SENSITIVE_WORDS, allWords)
    return newWords
  },
}

// 敏感人物相关操作
export const sensitivePersonStorage = {
  // 获取所有敏感人物
  getAll() {
    return storage.get(STORAGE_KEYS.SENSITIVE_PERSONS, [] as any[])
  },

  // 根据ID获取敏感人物
  getById(id: string) {
    const persons = this.getAll()
    return persons.find((person: any) => person.id === id)
  },

  // 创建敏感人物
  create(person: any) {
    const persons = this.getAll()
    const newPerson = {
      ...person,
      id: generateId(),
      created_time: getCurrentTime(),
    }
    persons.push(newPerson)
    storage.set(STORAGE_KEYS.SENSITIVE_PERSONS, persons)
    return newPerson
  },

  // 更新敏感人物
  update(id: string, updates: any) {
    const persons = this.getAll()
    const index = persons.findIndex((person: any) => person.id === id)
    if (index !== -1) {
      persons[index] = { ...persons[index], ...updates }
      storage.set(STORAGE_KEYS.SENSITIVE_PERSONS, persons)
      return persons[index]
    }
    return null
  },

  // 删除敏感人物
  delete(id: string) {
    const persons = this.getAll()
    const filteredPersons = persons.filter((person: any) => person.id !== id)
    storage.set(STORAGE_KEYS.SENSITIVE_PERSONS, filteredPersons)
    return true
  },

  // 搜索敏感人物
  search(params: { name?: string; level?: string }) {
    let persons = this.getAll()

    if (params.name) {
      persons = persons.filter(
        (person: any) =>
          person.name.toLowerCase().includes(params.name!.toLowerCase()) ||
          person.aliases.some((alias: string) => alias.toLowerCase().includes(params.name!.toLowerCase()))
      )
    }

    if (params.level) {
      persons = persons.filter((person: any) => person.level === params.level)
    }

    return persons
  },
}

// 文本处理配置相关操作
export const textProcessStorage = {
  // 获取配置
  get() {
    return storage.get(STORAGE_KEYS.TEXT_PROCESS_CONFIG, {
      enable_ideology_check: true,
      enable_sensitive_word_filter: true,
      enable_sensitive_person_filter: true,
      auto_replace_sensitive_words: true,
      custom_replacement: '***',
    })
  },

  // 更新配置
  update(config: any) {
    storage.set(STORAGE_KEYS.TEXT_PROCESS_CONFIG, config)
    return config
  },
}

// 大模型功能配置相关操作
export const llmFeatureStorage = {
  // 获取所有功能
  getAll() {
    return storage.get(STORAGE_KEYS.LLM_FEATURES, [] as any[])
  },

  // 根据大模型ID获取功能
  getByLLMId(llmId: string) {
    const features = this.getAll()
    return features.filter((feature: any) => feature.llm_id === llmId)
  },

  // 创建功能
  create(feature: any) {
    const features = this.getAll()
    const newFeature = {
      ...feature,
      id: generateId(),
      created_time: getCurrentTime(),
      updated_time: getCurrentTime(),
    }
    features.push(newFeature)
    storage.set(STORAGE_KEYS.LLM_FEATURES, features)
    return newFeature
  },

  // 更新功能
  update(id: string, updates: any) {
    const features = this.getAll()
    const index = features.findIndex((feature: any) => feature.id === id)
    if (index !== -1) {
      features[index] = {
        ...features[index],
        ...updates,
        updated_time: getCurrentTime(),
      }
      storage.set(STORAGE_KEYS.LLM_FEATURES, features)
      return features[index]
    }
    return null
  },

  // 删除功能
  delete(id: string) {
    const features = this.getAll()
    const filteredFeatures = features.filter((feature: any) => feature.id !== id)
    storage.set(STORAGE_KEYS.LLM_FEATURES, filteredFeatures)
    return true
  },

  // 获取可用功能模板
  getAvailableFeatures() {
    return [
      {
        code: 'text_generation',
        name: '文本生成',
        description: '基于输入生成文本内容',
      },
      {
        code: 'text_summarization',
        name: '文本摘要',
        description: '生成文本的摘要内容',
      },
      {
        code: 'text_translation',
        name: '文本翻译',
        description: '将文本翻译为其他语言',
      },
      {
        code: 'text_analysis',
        name: '文本分析',
        description: '分析文本的情感、主题等',
      },
      {
        code: 'question_answering',
        name: '问答系统',
        description: '回答用户提出的问题',
      },
    ]
  },
}

// 导出所有存储操作
export default {
  llmConfigStorage,
  sensitiveWordStorage,
  sensitivePersonStorage,
  textProcessStorage,
  llmFeatureStorage,
}
