import { defineStore } from 'pinia'
import { getToken, removeToken, setToken, getUserInfo as getStorageUserInfo, setUserInfo, removeUserInfo } from '@/utils/token.js'
import { getUserInfo, userLogin } from '@/api/user/index.js'
import { useToast } from '@/utils/modals/index.js'
// import defaultAvatar from '@/static/avatar.png'
// import router from '@/router'

// import storage from '@/utils/storages'

export const useUserStore = defineStore('app-user', {
  state () {
    return {
      userInfo: getStorageUserInfo(),
      token: getToken(),
    }
  },
  getters: {
    userId: state => state.userInfo?.userId,
    roleName: state => state.userInfo?.roleName ?? 'simple',
    username: state => state.userInfo?.username,
    resumed: state => !!state.resumeInfo.id,
  },
  actions: {
    async login () {
      return new Promise(async (resolve, reject) => {
        const { code } = await uni.login({
          provider: 'weixin',
        })
        const res = await userLogin({ code })
        if (res.code !== 200) {
          reject('自动登录失败')
        }
        if (res.user?.id) {
          this.setUserInfo(res.user)
          this.setToken(res.token)
          resolve(res.user)
        } else uni.getUserInfo({
          provider: 'weixin',
          success: ({ userInfo }) => {
            // 获取用户信息成功
            if (res.token) {
              this.setUserInfo(userInfo)
              this.setToken(res.token)
              resolve(userInfo)
            } else {
              useToast('微信登录失败！', {
                type: 'error',
                duration: 2 * 1000,
              })
              reject('登录失败!')
            }
          },
          fail: (err) => {
            useToast('微信登录失败，请先同意授权！', {
              type: 'error',
              duration: 2 * 1000,
            })
            this.removeToken()
            // 如果用户拒绝授权，可以引导用户打开授权设置页面
            if (err.errMsg === 'getUserInfo:fail auth deny') {
              this.openAuthSetting()
            }
            reject('登录失败')
          }
        })
      })
    },
    removeToken () {
      this.token = ''
      removeToken()
    },
    setToken (token) {
      this.token = token
      setToken(token)
    },
    removeUserInfo () {
      this.userInfo = {}
      removeUserInfo()
    },
    setUserInfo (userInfo = {}) {
      this.userInfo = userInfo
      setUserInfo(userInfo)
    },
    // 获取用户详情
    // async getUserInfo ({ params = {}, ...options } = {}) {
    //   const res = await getUserInfo(params, options)

    //   if (!res?.success) {
    //     throw new Error('获取用户信息失败')
    //   }

    //   if (!res?.data) {
    //     throw new Error('获取用户信息失败, 没有获取到数据')
    //   }

    //   const data = res.data
    //   this.userInfo = {
    //     ...data,
    //     userId: data.id,
    //     avatar: data.avatar || defaultAvatar,
    //     username: data.username,
    //   }

    //   return this.userInfo
    // },
    openAuthSetting () {
      uni.openSetting({
        success: function (res) {
          if (res.authSetting['scope.userInfo']) {
            // 用户开启了授权，重新调用 `uni.getUserInfo` 获取用户信息
            getUserInfo()
          }
        }
      })
    },
    logout ({ silenced = false, redirect = null } = {}) {
      this.removeToken()
      this.removeUserInfo()
      // this.userInfo = {}
      // this.resumeInfo = {}

      // if (!silenced) {
      //   router.replaceAll({
      //     force: true,
      //     path: '/login',
      //     query: {
      //       redirect,
      //     },
      //   })
      // }
    },
  },
})
