const host = '/api/wx'
// 定义错误码
const errorCode = {
	400: '参数错误',
	401: '登录过期',
	403: '没有权限',
	404: '接口未找到',
	405: '请求方式不允许',
	500: '服务器错误',
	502: '网关错误',
	503: '服务不可用'
}
// 响应处理
function responseHandle(res, resolve, reject) {
	if (res.statusCode >= 200 && res.statusCode < 300) {
		if (res.data.code !== 200) {
			uni.showToast({
				title: res.data.msg,
				icon: 'none'
			})
			reject(res.data)
		} else {
			resolve(res.data.data)
		}
	} else {
		if (res.statusCode === 401) {
			uni.hideLoading()
			const token = uni.removeStorageSync('token')
			uni.showModal({
				title: "登录过期",
				content: res.data.message,
				confirmText: "前往登录",
				cancelText: '回到首页',
				success(res) {
					if (res.confirm) {
						uni.reLaunch({
							url: '/pages/login/login'
						})
					} else {
						uni.reLaunch({
							url: '/pages/index/index'
						})
					}
				}
			})
			uni.showToast({
				title: res.data.message,
				icon: "error"
			})
			reject(res.data)
		} else {
			uni.hideLoading()
			uni.showToast({
				title: errorCode[res.statusCode],
				icon: 'error'
			})
			reject(res.data)
		}
	}
}
// 错误处理
function errorHandle(err, reject) {
	uni.showToast({
		title: '连接服务器失败',
		icon: 'error'
	})
	reject(err)
}
/**
 * 请求premise
 * @param {请求方式} method 
 * @param {接口地址} url 
 * @param {请求参数} data 
 */
function http({
	method = 'get',
	url = '',
	data = {},
	type = 'json'
} = {}) {
	const oid = uni.getStorageSync('oid')
	if (oid && data && !data.oid) {
		data.oid = oid
	}
	const contentType = type === 'json' ? 'application/json' : 'application/x-www-form-urlencoded'
	const token = uni.getStorageSync('token')
	// 设置请求体类型
	const header = {
		'content-type': contentType
	}
	// 添加token
	if (token) {
		header.Authorization = token
	}
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '处理中',
			mask: true
		})
		uni.request({
			url: host + url,
			header,
			method,
			data,
			success(res) {
				uni.hideLoading()
				setTimeout(() => {
					responseHandle(res, resolve, reject)
				}, 200);

			},
			fail(err) {
				uni.hideLoading()
				setTimeout(() => {
					errorHandle(err, reject)
				}, 200);

			}
		})
	})
}
export default http