import request from "@/common/request/index.js";

// 请求前拦截
const BEFOREINTERCEPT = (axios, currentPage, totalPage) => {
	axios = {
		...axios,
		data: {
			...axios.data,
			page: currentPage
		}
	}
	return axios
}

//参数处理
const AFTERINTERCEPT = (result, ListValue, currentPage, totalPage) => {
	if (result.code != 0) throw Error(result.msg);
	currentPage++;
	totalPage = result.totalPage;
	ListValue = ListValue.concat(result.data);
	return {
		ListValue,
		currentPage,
		totalPage
	}
}



export default {
	namespaced: true,
	state: {
		ListValue: [], //数据
		currentPage: 1, // 当前页
		totalPage: 1 //总页数
	},
	mutations: {
		increment(state, options) {
			Object.keys(options).forEach(item => state[item] = options[item])
		},
		changeValue(state,options){
		  state['ListValue']=options;	
		}
	},
	actions: {
		async reset({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				commit('increment', {
					ListValue: [],
					currentPage: 1,
					totalPage: 1,
				});
				resolve()
			})
		},
		async requestFunc({
			commit,
			state
		}, options) {
			var {
				ListValue,
				currentPage,
				totalPage
			} = state;
			if (currentPage > totalPage) return false;
			let axios = BEFOREINTERCEPT(options, currentPage, totalPage);
			var result = await request(axios);
			result = AFTERINTERCEPT(result, ListValue, currentPage, totalPage);
			commit('increment', result);
		}
	}

}
