import {
	getToken,
	setToken,
	removeToken,
	refreshToken
} from '@/utils/auth'
import {
	login
} from '@/api/login.js'
import errorCode from '@/utils/errorCode'


/**
 * http请求封装
 */
const myAxios = (req) => {

	let query = ''

	req.params && Object.keys(req.params).map((key, index) => {
		if (index) {
			query += '&' + key + '=' + encodeURIComponent(req.params[key])
		} else {
			query += '?' + key + '=' + encodeURIComponent(req.params[key])
		}
	})

	let reqData = {
		url: req.baseURL ? req.baseURL : '' + req.url + query,
		method: req.method,
		data: {
			...req.data
		},
		header: {
			...req.header
		},
		timeout: req.timeout || 10000
	}

	// 请求拦截器
	async function reqMiddleware(config) {

		if (config.header.isLogin) {
			return config
		}
		let token = await getToken()
		config.header['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
		return config
	}

	// 响应拦截器
	async function resMiddleware(res) {
		//重置Authorization时间
		refreshToken()
		const code = res.data.code || 200;
		// 获取错误信息
		const msg = errorCode[code] || res.data.msg || errorCode['default']
		if (code === 401) {
			console.log('拦截器信息:' + msg)
		} else if (code === 500) {
			console.log('拦截器信息:' + msg)
		} else if (code === 502) {
			console.log('拦截器信息:' + msg)
		} else if (code !== 200) {
			console.log('拦截器信息:' + msg)
		}
		return res.data
	}
	// 2. 函数内部返回Promise 对象
	return new Promise(async (resolve, reject) => {
		reqData = await reqMiddleware(reqData)
		// 3.wx.request()  小程序发送请求
		wx.request({
			// 把调用axios时传过来的所有参数解构赋值
			...reqData,
			// 请求成功之后调用的函数
			success: async (result) => {
				result = await resMiddleware(result)
				resolve(result)
			},
			// 请求失败之后调用的函数
			fail: (error) => {
				reject(error)
			},
			complete: () => {

			}
		});
	});

}


export default myAxios
