import { login, logout, getInfo, signUp } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { serverLang, clientLang } from '@/utils/i18n'
import useAppStore from '@/store/modules/app'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      applyLanguage: [],
      userInfo: null,
      userExpired: false
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        const lang = serverLang()

        return new Promise((resolve, reject) => {
          login(username, password, code, uuid, lang).then(res => {
            setToken(res.data.token)
            this.token = res.data.token
            useAppStore().setShowBanner('1')
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 注册
      signUp(userInfo) {
        const username = userInfo.email.trim()
        const password = userInfo.password
        const first_name = userInfo.firstName.trim()
        const last_name = userInfo.lastName.trim()
        const country = userInfo.country
        const phone = userInfo.phone
        const phone_prefix = userInfo.phone_prefix
        const shareCode = userInfo.shareCode
        const lang = serverLang()
        const {utm_source, utm_medium, utm_content, utm_campaign, utm_blocka} = userInfo

        return new Promise((resolve, reject) => {
          signUp(username, password, first_name, last_name, country, lang, shareCode, phone, phone_prefix, utm_source, utm_medium, utm_content, utm_campaign, utm_blocka).then(res => {
            setToken(res.data.token)
            this.token = res.data.token
            useAppStore().setShowBanner('1')
            // 自动登录时设置用户信息已过期状态
            this.userExpired = true
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.data.loginUser
            let applyLanguage = res.data.applyLanguage
            if (!applyLanguage || !applyLanguage.length) {
              applyLanguage = ['en']
            } else {
              applyLanguage = Array.from(new Set(applyLanguage.map(i => clientLang(i))))
            }
            const avatar = (user.avatar == "" || user.avatar == null) ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.id
            this.name = user.name
            this.avatar = avatar
            this.applyLanguage = applyLanguage
            this.userInfo = user
            this.userExpired = false
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout(this.token).then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            this.applyLanguage = []
            this.userInfo = null
            removeToken()
            resolve()
          }).catch(error => {
            this.token = ''
            this.roles = []
            this.permissions = []
            this.applyLanguage = []
            this.userInfo = null
            removeToken()
            resolve()
          })
        })
      }
    }
  })

export default useUserStore
