import axios from 'axios'
import {
	baseURL,
	contentType,
	messageName,
	requestTimeout,
	statusName,
	successCode,
} from '@/config/net.config'
// import router from '@/router'
import configpath from 'config/setting.config.js'
let baseURL1 = ''
let isAction, isDataAll;
const inforeq = (cb) => {
	fetch('/static/.config.json')
		.then((res) =>res = res.json()).then((res)=>{
			let obj = {
				...res,
				img_local_host: (process.env.NODE_ENV === 'production' ?
					res.prodIp || configpath.prodIp :
					process.env.NODE_ENV === 'test' ?
					res.testIp || configpath.testIp :
					res.devIp || configpath.devIp) + '/file/',
				// 请求 地址
				baseURL: (process.env.NODE_ENV === 'production' ?
					res.prodIp || configpath.prodIp :
					process.env.NODE_ENV === 'test' ?
					res.testIp || configpath.testIp :
					res.devIp || configpath.devIp) + '/api/h5',
			}
			baseURL1 = obj.baseURL
			cb && cb()
		})
}
inforeq()
/**
 * axios响应拦截器
 * @param data response数据
 * @param status HTTP status
 * @param statusText HTTP status text
 * @returns {Promise<*|*>}
 */
const handleData = async ({
	config,
	data,
	status,
	statusText
}) => {

	// 若data.code存在,覆盖默认code
	let code = data && data[statusName] ? data[statusName] : status
	// 若code属于操作正常code,则status修改为200
	switch (code) {
		case 200:
			// 业务层级错误处理,以下是假定restful有一套统一输出格式(指不管成功与否都有相应的数据格式)情况下进行处理
			// 例如响应内容:
			// 错误内容:{ code: 1, msg: '非法参数' }
			// 正确内容:{ code: 200, data: {  }, msg: '操作正常' }
			// return data
			// if (isAction)
			// Vue.prototype.$baseNotify(
			//   data[messageName],
			//   '消息提示',
			// )
			return data
		case 401:
			// store
			//   .dispatch('user/resetAll')
			//   .then(() =>
			//     router.push({ path: '/login', replace: true }).then(() => { })
			//   )
			break
		case 403:
			// router.push({ path: '/403' }).then(() => { })
			break
	}
	if (isDataAll) {
		return data
	}
	// 异常处理
	// 若data.msg存在,覆盖默认提醒消息
	//  const errMsg = `${data && data[messageName]
	// ? data[messageName]
	// : CODE_MESSAGE[code]
	// 	? CODE_MESSAGE[code]
	// 	: statusText
	// }`
	// console.log(data)
	return Promise.reject(data)
}

/**
 * @description axios初始化
 */
const instance = axios.create({
	baseURL,
	timeout: requestTimeout,
	headers: {
		'Content-Type': contentType,
	},
})

let pendingMap = new Map();
let removePending = function(config) {
	var key = `${config.method}:${config.url}:${JSON.stringify(config.params)}`;
	var func = pendingMap.get(key);
	if (func) {
		func();
		pendingMap.delete(key);
	}
}

/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(
	(config) => {
		config.baseURL = baseURL1
		// const token = store.getters['user/token']
		// config.baseURL = store.getters['user/locationpath'].baseURL
		removePending(config);
		// 发送请求,并将请求的取消标识放入pendingMap中
		config.cancelToken = new axios.CancelToken((cancelToken) => {
			pendingMap.set(`${config.method}:${config.url}:${JSON.stringify(config.params)}`, cancelToken)
		});
		// 规范写法 不可随意自定义
		// if (token) config.headers['token'] = token
		if (
			config.data &&
			config.headers['Content-Type'] ===
			'application/x-www-form-urlencoded;charset=UTF-8'
		)
			config.data = JSON.stringify(config.data)
		isAction = config.isAction
		isDataAll = config.isDataAll
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

/**
 * @description axios响应拦截器
 */
let url = '',
	path1 = ''
instance.interceptors.response.use(
	(response) => {
		const config = response.config
		url = `${config.method}:${config.url}:${JSON.stringify(config.params)}`;
		path1 = config.url
		return handleData(response)
	},
	(error) => {
		const {
			response
		} = error
		// console.log(response)
		if (response === undefined) {
			if (path1 !== '/eye/save_hand_img') {
				// Vue.prototype.$baseMessage(
				//   '网络错误',
				//   'error',
				//   'vab-hey-message-error'
				// )
			} else {
				pendingMap.delete(key);
			}
			return Promise.reject({
				code: -1
			})
		} else return handleData(response)
	}
)

export default instance