import store from '@/utils/store';
import dayjs from 'dayjs';
import { ProjectName } from '@/config/config';

export default {
	state: {
		token: store.get('token') || null,
		shopInfo: store.get('shopInfo') || {},
		info: store.get('userInfo') || {}
	},
	actions: {
		userLogin({ commit }, form) {
			let host = null;
			if (ProjectName == 'business') {
				host = () => {
					return this.$service.common.userLogin(form);
				};
			} else {
				host = () => {
					return this.$service.common.sassLogin(form);
				};
			}
			return host(form).then(res => {
				commit('SET_TOKEN', res);
				return res;
			});
		},

		userLogout({ dispatch }) {
			return new Promise(resolve => {
				// service.common.userLogout().done(() => {
				dispatch('userRemove').then(() => {
					resolve();
				});
			});
			// });
		},

		shopInfo({ commit }) {
			return this.$service.common.shopInfo().then(res => {
				commit('SET_SHOPINFO', res);
				return res;
			});
		},

		userInfo({ commit }) {
			let host = null;
			if (ProjectName == 'business') {
				host = () => {
					return this.$service.common.userInfo();
				};
			} else {
				host = () => {
					return this.$service.common.sassInfo();
				};
			}
			return host().then(res => {
				commit('SET_USERINFO', res);
				return res;
			});
		},

		userRemove({ commit }) {
			commit('CLEAR_USER');
			commit('CLEAR_SHOPINFO');
			commit('CLEAR_TOKEN');
			commit('RESET_PROCESS');
			commit('SET_MENU_GROUP', []);
			commit('SET_VIEW_ROUTES', []);
			commit('SET_MENU_LIST', 0);
		}
	},
	mutations: {
		SET_SHOPINFO(state, val) {
			state.shopInfo = val;
			store.set('shopInfo', val);
		},

		SET_USERINFO(state, val) {
			state.info = val;
			store.set('userInfo', val);
		},

		SET_TOKEN(state, { token, expire }) {
			state.token = token;
			store.set('token', token, expire && dayjs().add(expire, 'second'));
		},

		CLEAR_SHOPINFO(state) {
			state.shopInfo = {};
			store.remove('shopInfo');
		},

		CLEAR_TOKEN(state) {
			state.token = null;
			store.remove('token');
		},

		CLEAR_USER(state) {
			state.info = {};
			store.remove('userInfo');
		}
	}
};
