import Vue from 'vue'  //引入 Vue
import Vuex from 'vuex'  //引入 Vuex
import ajax from './common/js/ajax.js'  //引入封装好的 request 方法
import { //引入 api
		api_onLaunch
	} from './api.js'

Vue.use(Vuex)  //套路
const store = new Vuex.Store({
    state: {  //状态
		N401: 0,
		gotLocation: false,
		id: uni.getStorageSync('id'),
		openid: uni.getStorageSync('openid'),
		networkType: '',  //网络状态信息
		userWeixinInfo: {},  //用户微信信息，包括微信名，微信头像等
		userServerInfo: {},  //用户服务器信息，包括 token，用户名，等级等
		showVerify: false,  //是否显示手机短信验证弹窗
		showWarn: false,  //是否显示警告用户弹窗
		showGetUserInfoButton: false  //是否显示获取用户信息button
	},
    mutations: {
		CHANGENETWORKSTATUS (state, payload) {  //修改网络类型
			state.networkType = payload
		},
		GETUSERWEIXININFO (state, payload) { //获取到用户微信信息之后的操作
			console.log(payload)
			state.userWeixinInfo = payload
		},
		GETUSERSERVERINFO (state, payload) { //获取到用户服务器信息之后的操作
			if (!state.openid) { 
				uni.setStorageSync('openid', payload.openid)
				state.openid = payload.openid
			}
			if (!state.id) {
				uni.setStorageSync('id', payload.id)
				state.openid = payload.openid
			}
			console.log(payload)
			
			// payload.cha_nickname = 'TEST1211313123'
			// payload.money = 1
			
			// 模拟用户 请打开下面注释
			// payload.signuped = true
			// payload.type = 2
			// payload.level_name = '代理公司'
			
			
			state.userServerInfo = payload //把获取到的用户服务器信息，保存到 vuex 中
		},
		HIDEVERIFY (state) { //关闭手机号码验证弹窗
			state.showVerify = false
		},
		SHOWVERIFY (state) {  //打开手机号码验证弹窗
			state.showVerify = true
		},
		HIDEWARN (state) { //关闭警告用户弹窗
			state.showWarn = false
		},
		SHOWWARN (state) {  //打开警告用户弹窗
			state.showWarn = true
		},
		SHOWGETUSERINFOBUTTON (state) {  //显示获取用户信息按钮
			state.showGetUserInfoButton = true
		},
		HIDEGETUSERINFOBUTTON (state) {  //隐藏获取用户信息按钮
			state.showGetUserInfoButton = false
		},
		SIGNUP (state) {  // 用户报名成功改变状态
			state.userServerInfo.signuped = true
		},
		GETLOCALTION(state) { // 获取位置信息
			state.gotLocation = true
		},
		READCHALLENGE(state) { // 已读挑战消息
			state.userServerInfo.cha_nickname = ''
		}
	},
    actions: {
		onLaunch ({ commit, state }) {  //初始化后进行的一些异步操作
			return new Promise(async (resolve, reject) => {
				uni.showLoading({ title: '加载中', mask: true })  //显示loading
				const [getUserWeixinInfoErr, userWeixinInfo] = await uni.getUserInfo()  //首先获取用户微信信息
				if (getUserWeixinInfoErr) {  //获取用户微信信息失败后，提示用户，同时展示透明按钮
					uni.$emit('MESSAGE', '获取微信授权信息失败，请点击屏幕允许 大卫博士争霸赛获取您的公开信息（昵称、头像、地区及性别）', 864000000)
					uni.hideLoading()  //取消loading
					commit('SHOWGETUSERINFOBUTTON')
				} else { // 获取用户微信信息成功后，继续进行下一步
					uni.$emit('HIDEMESSAGE') // 隐藏信息提示框
					commit('GETUSERWEIXININFO', userWeixinInfo.userInfo) //将获取到的用户微信信息存在 store 里
					let CODE = '123'
					if (!state.openid) {
						const [ , { code }] = await uni.login()  //获取 code，并将code 连同用户头像/昵称/openid一同发给后台
						CODE = code
					}
					let latitude = '' // 经度
					let longitude = '' // 维度
					const location = await uni.getLocation({ type: 'gcj02' }) // 获取地理位置信息
					uni.hideLoading()  //取消loading
					const login = () => {
						uni.showLoading({ title: '加载中', mask: true })  //显示loading
						this.$ajax.get(`${api_onLaunch}?id=${state.id}&sex=${state.userWeixinInfo.gender}&latitude=${latitude}&longitude=${longitude}&code=${CODE}&avatar=${state.userWeixinInfo.avatarUrl}&openid=${state.openid ? state.openid : '123'}&nickname=${state.userWeixinInfo.nickName}`).then(([ , { data: res }]) => {
							if (res.code === 200) { //当前微信用户已经绑定手机号了
								state.N401 = 0
								commit('GETUSERSERVERINFO', res.data)
								uni.hideLoading()  //异步操作结束，停止 loading
								resolve()
							} else if (res.code === 300) { //当前微信用户没有绑定手机号，弹出验证码框 // 401 表示 code 过期/失效 openid 获取不到等
								uni.hideLoading()  //异步操作结束，停止 loadin
								commit('SHOWVERIFY')
								resolve()
							} else if (res.code === 401) {
								uni.hideLoading() // 异步操作结束，停止 loading
								reject(500)
							} else { //其他边界情况，提示用户下拉刷新
								uni.hideLoading() // 异步操作结束，停止 loading
								reject(500)
							}
						})
					}
					const checkLocation = async () => {
						if (!state.gotLocation) {
							const [, { cancel, confirm }] = await uni.showModal({
								title: '提示',
								content: '获取您的位置信息失败，会导致您无法上传图片',
								showCancel: false,
								confirmText: '重新获取'
							})
							if (confirm) {
								const settings = await new Promise(resolve => wx.openSetting({
									success (res) {
										resolve(res.authSetting)
									}
								}))
								if (settings['scope.userLocation']) {
									commit('GETLOCALTION')
									login()
								} else {
									checkLocation()
								}
							} else {
								checkLocation()
							}
						}
					}
					if (location.length == 2) {
						commit('GETLOCALTION')
						latitude = location[1].latitude
						longitude = location[1].longitude
						login()
					} else {
						checkLocation()
					}
				}
			})
		}
	}
})

Vuex.Store.prototype.$ajax = ajax(store)

export default store