import { wechatLogin } from '@/api/index';

const LOGIN_EXPIRE = 3 * 24 * 60 * 60 * 1000;
const user = {
	state: {
		user: {},
		token: '',
		openId: '',
		// 是否需要刷新，比如登录返回、页面操作返回上一页
		needRefresh: false,
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
			uni.setStorageSync('token', token)
			// #ifdef MP-WEIXIN || H5
			if (token) uni.setStorageSync('expireTime', Date.now() + LOGIN_EXPIRE);
			// #endif
		},
		SET_USER: (state, user) => {
			state.user = user
			uni.setStorageSync('user', user)
		},
		SET_OPENID: (state, openId) => {
			state.openId = openId
			uni.setStorageSync('openId', openId)
		},
		SET_NEED_REFRESH: (state, payload) => {
			state.needRefresh = payload
		},
	},
	actions: {
		// 登录
		login({ commit, dispatch }, payload) {
			return new Promise((resolve, reject) => {
				let { isBack = 0, ...forms } = payload;
				let params = {
					...forms,
				};
				clientLoginNew(params).then((res) => {
					if (res.code == 200) {
						if (res.result.userInfo.delFlag == 1) {
							uni.showModal({
								title: '温馨提示',
								content: '该账号近期已注销，如有疑问请联系客服',
								showCancel: false,
								confirmText: '知道了',
								confirmColor: '#0879FF',
							});
							return;
						}
						commit('SET_USER', res.result)
						commit('SET_TOKEN', res.result.token)
						commit('SET_REFRESH_TOKEN', res.result.refreshToken)
						
						uni.showToast({
							icon: 'none',
							title: '登录成功'
						})
						if (isBack == 1) {
							commit('SET_NEED_REFRESH', true);
							// #ifdef MP-WEIXIN
							uni.navigateBack({ delta: 2 });
							// #endif
							// #ifndef MP-WEIXIN
							uni.navigateBack();
							// #endif
						} else if (isBack == 0) {
							uni.switchTab({
								url: '/pages/home/home'
							});
						}
					} else if (res.code == 504) {
						eventBus.emit('openPage');
					} else if (res.code == 500) {
						uni.$u.toast(res.message);
					}

					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 页面刷新标识
		setRefresh({ commit, state }, payload) {
			commit('SET_NEED_REFRESH', payload)
		},
		// 登出
		logOut({ commit }) {
			return new Promise(resolve => {
				commit('SET_USER', '')
				commit('SET_TOKEN', '')
				commit('SET_REFRESH_TOKEN', '')
				commit('SET_OPENID', '')

				// #ifdef MP-WEIXIN
				uni.switchTab({
					url: '/pages/home/home'
				});
				// #endif
				// #ifndef MP-WEIXIN
				uni.reLaunch({
					url: '/pages/login/login'
				});
				// #endif
				resolve()
			})
		},
	}
}

export default user
