import { login, logout, getInfo, refreshToken, getPhoneCode, isLogin, isAdmin } from '@/api/login'
import { getToken, setToken, setExpiresIn, removeToken } from '@/utils/auth'

// 更严格的手机号和邮箱正则表达式
const phonePattern = /^(\+86)?1[3-9]\d{9}$/ // 支持前缀 +86
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/

// 构建 payload 函数
const buildPayload = ({ loginMethod, username, password, uuid, code, mobile, verificationCode, phoneUuid }) => {
    let loginType = ''
    if (loginMethod === 'mobile') {
        loginType = phonePattern.test(mobile.trim())
            ? 'PHONE_OTP'
            : emailPattern.test(mobile.trim())
            ? 'EMAIL_OTP'
            : 'PHONE_OTP'
        return {
            username: mobile.trim(),
            verificationCode,
            uuid,
            code,
            loginType,
            phoneUuid
        }
    } else {
        loginType = phonePattern.test(username.trim())
            ? 'PHONE_PASSWORD'
            : emailPattern.test(username.trim())
            ? 'EMAIL_PASSWORD'
            : 'USERNAME_PASSWORD'
        return {
            username: username.trim(),
            password,
            verificationCode,
            uuid,
            code,
            loginType,
            phoneUuid
        }
    }
}

const user = {
    state: {
        token: getToken(),
        id: '',
        name: '',
        avatar: '',
        roles: [],
        permissions: []
    },

    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
        },
        SET_EXPIRES_IN(state, time) {
            state.expires_in = time
        },
        SET_ID(state, id) {
            state.id = id
        },
        SET_NAME(state, name) {
            state.name = name
        },
        SET_AVATAR(state, avatar) {
            state.avatar = avatar
        },
        SET_ROLES(state, roles) {
            state.roles = roles
        },
        SET_PERMISSIONS(state, permissions) {
            state.permissions = permissions
        }
    },

    actions: {
        IsLogin({ commit }, userInfo) {
            const payload = buildPayload(userInfo)
            return isLogin(payload)
                .then(res => res)
                .catch(error => Promise.reject(error))
        },
        IsAdmin({ commit }, userInfo) {
            const payload = buildPayload(userInfo)
            return isAdmin(payload)
                .then(res => res)
                .catch(error => Promise.reject(error))
        },

        // 登录
        Login({ commit }, userInfo) {
            const payload = buildPayload(userInfo)
            return login(payload)
                .then(res => {
                    const { access_token, expires_in } = res.data
                    setToken(access_token)
                    commit('SET_TOKEN', access_token)
                    setExpiresIn(expires_in)
                    commit('SET_EXPIRES_IN', expires_in)
                    return res
                })
                .catch(error => Promise.reject(error))
        },

        // 获取手机验证码
        GetPhoneCode({ commit }, userInfo) {
            const payload = {
                username: userInfo.mobile.trim(),
                uuid: userInfo.uuid,
                code: userInfo.code,
                phoneUuid: userInfo.phoneUuid,
                verificationCodeType: userInfo.mobileCodeType
            }
            return getPhoneCode(payload)
                .then(res => res)
                .catch(error => Promise.reject(error))
        },

        // 获取用户信息
        GetInfo({ commit }) {
            return getInfo()
                .then(res => {
                    const user = res.user
                    const avatar = user.avatar ? user.avatar : require('@/assets/images/profile.jpg')
                    commit('SET_ROLES', res.roles && res.roles.length > 0 ? res.roles : ['ROLE_DEFAULT'])
                    commit('SET_PERMISSIONS', res.permissions)
                    commit('SET_ID', user.userId)
                    commit('SET_NAME', user.userName)
                    commit('SET_AVATAR', avatar)

                    // 存取用户的userId
                    sessionStorage.setItem('userId', res.user?.userId)
                    sessionStorage.setItem('deptName', res.user?.dept?.deptName)
                    sessionStorage.setItem('userName', res.user?.userName)
                    return res
                })
                .catch(error => Promise.reject(error))
        },

        // 刷新 token
        RefreshToken({ commit, state }) {
            return refreshToken(state.token)
                .then(res => {
                    const expiresIn = res.data
                    setExpiresIn(expiresIn)
                    commit('SET_EXPIRES_IN', expiresIn)
                })
                .catch(error => Promise.reject(error))
        },

        // 退出登录
        LogOut({ commit, state }) {
            return logout(state.token)
                .then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    commit('SET_PERMISSIONS', [])
                    removeToken()
                })
                .catch(error => Promise.reject(error))
        },

        // 前端退出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user
