import { http } from 'uview-plus';
import { useAuthStore, useCommonStore } from '@/store';
import { env } from '@/env';

const HEADER_FORM = 'application/x-www-form-urlencoded'
const HEADER_UPLOAD = 'multipart/form-data';
const HEADER_JSON = 'application/json;charset=UTF-8';
const HEADER_TEXT = 'text/plain;charset=UTF-8';

export {
	HEADER_FORM, HEADER_UPLOAD, HEADER_JSON, HEADER_TEXT
}



export const HttpConfig = () => {

	// 初始化请求配置
	http.setConfig((config) => {

		/* config 为默认全局配置*/
		config.baseURL = env.baseApi;
		config.custom = {
			type: 'json', // 不区分大小写:form,json,text,upload,none;
			loading: false, //是否显示加载动画
			showError: true, //是否显示错误消息
			returnData: true, //true:返回的数据成功只返回data  false:返回response
			catch: true, //默认数据返回不成功进入catch返回
			auth: true, //是否需要授权,是否头部携带token
		}
		return config
	})

	// 请求拦截
	http.interceptors.request.use((config) => {
		// 初始化请求拦截器时，会执行此方法，此时data为undefined，赋予默认{}
		config.data = config.data || {};
		config.custom = config.custom || {};
		if (!config.header["Content-Type"]) {
			let type = (config.custom.type || 'none').toLowerCase();
			switch (type) {
				case 'form':
					config.header["Content-Type"] = HEADER_FORM;
					break;
				case 'upload':
					config.header["Content-Type"] = HEADER_UPLOAD;
					break;
				case 'text':
					config.header["Content-Type"] = HEADER_TEXT;
					break;
				case 'json':
					config.header["Content-Type"] = HEADER_JSON;
					break;
			}
		}

		if (config.custom.auth) {
			config.header.Authorization = 'Bearer ' + (useAuthStore().token || "");

		}
		if (config.custom.loading) {
			//打开加载动画
			useCommonStore().showLoading();
		}

		return config
	}, config => {
		return Promise.reject(config)
	})


	// 响应拦截
	http.interceptors.response.use(async (response) => {
		useCommonStore().hideLoading();
		const data = response.data;
		const custom = response.config.custom || {};

		if (data.code == 401) {
			if (custom.showError) {
				uni.showToast({ title: '请重新登录', icon: 'error', duration: 3000 });
			}
			useAuthStore().$reset();
			uni.reLaunch({
				url: "/pages/index/login"
			})
		} else if (data.code == 200) {
			if (!custom.returnData) {
				return data
			} else {
				return data.data
			}
		} else {
			if (custom.showError) {
				uni.showToast({ title: data.message || data.msg, icon: 'error', duration: 3000 });
			}
			if (custom.catch) {
				return Promise.reject(data)
			} else {
				return data;
			}
		}
	}, (response) => {
		useCommonStore().hideLoading();
		let errorData = '网络错误';
		let message = response.message || response.msg;
		if (message == "request:fail url not in domain list") {
			errorData = '检查请求域名是否添加了域名白名单';
		} else if (message == 'request:fail timeout') {
			errorData = '请求超时:请检查网络';
		} else {
			errorData = message || '网络错误';
		}
		uni.showToast({ title: errorData, icon: 'error', duration: 3000 });
		return Promise.reject(response)
	})
}

export { http };