import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  // phoneLogin as phoneLoginApi,
  getUserInfo as getUserInfoApi,
  // psdLogin as psdLoginApi,
  logout as logoutApi,
  getCsInfo as getCsInfoApi,
  bindRegId,
  userInfoPermitApi,
  // updatePwdByPhone,
} from '@/api'
// import type { smsLoginType, accountLoginType, updatePasswordType } from '@/api';
// import defaultAvatar from "@/static/default_avatar.png";
import { setCache, getCache } from '@/utils'
import { global } from '@/store'
import router from '@/router/router'
import db from '@/utils/db'

export const user = defineStore('user', () => {
  const userInfo = ref(db.get('userInfo') || ({} as any))
  const csInfo = ref(db.get('csInfo') || {})
  const token = ref(db.get('token') || '')
  const { getDicts } = global()

  const afterLogin = async () => {
    await Promise.allSettled([getUserInfo(), getDicts()])
    // getCsInfo(); // 需等待用户信息加载完毕
  }

  const logout = async () => {
    // #ifdef APP-PLUS
    if (db.get('registerID')) {
      await bindRegId({
        registrationId: db.get('registerID'),
        type: 2,
      })
    }
    // #endif
    await logoutApi()
    clear()
    router.reLaunch('/pages/login/index')
  }

  const getUserInfo = async () => {
    const res = await getUserInfoApi()
    userInfo.value = res.data
    db.set('userInfo', res.data)
    getUserInfoPermit()
    return res.data
  }
  // 当前登录用户是否管理员身份
  async function getUserInfoPermit() {
    const { data } = await userInfoPermitApi()
    db.set('userAdmin', data)
  }
  const getCsInfo = async () => {
    const res = await getCsInfoApi(userInfo.value.id)
    csInfo.value = res.data
    db.set('csInfo', res.data)
    return res.data
  }

  const clear = async () => {
    token.value = ''
    userInfo.value = {}
    csInfo.value = {}
    await db.clear()
  }

  const setToken = (data: string) => {
    token.value = data
    db.set('token', data)
  }

  return {
    userInfo,
    csInfo,
    token,
    // setInfo,
    // login,
    // phoneLogin,
    // accordLogin,
    // updatePassword,
    getUserInfo,
    getCsInfo,
    logout,
    clear,
    afterLogin,
    setToken,
  }
})
