import ajax from '@/common/ajax'
import store from '@/store'

let state = {
		token: uni.getStorageSync('TOKEN'), //是否已经登录
		userInfo: uni.getStorageSync('userInfo') || {}, //用户信息
		code: uni.getStorageSync('code'), //企微 code
	},
	getters = {
		userInfo(state) {
			return state.userInfo;
		},
		token(state) {
			return state.token;
		}
	},
	mutations = {
		setUserInfo(state, info) { //登录成功后的操作
			//原有的结合传来的参数
			state.userInfo = info || {};
			state.token = uni.getStorageSync('TOKEN') || '';
			uni.setStorageSync('userInfo', info);
		},
		logout(state) {
			state.info = {};
			state.token = '';
			state.code = '';
			uni.setStorageSync('userInfo', {});
			uni.removeStorageSync('TOKEN');
			uni.setStorageSync('code', '');
		},
		setToken(state, token) { 
			state.token = token;
			uni.setStorageSync('TOKEN', token);
		},
		setCode(state, code) {
			state.code = code;
			uni.setStorageSync('code', code);
		},
	},
	actions = {
		login({
			commit,
			state
		},params) {
			uni.showLoading({
				title: '登录中',
				mask: true
			})
			let token = ''
			ajax.post('/shunt/login', {code: state.code, ...params }).then(res => {
				token = res?.data?.token || ''
			}).catch(error => {
				console.error('login', error)
			}).finally(() => {
				uni.hideLoading()
				commit('setToken', token)
				if (token) {
					store.dispatch('user/updateUserInfo')
					uni.reLaunch({
						url: '/pages/index/index'
					});
				} else {
					commit('logout', '')
					uni.reLaunch({
						url: '/pages/error/403/403'
					});
				}
			})
		},
		updateUserInfo({
			commit,
			state
		}) {
			uni.showLoading({
				mask: true
			})
			state.token && ajax.post('/shunt/userinfo').then(res => {
				const info = res.data || {}
				commit('setUserInfo', info)
			}).catch(error => {
				console.error('updateUserInfo', error)
				commit('setUserInfo', {})
			}).finally(() => {
				uni.hideLoading()
			})
		},

	}
export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions
}
