import { userService } from '@/services/index.js'
import authorize from '@/common/authorize.js'
import { msg as showMsg } from '@/common/util.js'
import { switchTabTo } from '@/common/utilsTools.js'

const state = {
    userId: '',
    userIdentity: '',
    userInfo: null,
    hasLogin: false,
    isWxAuthorize: false,
    inviteUserId: 0,
}
const mutations = {
    // 用户登录
    LOGIN(state, data) {
        const userInfo = JSON.parse(data)
        state.userInfo = userInfo
        state.hasLogin = true
        state.isWxAuthorize = true
        state.userId = userInfo.userId
        state.userIdentity = userInfo.userIdentity
        uni.setStorageSync('openId', userInfo.openId)
    },
    // 退出登录
    LOGIN_OUT(state, data) {
        const userInfo = JSON.parse(data) || null
        state.userInfo = userInfo
        state.hasLogin = false
        state.isWxAuthorize = false
        state.userId = ''
        state.userIdentity = ''
        userInfo && uni.setStorageSync('openId', userInfo.openId)
    },
    // 设置邀请用户id
    setInviteUserId(state, id){
        state.inviteUserId = parseInt(id)
    }
}
const actions = {
    // 微信授权登录
    async wechatlogin({ commit, dispatch, state }) {
        // 获取code
        const code = await authorize.getCode('weixin')
        userService.UserWechatAuthorLogin({ code })
            .then(response => {
                console.log('登录成功')
                commit('LOGIN', response.data)
                dispatch('cart/getCartNumber', state.userId, { root: true }) // 获取购物车数量信息
                dispatch('coupon/getCouponActivity', null, { root: true }) // 获取优惠券弹窗信息
                dispatch('coupon/initReceiveCouponCount', null, { root: true }) // 获取已领取优惠券数量
            })
            .catch(error => {
                console.log('游客')
                dispatch('coupon/getCouponActivity', null, { root: true }) // 游客也要获取优惠券弹窗信息
                commit('LOGIN_OUT', error.data)
            })
    },
    // 手机号注册登录
    customLogin({ commit, state, dispatch }, params) {
        params.shareUserId = state.inviteUserId
        return userService.UserMobileLogin(params)
            .then(response => {
                // 保存用户信息
                commit('LOGIN', response.data)
                dispatch('cart/getCartNumber', state.userId, { root: true }) // 获取购物车数量信息
                dispatch('coupon/getCouponActivity', null, { root: true }) // 获取优惠券弹窗信息
                dispatch('coupon/initReceiveCouponCount', null, { root: true }) // 获取已领取优惠券数量
                // 登录成功提示
                showMsg('登录成功', 1500, false, 'success')
                setTimeout(() => {
                    switchTabTo('/pages/tabBar/index/index')
                }, 1500)
            })
            .catch(error => {
                showMsg(error.msg, 2000)
            })
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}
