import store from '../store/index.js';

// 不含icon提示框
export const toast = str => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: str,
			icon: "none",
			duration: 1500,
			success: () => {
				setTimeout(() => {
					resolve
				}, 1500)
			}
		})
	})
};

// 成功提示框
export const successToast = str => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: str || '请求成功',
			icon: "success",
			duration: 1500,
			success: () => {
				setTimeout(() => {
					resolve()
				}, 1500)
			}
		})
	})
};

// loading
export const showLoading = () => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			success: () => {
				resolve()
			}
		})
	})
};

// 提示loading
export const tipLoading = str => {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: str,
			success: () => {
				resolve()
			}
		})
	})
};

// 隐藏loading
export const hideLoading = () => {
	return new Promise((resolve, reject) => {
		uni.hideLoading({
			success: () => {
				resolve()
			}
		})
	})
};

// 模态弹窗
export const modal = (options = {}) => {
	if (!options) return;
	const {
	  title,
	  content,
	  showCancel,
	  cancelText,
	  cancelColor,
	  confirmText,
	  confirmColor
	} = Object.assign({}, options.content ? options : { content: options });
	return new Promise((resolve, reject) => {
	  uni.showModal({
	    title: title || "提示",
	    content: String(content),
	    showCancel: typeof showCancel == "boolean" ? showCancel : true,
	    cancelText: cancelText || "取消",
	    cancelColor: cancelColor || "#323233",
	    confirmText: confirmText || "确定",
	    confirmColor: confirmColor || "#FF3F42",
	    success(res) {
	      if (res.confirm) {
	        resolve(res);
	      } else {
	        reject();
	      }
	    }
	  });
	});
};

/**
 * 跳转页面 navigateTo
 * 保留当前页面，跳转到应用内的某个页面
 * @param {String} url 需要跳转的页面
 * @param {Boolean} isAuth 是否需要鉴权
 * @returns
 */
export const navPage = (url, isAuth = 0) => {
	if((isAuth && store.state.isLogin) || !isAuth){
		uni.navigateTo({
			url,
			fail: err=>{
				console.log('页面跳转失败', url, err)
			}
		})
	}else{
		uni.navigateTo({
			url:'/pages/login/index'
		})
	}
};

/**
 * 跳转页面 redirectTo
 * 关闭当前页面，跳转到应用内的某个页面
 * @param {String} url 需要跳转的页面
 * @param {Boolean} isAuth 是否需要鉴权
 * @returns
 */
export const redPage = (url, isAuth = 0) => {
	if((isAuth && store.state.isLogin) || !isAuth){
		uni.redirectTo({
			url,
			fail: err=>{
				console.log('页面跳转失败', url, err)
			}
		})
	}else{
		uni.navigateTo({
			url:'/pages/login/index'
		})
	}
};

/**
 * 返回页面
 * @param {Number} num 返回的页面数
 * @param {Number} time 延时返回
 * @returns
 */
export const backPage = (num = 1, time = 0) => {
	if(!num) return false;
	setTimeout(() => {
		uni.navigateBack({
		    delta: num
		});
	}, time)
};

export default {
	toast,
	successToast,
	showLoading,
	tipLoading,
	hideLoading,
	modal,
	navPage,
	redPage,
	backPage
}