import { wxLogin } from '@/apis/user.js'
import store from '@/store/index.js'
import { isFunction } from '@/utils/types.js'
import Toast from '@/lib/toast/index.js'

// wx.login
export function login_wx(cb) {
	try{
		uni.login({
			success: async res => {
				const { status, data } = await wxLogin(res.code)
				if(status) {
					cb && isFunction(cb) && cb()
					store.state.user.openid = data.openid
					store.state.user.unionid = data.unionid
					store.state.user.session_key = data.session_key
				}
			},
			fail: err => uni.showModal({
				title: "提示",
				content: err.errMsg,
				showCancel: false
			})
		})
	}catch(e){
		console.log(e)
		//TODO handle the exception
	}
}

/**
 * @desc 检查登录
 * @param { Function } cb  
 */
export function checkLogin(cb) {
	if(!store.state.user.token) return Toast({title: '您尚未登录,请先登录', cb: () => {
		uni.navigateTo({
			url: '/pages/login/index'
		})
	}})
	cb && isFunction(cb) && cb()
}