// stores/app.js - 应用全局状态管理
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    // 系统信息
    systemInfo: {},
    
    // 网络状态
    networkType: 'unknown',
    isOnline: true,
    
    // 应用配置
    config: {
      theme: 'light',
      language: 'zh-CN'
    },
    
    // 加载状态
    globalLoading: false,
    
    // 错误信息
    errors: [],
    
    // 通知消息
    notifications: [],
    
    // 搜索历史
    searchHistory: []
  }),
  
  getters: {
    // 是否为暗黑主题
    isDarkTheme: (state) => state.config.theme === 'dark',
    
    // 未读通知数量
    unreadNotificationCount: (state) => state.notifications.filter(n => !n.read).length,
    
    // 最近搜索记录（前10条）
    recentSearches: (state) => state.searchHistory.slice(0, 10)
  },
  
  actions: {
    /**
     * 初始化应用
     */
    async initApp() {
      try {
        // 获取系统信息
        const systemInfo = uni.getSystemInfoSync()
        this.systemInfo = systemInfo
        
        // 获取网络类型
        const networkInfo = await uni.getNetworkType()
        this.networkType = networkInfo.networkType
        this.isOnline = networkInfo.networkType !== 'none'
        
        // 加载本地配置
        this.loadConfig()
        
        // 加载搜索历史
        this.loadSearchHistory()
        
        console.log('应用初始化完成:', {
          systemInfo: this.systemInfo,
          networkType: this.networkType,
          config: this.config
        })
      } catch (error) {
        console.error('应用初始化失败:', error)
      }
    },
    
    /**
     * 加载配置
     */
    loadConfig() {
      try {
        const config = uni.getStorageSync('app_config')
        if (config) {
          this.config = { ...this.config, ...config }
        }
      } catch (error) {
        console.error('加载配置失败:', error)
      }
    },
    
    /**
     * 保存配置
     */
    saveConfig() {
      try {
        uni.setStorageSync('app_config', this.config)
      } catch (error) {
        console.error('保存配置失败:', error)
      }
    },
    
    /**
     * 设置主题
     */
    setTheme(theme) {
      this.config.theme = theme
      this.saveConfig()
    },
    
    /**
     * 设置语言
     */
    setLanguage(language) {
      this.config.language = language
      this.saveConfig()
    },
    
    /**
     * 设置全局加载状态
     */
    setGlobalLoading(loading) {
      this.globalLoading = loading
    },
    
    /**
     * 添加错误信息
     */
    addError(error) {
      const errorItem = {
        id: Date.now(),
        message: error.message || error,
        timestamp: new Date(),
        type: error.type || 'error'
      }
      this.errors.unshift(errorItem)
      
      // 只保留最近50条错误
      if (this.errors.length > 50) {
        this.errors = this.errors.slice(0, 50)
      }
    },
    
    /**
     * 清除错误信息
     */
    clearErrors() {
      this.errors = []
    },
    
    /**
     * 添加通知
     */
    addNotification(notification) {
      const notificationItem = {
        id: Date.now(),
        title: notification.title,
        message: notification.message,
        type: notification.type || 'info',
        read: false,
        timestamp: new Date()
      }
      this.notifications.unshift(notificationItem)
      
      // 只保留最近100条通知
      if (this.notifications.length > 100) {
        this.notifications = this.notifications.slice(0, 100)
      }
    },
    
    /**
     * 标记通知为已读
     */
    markNotificationAsRead(id) {
      const notification = this.notifications.find(n => n.id === id)
      if (notification) {
        notification.read = true
      }
    },
    
    /**
     * 标记所有通知为已读
     */
    markAllNotificationsAsRead() {
      this.notifications.forEach(n => n.read = true)
    },
    
    /**
     * 清除通知
     */
    clearNotifications() {
      this.notifications = []
    },
    
    /**
     * 加载搜索历史
     */
    loadSearchHistory() {
      try {
        const history = uni.getStorageSync('search_history')
        if (history) {
          this.searchHistory = history
        }
      } catch (error) {
        console.error('加载搜索历史失败:', error)
      }
    },
    
    /**
     * 保存搜索历史
     */
    saveSearchHistory() {
      try {
        uni.setStorageSync('search_history', this.searchHistory)
      } catch (error) {
        console.error('保存搜索历史失败:', error)
      }
    },
    
    /**
     * 添加搜索记录
     */
    addSearchHistory(keyword) {
      if (!keyword || !keyword.trim()) return
      
      keyword = keyword.trim()
      
      // 移除已存在的相同关键词
      this.searchHistory = this.searchHistory.filter(item => item !== keyword)
      
      // 添加到开头
      this.searchHistory.unshift(keyword)
      
      // 只保留最近20条
      if (this.searchHistory.length > 20) {
        this.searchHistory = this.searchHistory.slice(0, 20)
      }
      
      this.saveSearchHistory()
    },
    
    /**
     * 清除搜索历史
     */
    clearSearchHistory() {
      this.searchHistory = []
      this.saveSearchHistory()
    },
    
    /**
     * 更新网络状态
     */
    updateNetworkStatus(networkType) {
      this.networkType = networkType
      this.isOnline = networkType !== 'none'
      
      if (!this.isOnline) {
        this.addNotification({
          title: '网络连接',
          message: '网络连接已断开，请检查网络设置',
          type: 'warning'
        })
      }
    },
    
    /**
     * 监听网络状态变化
     */
    watchNetworkStatus() {
      uni.onNetworkStatusChange((res) => {
        this.updateNetworkStatus(res.networkType)
      })
    }
  }
})