import {
	wecatLogin,
	getUserInfo
} from "../../api/index.js"
export default {
	namespaced: true,
	state: {
		isPhone: false, //是否显示手机登录弹窗
		wxCode: '', //微信code
		wxInfo: null,
		address: null,
		isAuth: false, //是否显示授权按钮
		userInfo: null, //用户信息
	},
	getters: {

	},
	mutations: {
		SET_CODE: (state, wxCode) => {
			state.wxCode = wxCode
		},
		SET_WXINFO: (state, wxInfo) => {
			state.wxInfo = wxInfo
		},
		SET_ADDRESS: (state, address) => {
			state.address = address
		},
		IS_PHONE: (state, phone) => {
			state.isPhone = phone
		},
		IS_AUTH: (state, auth) => {
			state.isAuth = auth
		},
		SET_USER_INFO: (state, info) => {
			state.userInfo = info
		}
	},
	actions: {
		getWxInfo({
			commit,
			state
		}) {
			return new Promise(async (resolve, reject) => {
				let [, {
					code
				}] = await uni.login()
				if (code) {
					console.log(111)
					let [wxInfoErrMsg, wxInfoData] = await uni.getUserInfo()
					if (wxInfoErrMsg) {
						uni.showModal({
							content: '获取微信信息失败'
						})
					}
					let {
						userInfo
					} = wxInfoData
					let [addressErrMsg, addressData] = await uni.getLocation()
					if (addressErrMsg) {
						uni.showModal({
							content: '获取位置信息失败'
						})
					}
					let {
						latitude,
						longitude
					} = addressData
					commit('SET_ADDRESS', addressData)
					commit('SET_WXINFO', wxInfoData.userInfo)
					let res = await wecatLogin({
						openid: '',
						avatar: userInfo.avatarUrl,
						nickname: userInfo.nickName,
						code,
						longitude,
						latitude
					})
					if (res.code === 200) {
						uni.setStorageSync("token", res.data.token);
						commit('IS_AUTH', false)
						let uRes = await getUserInfo()
						if (uRes.code === 200) {
							uni.setStorageSync('userInfo', uRes.data);
							commit('SET_USER_INFO', uRes.data);
						} else {
							uni.showModal({
								content: '获取用户信息失败'
							})
						}
					}
					if (res.code === 300) {
						// let [, {
						// 	code
						// }] = await uni.login()
						// commit("SET_CODE", code);
						commit('IS_PHONE', true)
						// if (code) {
						// 	reject({
						// 		code: 4,
						// 		msg: '请使用手机登录'
						// 	})
						// } else {
						// 	reject({
						// 		code: 1,
						// 		msg: '微信登录失败'
						// 	})
						// }
					}
				} else {
					reject({
						code: 1,
						msg: '微信登录失败'
					})
				}
			})
		}
	}
}
