import {
	postTokenApi,
	getUserInfoApi,
} from '@/config/api.js';

const state = () => ({
	openid: '',
	isReg: '',
	id: '',
	name: '',
	number: '',
	password: '',
	phone: '',
	status: '',
	type: '',
	username: '',
	userInfo: {},
	userBasicInfo: {},

})

const getters = {

}

// actions
const actions = {

	async login({
		commit,
		dispatch,
		state
	}, params) {
		const login_result = await postTokenApi({
			...params
		}, {
			custom: {
				auth: false
			}
		});

		if (login_result) {

			await commit('setLogin', login_result);

			switch (login_result.status) {

				case 'not_reg': //未注册
					uni.$u.route({
						url: '/pages/student/my/login/login',
						type: 'reLaunch',
					});
					break;

				case 'annulled': //已注销
					uni.$u.route({
						url: '/pages/student/my/written-off/written-off',
						type: 'navigateTo',
					});
					break;

				case 'annulling': //注销中
					uni.$u.route({
						url: '/pages/student/my/freezing/freezing',
						type: 'navigateTo',
					});
					break;

				case 'active': //已注册
					const userInfo = await dispatch(`getUserInfo`);
					if (userInfo?.teacher) {
						uni.$u.route({
							url: 'pages/tabBar/home/home',
							type: 'switchTab',
							params: {

							}
						})
					}

					break;
			}
		}


	},

	async loginOut({
		commit,
		dispatch,
		state
	}, params) {
		
		await commit('setLoginOut', {});
		uni.$u.route('/pages/main/my/login/login');
	},

	async getUserInfo({
		commit,
		dispatch,
		state
	}, params) {

		const result = await getUserInfoApi();
		
		commit('setUserInfo', result);

		uni.$u.vuex('vuex_user', result);

		return result;
	},
}

// mutations
const mutations = {

	setLogin(state, result) {
		let vuex_token = `Bearer ${result.access_token}`
		uni.$u.vuex('vuex_token', vuex_token);
		uni.$u.vuex('vuex_phone', result.phone);
		uni.$u.vuex('hasLogin', true);
	},
	
	setLoginOut(state, result) {
		uni.$u.vuex('vuex_token', '');
		uni.$u.vuex('vuex_phone', '');
		uni.$u.vuex('vuex_user', {});
		uni.$u.vuex('hasLogin', false);
	},
	
	setUserInfo(state, result) {
		state.userInfo = result;
	},
	
	

}

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