import { BASEURL, TokenPrefix, APIPrefix } from '../publicConfig/config'

let serverCode = {
	3: '重定向',
	4: '请求包含错误或未找到资源',
	5: '服务器错误'
}


let Request = (api, data, method = 'POST', header = {}, showLoading = true) => {
	//获取token
	const XSRFToken=uni.getStorageSync(`${TokenPrefix}_XSRFToken`);
	const token=uni.getStorageSync(`${TokenPrefix}_token`);

	header = {
		'Content-Type': 'application/json;charset=UTF-8',
		'Cookie': 'XSRF-TOKEN=' + uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
		"X-XSRF-TOKEN": uni.getStorageSync(`${TokenPrefix}_XSRFToken`) || '',
		"Authorization": uni.getStorageSync(`${TokenPrefix}_token`) || '',
		...header
	}
	if(showLoading){
		uni.showLoading({
			title: '加载中...',
		})
	}
	console.log('请求参数：', data);

	return new Promise((reslove, reject) => {
		const { projectMini } = getApp().globalData
		const newApi = APIPrefix + api.replace(/{mini}/g, projectMini)
		uni.request({
			//#ifdef MP
			url: BASEURL.url + newApi,
			//#endif

			//#ifdef H5
			url: newApi,
			//#endif

			data,
			method,
			header,
			success: (res) => {
				if(showLoading){
					uni.hideLoading()
				}
				if (res.statusCode == '404') {
					uni.showToast({
						title: '无法找到资源',
						icon: 'error',
						duration: 3000
					})
				} else if (res.statusCode === 401 && !newApi.includes('/auth/app-login')) {
					//#ifdef MP
					if(!XSRFToken&&!token){
						//如果没有token，说明不是token过期，而是访客身份
						reject("");
					}else{
						let app = getApp()
						uni.showToast({
							title: '登录已过期',
							icon: 'error',
							duration: 3000
						})
						uni.removeStorageSync(`${TokenPrefix}_token`)
						uni.removeStorageSync(`${TokenPrefix}_XSRFToken`)
						uni.removeStorageSync('cookies')
						app.judgePlatform();
					}
					//#endif
					
					//#ifdef H5
					let app = getApp()
					uni.showToast({
						title: '登录已过期',
						icon: 'error',
						duration: 3000
					})
					uni.removeStorageSync(`${TokenPrefix}_token`)
					uni.removeStorageSync(`${TokenPrefix}_XSRFToken`)
					uni.removeStorageSync('cookies')
					app.judgePlatform();
					//#endif
				} else if (res.statusCode !== 200) {
					console.log('响应日志：', res.data);
					if (res.data.messageType) {	
						if(!newApi.includes('/auth/app-login')){ //登录接口自定义处理
							uni.showToast({
								title: res.data.message,
								icon: 'none',
								duration: 3000
							})
						}						
						reject(res.data)
					} else {
						uni.showToast({
							title: serverCode[res.statusCode.toString()[0]],
							icon: 'error',
							duration: 3000
						})
					}
				} else {
					reslove(res)
				}
			},
			fail: (err) => {
				if(showLoading){
					uni.hideLoading()
				}
				uni.showToast({
					title: err.info || '请求失败！',
					icon: 'error',
					duration: 2000
				})
				reject(err)
			}
		})
	})
}

export default Request
