// 应用状态管理
import { defineStore } from 'pinia'

export const useAppStore = defineStore('app', {
  state: () => ({
    // 登录状态
    isLoggedIn: !!uni.getStorageSync('token'),
    
    // 连接状态
    isOnline: true,
    
    // 同步状态
    syncStatus: 'synced', // synced, syncing, syncFailed
    
    // 离线模式
    isOfflineMode: false,
    
    // 最后同步时间
    lastSyncTime: uni.getStorageSync('lastSyncTime') || null
  }),
  
  getters: {
    // 检查是否为离线用户
    isOfflineUser: (state) => {
      const userInfo = uni.getStorageSync('userInfo') || {}
      return userInfo.isOffline === true || userInfo.userId === 'local_user'
    },
    
    // 检查OCR功能是否可用
    isOcrAvailable: (state) => {
      return !state.isOfflineMode && state.isOnline
    }
  },
  
  actions: {
    // 设置登录状态
    setLoggedIn(status) {
      this.isLoggedIn = status
    },
    
    // 设置连接状态
    setOnline(status) {
      this.isOnline = status
    },
    
    // 设置同步状态
    setSyncStatus(status) {
      this.syncStatus = status
    },
    
    // 设置离线模式
    setOfflineMode(status) {
      this.isOfflineMode = status
    },
    
    // 设置最后同步时间
    setLastSyncTime(time) {
      this.lastSyncTime = time
      uni.setStorageSync('lastSyncTime', time)
    },
    
    // 初始化应用状态
    initAppStatus() {
      // 检查登录状态
      this.isLoggedIn = !!uni.getStorageSync('token')
      
      // 检查是否为离线用户
      const userInfo = uni.getStorageSync('userInfo') || {}
      this.isOfflineMode = userInfo.isOffline === true || userInfo.userId === 'local_user'
      
      // 检查网络状态
      uni.getNetworkType({
        success: (res) => {
          this.isOnline = res.networkType !== 'none'
        },
        fail: () => {
          this.isOnline = false
        }
      })
    },
    
    // 监听网络状态变化
    watchNetworkStatus() {
      uni.onNetworkStatusChange((res) => {
        this.isOnline = res.isConnected
      })
    }
  }
})
