import { createStore } from '@/utils/vuex-shim.js'

let lifeData = {};

try {
	lifeData = uni.getStorageSync('lifeData');
} catch (e) {

}

let saveStateKeys = ['vuex_user', 'vuex_token', 'userInfo', 'userBpData', 'isChildCustomer', 'customerDetails'];

const saveLifeData = function(key, value) {
	if (saveStateKeys.indexOf(key) != -1) {
		let tmp = uni.getStorageSync('lifeData');
		tmp = tmp ? tmp : {};
		tmp[key] = value;
		uni.setStorageSync('lifeData', tmp);
	}
}

const storeOptions = {
	state: {
		vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {
			name: '明月'
		},
		vuex_token: lifeData.vuex_token ? lifeData.vuex_token : '',
		vuex_version: '1.0.1',
		vuex_demo: '绛紫',
		userInfo: lifeData.userInfo ? lifeData.userInfo : {
			name: '',
			code: ''
		},
		userBpData: lifeData.userBpData ? lifeData.userBpData : {
			USER_BP: '',
			ROLES: [{
				"ROLE_DESC": "",
				"ROLE_ID": "WLY001"
			}],
			USER_NAME: ''
		},
		quotaOrder: {
			'ITEM_INNER': [],
			'ITEM_OUTER': [],
			'item_d': [],
			'ATTACHMENT': [],
			'INFO': {}
		},
		noQuotaOrder: {
			'ITEM': [],
			'item_d': [],
			'ATTACHMENT': [],
			'INFO': {}
		},
		groupOrder: {
			'ITEM': [],
			'ATTACHMENT': [],
			'INFO': {},
			'baseinfo': {}
		},
		isChildCustomer: lifeData.isChildCustomer !== undefined ? lifeData.isChildCustomer : false,
		customerDetails: lifeData.customerDetails ? lifeData.customerDetails : {
			info: {}
		}
	},
	getters: {
		role(state) {
			if (!state.userBpData) {
				return {
					USER_BP: '',
					ROLE: ''
				}
			}
			const roleId = state.userBpData.ROLES && state.userBpData.ROLES.length > 0
				? state.userBpData.ROLES[0].ROLE_ID
				: ''
			return {
				USER_BP: state.userBpData.USER_BP || '',
				ROLE: roleId
			}
		}
	},
	mutations: {
		$uStore(state, payload) {
			let nameArr = payload.name.split('.');
			let saveKey = '';
			let len = nameArr.length;
			if (len >= 2) {
				let obj = state[nameArr[0]];
				for (let i = 1; i < len - 1; i++) {
					obj = obj[nameArr[i]];
				}
				obj[nameArr[len - 1]] = payload.value;
				saveKey = nameArr[0];
			} else {
				state[payload.name] = payload.value;
				saveKey = payload.name;
			}
			saveLifeData(saveKey, state[saveKey])
		}
	}
}

const store = createStore(storeOptions)

export default store
