import * as db from './db.js'
import { baseUrl } from './config.js';
import { User } from '@/config/api.js'
import { modal } from '@/config/util.js'
const showError = error => {
	let errorMsg = ''
	switch (error.status) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '跨域拒绝访问'
			break
		case 404:
			errorMsg = `请求地址出错: ${error.config.url}`
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = error.msg
			break
	}
	uni.showToast({
		title: errorMsg,
		icon: 'none',
		duration: 1000,
		complete: function() {
			setTimeout(()=> {
				uni.hideToast();
			}, 1000);
		}
	});
}	
// get请求
export const getHttp = (url,data,status=1)=> {
	// 获取用户token和用户信息
	let token = db.get("access_token");
	let authHeader = token || '';
	if(status) {
		uni.showLoading({
			title: '加载中'
		});		
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data: data,
			header: {
				// 'Accept': 'application/json',
				// 'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
				'Authorization':authHeader
			},
			method: 'GET',
			success: (res) => {
				status && uni.hideLoading();
				res.data.Ret === 403 && uni.showModal({
					title: '',
					confirmColor:'#3385FF',
					content: res.data.Msg,
					showCancel: false
				});
				resolve(res.data)
			},
			fail: (error) => {
				console.log(error)
				status && uni.hideLoading();
				if (error && error.response) {
					showError(error.response);
				}
			},
			complete: () => {
				setTimeout(()=> {
					status && uni.hideLoading();
				}, 250);
			}
		});
	})
}
// post请求
export const postHttp = (url,data,status=1)=> {
	// 获取用户token和用户信息
	let token = db.get("access_token");
	let authHeader =  token || '';
	
	if(status) {
		uni.showLoading({
			title: '加载中'
		});
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			data: data,
			header: {
				// 'Accept': 'application/json',
				'Content-Type': 'application/json',
				'Authorization':authHeader
			},
			method: 'POST',
			success: (res) => {
				status && uni.hideLoading();
				res.data.Ret === 403 && uni.showModal({
					title: '',
					confirmColor:'#3385FF',
					content: res.data.Msg,
					showCancel: false
				});
				resolve(res.data)
			},
			fail: (error) => {
				status && uni.hideLoading();
				if (error && error.response) {
					showError(error.response);
				}
			},
			complete: () => {
				setTimeout(()=> {
					status && uni.hideLoading();
				}, 250);
			}
		});
	})
}