/**
 * 应用状态管理模块
 * 管理应用全局状态、配置、系统信息等
 */

import { defineStore } from 'pinia'
import { APP_CONFIG } from '@/common/config'

export const useAppStore = defineStore('app', {
  state: () => ({
    // 应用信息
    appInfo: {
      name: APP_CONFIG.name,
      version: APP_CONFIG.version,
      description: APP_CONFIG.description
    },
    
    // 系统信息
    systemInfo: null,
    
    // 网络状态
    networkType: 'unknown',
    isOnline: true,
    
    // 应用状态
    isLoading: false,
    loadingText: '加载中...',
    
    // 主题设置
    theme: 'light',
    
    // 语言设置
    language: 'zh-CN',
    
    // 页面栈信息
    pageStack: [],
    
    // 全局配置
    globalConfig: {
      showTabBar: true,
      enablePullRefresh: true,
      enableReachBottom: true,
      backgroundColor: '#f5f5f5'
    },
    
    // 缓存管理
    cache: {
      maxSize: APP_CONFIG.cache.maxSize,
      currentSize: 0,
      items: new Map()
    },
    
    // 错误信息
    errors: [],
    
    // 通知消息
    notifications: [],
    
    // 更新信息
    updateInfo: {
      hasUpdate: false,
      version: null,
      description: null,
      forceUpdate: false
    }
  }),

  getters: {
    // 获取当前页面
    currentPage: (state) => {
      const pages = getCurrentPages()
      return pages[pages.length - 1]
    },
    
    // 获取页面栈深度
    pageStackDepth: (state) => {
      return getCurrentPages().length
    },
    
    // 检查是否为首页
    isHomePage: (state) => {
      const pages = getCurrentPages()
      return pages.length === 1
    },
    
    // 获取设备信息
    deviceInfo: (state) => {
      if (!state.systemInfo) return null
      
      return {
        platform: state.systemInfo.platform,
        system: state.systemInfo.system,
        model: state.systemInfo.model,
        brand: state.systemInfo.brand,
        screenWidth: state.systemInfo.screenWidth,
        screenHeight: state.systemInfo.screenHeight,
        windowWidth: state.systemInfo.windowWidth,
        windowHeight: state.systemInfo.windowHeight,
        statusBarHeight: state.systemInfo.statusBarHeight,
        safeArea: state.systemInfo.safeArea
      }
    },
    
    // 检查是否为移动设备
    isMobile: (state) => {
      if (!state.systemInfo) return true
      return state.systemInfo.platform !== 'devtools'
    },
    
    // 检查是否为开发工具
    isDevTools: (state) => {
      if (!state.systemInfo) return false
      return state.systemInfo.platform === 'devtools'
    },
    
    // 获取缓存使用率
    cacheUsageRate: (state) => {
      return (state.cache.currentSize / state.cache.maxSize * 100).toFixed(2)
    },
    
    // 检查缓存是否已满
    isCacheFull: (state) => {
      return state.cache.currentSize >= state.cache.maxSize
    },
    
    // 获取未读通知数量
    unreadNotificationCount: (state) => {
      return state.notifications.filter(n => !n.read).length
    }
  },

  actions: {
    /**
     * 初始化应用
     */
    async initApp() {
      try {
        // 获取系统信息
        await this.getSystemInfo()
        
        // 获取网络状态
        await this.getNetworkType()
        
        // 监听网络状态变化
        this.watchNetworkStatus()
        
        // 检查应用更新
        await this.checkUpdate()
        
        console.log('应用初始化完成')
      } catch (error) {
        console.error('应用初始化失败:', error)
        this.addError('应用初始化失败', error)
      }
    },

    /**
     * 获取系统信息
     */
    async getSystemInfo() {
      try {
        const systemInfo = await new Promise((resolve, reject) => {
          uni.getSystemInfo({
            success: resolve,
            fail: reject
          })
        })
        
        this.systemInfo = systemInfo
        return systemInfo
      } catch (error) {
        console.error('获取系统信息失败:', error)
        throw error
      }
    },

    /**
     * 获取网络类型
     */
    async getNetworkType() {
      try {
        const networkInfo = await new Promise((resolve, reject) => {
          uni.getNetworkType({
            success: resolve,
            fail: reject
          })
        })
        
        this.networkType = networkInfo.networkType
        this.isOnline = networkInfo.networkType !== 'none'
        
        return networkInfo
      } catch (error) {
        console.error('获取网络状态失败:', error)
        throw error
      }
    },

    /**
     * 监听网络状态变化
     */
    watchNetworkStatus() {
      uni.onNetworkStatusChange((res) => {
        this.networkType = res.networkType
        this.isOnline = res.isConnected
        
        if (!res.isConnected) {
          this.showToast('网络连接已断开', 'error')
        } else {
          this.showToast('网络连接已恢复', 'success')
        }
      })
    },

    /**
     * 显示加载状态
     * @param {string} text 加载文本
     */
    showLoading(text = '加载中...') {
      this.isLoading = true
      this.loadingText = text
      
      uni.showLoading({
        title: text,
        mask: true
      })
    },

    /**
     * 隐藏加载状态
     */
    hideLoading() {
      this.isLoading = false
      uni.hideLoading()
    },

    /**
     * 显示提示消息
     * @param {string} title 提示内容
     * @param {string} icon 图标类型
     * @param {number} duration 显示时长
     */
    showToast(title, icon = 'none', duration = 2000) {
      uni.showToast({
        title,
        icon,
        duration,
        mask: false
      })
    },

    /**
     * 显示模态对话框
     * @param {Object} options 对话框选项
     */
    async showModal(options) {
      const defaultOptions = {
        title: '提示',
        content: '',
        showCancel: true,
        cancelText: '取消',
        confirmText: '确定'
      }
      
      return new Promise((resolve) => {
        uni.showModal({
          ...defaultOptions,
          ...options,
          success: resolve,
          fail: resolve
        })
      })
    },

    /**
     * 设置主题
     * @param {string} theme 主题名称
     */
    setTheme(theme) {
      this.theme = theme
      
      // 应用主题样式
      const themeClass = `theme-${theme}`
      const body = document.body || document.documentElement
      
      // 移除旧主题类
      body.classList.remove('theme-light', 'theme-dark')
      // 添加新主题类
      body.classList.add(themeClass)
      
      // 保存到本地存储
      uni.setStorageSync('app-theme', theme)
    },

    /**
     * 设置语言
     * @param {string} language 语言代码
     */
    setLanguage(language) {
      this.language = language
      
      // 保存到本地存储
      uni.setStorageSync('app-language', language)
    },

    /**
     * 更新页面栈信息
     */
    updatePageStack() {
      const pages = getCurrentPages()
      this.pageStack = pages.map(page => ({
        route: page.route,
        options: page.options
      }))
    },

    /**
     * 添加缓存项
     * @param {string} key 缓存键
     * @param {any} value 缓存值
     * @param {number} expire 过期时间（毫秒）
     */
    setCache(key, value, expire = APP_CONFIG.cache.defaultExpire) {
      const item = {
        value,
        expire: Date.now() + expire,
        size: JSON.stringify(value).length
      }
      
      // 检查缓存空间
      if (this.cache.currentSize + item.size > this.cache.maxSize) {
        this.clearExpiredCache()
        
        // 如果还是不够空间，清除最旧的缓存
        if (this.cache.currentSize + item.size > this.cache.maxSize) {
          this.clearOldestCache()
        }
      }
      
      // 如果已存在，先移除旧的
      if (this.cache.items.has(key)) {
        const oldItem = this.cache.items.get(key)
        this.cache.currentSize -= oldItem.size
      }
      
      // 添加新缓存
      this.cache.items.set(key, item)
      this.cache.currentSize += item.size
    },

    /**
     * 获取缓存项
     * @param {string} key 缓存键
     */
    getCache(key) {
      const item = this.cache.items.get(key)
      
      if (!item) return null
      
      // 检查是否过期
      if (Date.now() > item.expire) {
        this.removeCache(key)
        return null
      }
      
      return item.value
    },

    /**
     * 移除缓存项
     * @param {string} key 缓存键
     */
    removeCache(key) {
      const item = this.cache.items.get(key)
      if (item) {
        this.cache.items.delete(key)
        this.cache.currentSize -= item.size
      }
    },

    /**
     * 清除过期缓存
     */
    clearExpiredCache() {
      const now = Date.now()
      const expiredKeys = []
      
      for (const [key, item] of this.cache.items) {
        if (now > item.expire) {
          expiredKeys.push(key)
        }
      }
      
      expiredKeys.forEach(key => this.removeCache(key))
    },

    /**
     * 清除最旧的缓存
     */
    clearOldestCache() {
      if (this.cache.items.size === 0) return
      
      const oldestKey = this.cache.items.keys().next().value
      this.removeCache(oldestKey)
    },

    /**
     * 清除所有缓存
     */
    clearAllCache() {
      this.cache.items.clear()
      this.cache.currentSize = 0
    },

    /**
     * 添加错误信息
     * @param {string} message 错误消息
     * @param {Error} error 错误对象
     */
    addError(message, error = null) {
      const errorInfo = {
        id: Date.now(),
        message,
        error: error ? error.toString() : null,
        stack: error ? error.stack : null,
        timestamp: new Date().toISOString(),
        url: this.currentPage?.route || 'unknown'
      }
      
      this.errors.unshift(errorInfo)
      
      // 限制错误数量
      if (this.errors.length > 100) {
        this.errors = this.errors.slice(0, 100)
      }
      
      console.error('应用错误:', errorInfo)
    },

    /**
     * 清除错误信息
     */
    clearErrors() {
      this.errors = []
    },

    /**
     * 添加通知
     * @param {Object} notification 通知对象
     */
    addNotification(notification) {
      const notificationInfo = {
        id: Date.now(),
        title: notification.title,
        content: notification.content,
        type: notification.type || 'info',
        read: false,
        timestamp: new Date().toISOString(),
        ...notification
      }
      
      this.notifications.unshift(notificationInfo)
      
      // 限制通知数量
      if (this.notifications.length > 50) {
        this.notifications = this.notifications.slice(0, 50)
      }
    },

    /**
     * 标记通知为已读
     * @param {number} id 通知ID
     */
    markNotificationAsRead(id) {
      const notification = this.notifications.find(n => n.id === id)
      if (notification) {
        notification.read = true
      }
    },

    /**
     * 清除通知
     * @param {number} id 通知ID
     */
    removeNotification(id) {
      const index = this.notifications.findIndex(n => n.id === id)
      if (index > -1) {
        this.notifications.splice(index, 1)
      }
    },

    /**
     * 清除所有通知
     */
    clearNotifications() {
      this.notifications = []
    },

    /**
     * 检查应用更新
     */
    async checkUpdate() {
      try {
        // #ifdef MP-WEIXIN
        const updateManager = uni.getUpdateManager()
        
        updateManager.onCheckForUpdate((res) => {
          if (res.hasUpdate) {
            this.updateInfo.hasUpdate = true
            console.log('发现新版本')
          }
        })
        
        updateManager.onUpdateReady(() => {
          this.showModal({
            title: '更新提示',
            content: '新版本已准备好，是否重启应用？',
            success: (res) => {
              if (res.confirm) {
                updateManager.applyUpdate()
              }
            }
          })
        })
        
        updateManager.onUpdateFailed(() => {
          this.showToast('更新失败，请稍后重试', 'error')
        })
        // #endif
      } catch (error) {
        console.error('检查更新失败:', error)
      }
    },

    /**
     * 重置应用状态
     */
    resetApp() {
      this.$reset()
      this.clearAllCache()
      this.clearErrors()
      this.clearNotifications()
    }
  },

  // 持久化配置
  persist: {
    key: 'app-store',
    storage: {
      getItem: (key) => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
      removeItem: (key) => uni.removeStorageSync(key)
    },
    paths: ['theme', 'language', 'globalConfig']
  }
})