import { preferences } from '@kit.ArkData'
import { router } from '@kit.ArkUI'
import { Data } from '../models/LoginInfoModel'
import { ExpertData } from '../models/RequestDefaultModel'
import { BusinessError } from '@kit.BasicServicesKit'
import { logger } from '../utils/logger'
export interface HdUser {
  id: string
  username: string
  avatar: string
  token: string
  refreshToken: string
  nickName?: string
  totalTime?: number
  clockinNumbers?: number
}

export const AUTH_STORE_KEY = 'authStore'

class AuthStore {
  store: preferences.Preferences | null = null

  getStore() {
    if (!this.store) {
      this.store = preferences.getPreferencesSync(getContext(), { name: AUTH_STORE_KEY })
    }
    return this.store
  }

  async setUser(user: Data) {
    AppStorage.setOrCreate('user', user)
    await this.getStore().put(AUTH_STORE_KEY, JSON.stringify(user))
    await this.getStore().flush()
  }

  async updateUser(user: ExpertData) {
    AppStorage.setOrCreate('user', user)
    await this.getStore().put(AUTH_STORE_KEY, JSON.stringify(user))
    await this.getStore().flush()
  }

  async setPerfactUser(mobile:string,user:ExpertData) {
    AppStorage.setOrCreate('mobile', mobile)
    await this.getStore().put(mobile, JSON.stringify(user))
    await this.getStore().flush((err:BusinessError)=>{
      if (err) {
        console.error('保存失败',err.code,err.message)
      } else {
        console.info('保存成功',JSON.stringify(user))
      }
    })
  }

  async delUser() {
    AppStorage.setOrCreate('user', {})
    await this.getStore().put(AUTH_STORE_KEY, '{}')
    await this.getStore().flush()
  }

  initUser() {
    const json = this.getStore().getSync(AUTH_STORE_KEY, '{}') as string
    AppStorage.setOrCreate('user', JSON.parse(json))
  }

  getUser() {
    logger.info('个人资料initUser'+ (AppStorage.get<Data>('user') || {} as Data)+'');
    return AppStorage.get<Data>('user') || {} as Data
  }

  getPerfactUser(phone:string) {
    return AppStorage.get<ExpertData>(phone) || {} as ExpertData
  }

  checkAuth(options: router.RouterOptions | Function) {
    //   if (this.getUser().token) {
    //     if (typeof options === 'function') {
    //       options()
    //     } else {
    //       router.pushUrl(options)
    //     }
    //   } else {
    //     if (typeof options === 'function') {
    //       router.pushUrl({
    //         url: 'pages/LoginPage',
    //       })
    //     } else {
    //       const params = options.params as Record<string, string> || {}
    //       params.return_path = options.url
    //       router.pushUrl({
    //         url: 'pages/LoginPage',
    //         params: params
    //       })
    //     }
    //   }
  }
}

export const authStore = new AuthStore()