import { wechatAuthLogin, mobileLogin, getAccessToken } from '@/services/api/auth.js'
import { fetchMessageCount } from '@/services/api/notice.js'
import { wxLogin } from '@/common/auth.js'
import { setStorage, getStorage } from '@/common/storage.js'
import { objAssign } from '@/common/utils.js'

function initUserState() {
    const state = {
        // 用户信息
        headImgUrl: '',
        mobile: '',
        nickName: '',
        openId: '',
        userId: 0,
        userIdentity: -1, // 用户类型
        inviteUserId: '', // 分享者用户ID
        accessToken: '', // token
        hasLogin: false, // 用户是否登录
        notice_count: 0, // 消息通知数量
    }
    const userInfo = getStorage('USER_INFO')
    if (userInfo) {
        Object.assign(state, userInfo)
    }
    const accessToken = getStorage('ACCESS_TOKEN')
    if (accessToken) {
        state.accessToken = accessToken
    }
    return state
}

const state = initUserState()

console.log(state)

const mutations = {
    SET_USER_INFO: (state, userInfo) => {
        state.hasLogin = true
        objAssign(state, userInfo)
    },
    SET_INVITE_USER_ID: (state, id) => {
        state.inviteUserId = id
    },
    SET_ACCESS_TOKEN: (state, token) => {
        state.accessToken = token
    },
    SET_LOGINOUT: (state, logout) => {
        state.hasLogin = logout
    },
    SET_NOTICE_COUNT: (state, count) => {
        state.notice_count = count
    },
    SET_TABBAR_BADGE: (state, count) => {
        if (count >= 100) {
            return uni.setTabBarBadge({ index: 2, text: '99+' })
        }
        if (count > 0) {
            return uni.setTabBarBadge({ index: 2, text: count.toString() })
        }
        uni.removeTabBarBadge({ index: 2 })
    }
}

const actions = {
    // 微信自动登录
    async wxAutoLogin({ commit, state, dispatch }) {
        try {
            const code = await wxLogin() // 获取微信code
            const res = await wechatAuthLogin({ code }) // 微信自动登录
            const data = JSON.parse(res.data)
            commit('SET_USER_INFO', data)
            setStorage('USER_INFO', data)
            dispatch('getAccessToken') // 获取token
            commit('SET_LOGINOUT', true)
        } catch (e) {
            commit('SET_LOGINOUT', false)
            console.log(e)
            
        }
    },
    // 手机号注册登录
    async register({ commit }, resigterData) {
        try {
            const res = await mobileLogin(resigterData)
            const data = JSON.parse(res.data)
            commit('SET_USER_INFO', data)
            setStorage('USER_INFO', data)
            commit('SET_LOGINOUT', true)
        } catch (e) {
            commit('SET_LOGINOUT', false)
            console.log(e)
        }
    },
    // 获取accessToken
    async getAccessToken({ commit }) {
        try {
            const res = await getAccessToken()
            commit('SET_ACCESS_TOKEN', res.data)
            setStorage('ACCESS_TOKEN', res.data)
            commit('SET_LOGINOUT', true)
        } catch (e) {
            commit('SET_LOGINOUT', false)
            console.log(e)
        }
    },
    // 短信消息统计
    async updateNoticeNum({ commit }) { // 更新通知消息数量
        try{
            const commonId = getStorage('USER_INFO').userId || 0
            const { data } = await fetchMessageCount({ commonId })
            commit('SET_NOTICE_COUNT', data.count)
            commit('SET_TABBAR_BADGE', data.count)
        }catch(error){
            console.log(error)
        }
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
