import store from '@/utils/store';
import service from '@/service/index';
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 service.common.userLogin(form);
				};
			} else {
				host = () => {
					return service.common.sassLogin(form);
				};
			}
			return host(form).then(res => {
				commit('SET_TOKEN', res);
				return res;
			});
		},

		userLogout({ commit }) {
			// return service.common.userLogout().done(() => {
			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);
			// });
		},

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

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

		userInvalid({ commit }) {
			commit('CLEAR_TOKEN');
		}
	},
	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_USER(state) {
			state.info = {};
			store.remove('userInfo');
		},

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