import {
	simpleDebounce,
	throttle
} from "./util.js"

import { timeout } from "@/utils/request.js";

let loadingCount = 0; //loading发起时加的计数
let currentState = {};

const defaultState = {
	loadingText: "正在加载…",
	loadingTime: timeout
}

const endLoading = simpleDebounce(() => {
	currentState = {};
	uni.hideLoading();
}, 500)

const throttleShowLoading = throttle(500, () => {
	uni.showLoading({
		title: currentState.loadingText
	});
	if (currentState.loadingTime) {
		setTimeout(() => {
			endLoading();
			loadingCount = 0
		}, currentState.loadingTime)
	}
})

export const showLoading = (state = defaultState) => {
	if (loadingCount === 0) {
		currentState = state;
		throttleShowLoading();
	}
	loadingCount += 1;
};

export const hideLoading = () => {
	if (loadingCount <= 0) {
		return;
	}
	loadingCount -= 1;
	if (loadingCount === 0) {
		endLoading();
	}
};
