import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex); //vue的插件机制

import api from '@/api/api.js'

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state: {
		configList: {}, //配置对象
		userInfo: {},
	},
	getters: {
		getConfig(state) {
			return state.configList
		}
	},
	mutations: {
		// 初始化配置
		initConfig(state) {
			//初始化用户信息(防止用户每次点击重新进入小程序用户信息都没有了)
			if (uni.getStorageSync('token') && uni.getStorageSync('userInfo')) {
				state.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
			}

			let apiConfig = [ 'getPrivacyPolicy' , 'getUserAgreement' ]		//需要访问不同接口才能得到的配置数据
			let key = ['privacyAgreement','userAgreement']
			apiConfig.forEach((item,index) => {
				api(item,res => {
					state.configList[key[index]] = res.result
				})
			})
		},
		login(state , form) {
			if (!form) { //微信登录
				uni.login({
					success(res) {
						if (res.errMsg != "login:ok") {
							return
						}
						api('studentLogin', {
							code: res.code
						}, res => {
							if (res.code != 200) {
								return
							}
							uni.setStorageSync('token', res.result.token);
							uni.setStorageSync('userInfo', JSON.stringify(res.result.userInfo));
							state.userInfo = res.result.userInfo
							//用户未设置用户名和头像,跳转上传头像或设置昵称页面
							if (!state.userInfo.nickName || !state.userInfo.headImage) {
								uni.navigateTo({
									url: '/pages/login/wxUserInfo'
								})
							} else {		//跳转报修页面
								uni.switchTab({
									url: '/pages/repair/repair'
								})
							}

						})
					},
					fail(err) {
						console.error(err)
					}
				})
			} else { //手机登录
				api('repairLogin' , form , res => {
					if (res.code == 200) {
						uni.setStorageSync('token', res.result.token);
						uni.setStorageSync('userInfo', JSON.stringify(res.result.userInfo));
						state.userInfo = res.result.userInfo
						uni.switchTab({
							url: '/pages/repair/repair'
						})
					}
				})
			}
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
	},
	actions: {},
})

export default store