import store from '@/store'
import config from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import {
	getPracticalUrl,
	setPracticalUrl
} from '@/utils/practicalUrl'
import storage from './storage'
import {
	removeToken
} from './auth'
let timeout = 10000
const practicalUrl = getPracticalUrl()
const baseUrl = practicalUrl ? practicalUrl : config.baseUrl
// const baseUrl = config.baseUrl

const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	const tokenKey = store.getters.tokenKey;
	const tokenValue = store.getters.token;
	if (getToken() && !isToken) {
		console.log("权限校验")
		config.header['Authorization'] = 'Bearer ' + getToken()
		if (tokenKey) config.header["Authorization-key"] = tokenKey;
	}
	config.header['Platform'] = 'APP'
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.practicalUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(response => {
				let [error, res] = response
				if (error) {
					toast('后端接口连接异常')
					reject('后端接口连接异常')
					return
				}
				const {
					code,
					data,
					msg,
					success
				} = res.data
				const resCode = res.data.status || code || 200
				const resMsg = errorCode[resCode] || msg || errorCode['default']
				if (resCode === 401) {
					console.log("401")
					showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录').then(res => {
						if (res.confirm) {
							store.dispatch('LogOut').then(res => {
								uni.reLaunch({
									url: '/pages/login'
								})
							})
							//清空缓存信息
							storage.clean()
							removeToken()
						}
					})
					reject('无效的会话，或者会话已过期，请重新登录。')
				}
				if (resCode === 404) {
					console.log("404")
					showConfirm('访问的资源不存在').then(res => {
						if (res.confirm) {
							// store.dispatch('LogOut').then(res => {
							// 	uni.reLaunch({
							// 		url: '/pages/login'
							// 	})
							// })
						}
					})
					reject('访问的资源不存在')
				} else if (resCode === 500) {
					console.log(res.data)
					console.log("500")
					//toast(msg)
					showConfirm(resMsg).then(res => {
						if (res.confirm) {

						}
					})
					reject('500')
				}else if (resCode === 502) {
					//token 过期
					uni.reLaunch({
						url: 'pages/login'
					})
					console.log(res.data)
					toast(msg)
					reject('502')
				} else if (resCode !== 200) {
					console.log("resCode !== 200")
					toast(resMsg)
					reject(resCode)
				}
				//todo 
				resolve(res.data)
			})
			.catch(error => {
				let {
					message
				} = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				toast(message)
				reject(error)
			})
	})
}

export default request