import Vue from 'vue';
import Vuex from 'vuex';

import MD5 from '@/assets/scripts/md5';
import configs from '@/configs/env';
import apis from '@/configs/http';
import chart from '@/store/modules/chart';

Vue.use(Vuex);

const store = new Vuex.Store({
	strict: !configs.isProduction,
	modules: {
		chart
	},
	state: {
		loginUser: {},
		token: '',
		isLoading: false,
	},
	mutations: {
		setLoginUser(state, loginUser) {
			state.loginUser = loginUser;
		},
		setToken(state, token) {
			state.token = token;
		},
		setLoading(state, flag) {
			state.isLoading = flag;
		},
	},
	actions: {
		login({ commit }, { username, password }) {
			commit('setLoading', true);
			console.log(`login actions: `, arguments);
			const encryptPwd = MD5(password);
			const data = { username, password: encryptPwd };
			return apis.sz.post('/TAdmin/userLogin', data)
				.then(res => {
					// const { token, userObj } = res.data;
					//用户名缓存
					uni.setStorageSync("name", res.data.name);
					const userObj = res.data;
					commit('setLoading', false);
					commit('setLoginUser', userObj);
					// commit('setToken', token);
				}, _ => {
					commit('setLoading', false);
					return Promise.reject();
				});
		}
	}
});

export default store;