import Axios, {
	AxiosResponse,
	InternalAxiosRequestConfig,
	AxiosError,
  } from 'axios';
import { domainManager } from '../utils/domainManager'
let datas: AxiosResponse

export enum ApiResult{
	'SUCCESS' = 1,
	'FAILED' = 0,
	'TOKEN_INVALID' = 10000,
	'TOKEN_ILLEGAL' = 10001,
}
/**
 * get status code
 * @param {AxiosResponse} response Axios  response object
 */
const getErrorCode2text = (response: AxiosResponse): string => {
	const code = response.status
	let message = 'Request Error'
	switch (code) {
		case 400:
			message = 'Request Error'
			break
		case 401:
			message = 'Unauthorized, please login'
			break
		case 403:
			message = '拒绝访问'
			break
		case 404:
			message = '访问资源不存在'
			break
		case 408:
			message = '请求超时'
			break
		case 500:
			message = '位置错误'
			break
		case 501:
			message = '承载服务未实现'
			break
		case 502:
			message = '网关错误'
			break
		case 503:
			message = '服务暂不可用'
			break
		case 504:
			message = '网关超时'
			break
		case 505:
			message = '暂不支持的 HTTP 版本'
			break
		default:
			message = '位置错误'
	}
	return message
}

/**
 * @returns  {AxiosResponse} result
 * @tutorial see more:https://github.com/onlyling/some-demo/tree/master/typescript-width-axios
 * @example
 * service.get<{data: string; code: number}>('/test').then(({data}) => { console.log(data.code) })
 */
const service = Axios.create({
	baseURL: domainManager().UploadUrl,
	timeout: 20000,
	headers: {
		"Content-Type": "application/x-www-form-urlencoded;"
	}
})



/**
 * @description 请求发起前的拦截器
 * @returns {AxiosRequestConfig} config
 */
service.interceptors.request.use(
	async (config: InternalAxiosRequestConfig) => {
		return config;
	},
	error => {
		//TODO:  新增网络请求异常处理业务
		return Promise.reject(error)
	}
)

/**
 * @description 响应收到后的拦截器
 * @returns {}
 */
service.interceptors.response.use(

	/** 请求有响应 */
	async (response: AxiosResponse) => {
		if (response.status === 200) {
			if(response.data.resultCode == ApiResult.TOKEN_ILLEGAL || response.data.resultCode == ApiResult.TOKEN_INVALID){
				
			}
			datas = response
			return Promise.resolve(datas)
		} else {
			const __text = getErrorCode2text(response)
			return Promise.reject(new Error(__text))
		}
	},
	/** 请求无响应 */
	(error: AxiosError) => {
		if (error && error.response) {
			const __text = getErrorCode2text(error.response);
			return Promise.reject(new Error(__text));
		  } else {
			return Promise.reject(new Error('unknow error'));
		  }
	}
)

export default service
