import axios from 'axios'
import { Message } from 'element-ui'
import { Loading } from 'element-ui';
import CancelTokens from './CancelTokens'
const baseURL = '/api' //代理接口的名称
import { $addStorageEvent } from '../util/processingData'

//不需要带token 匿名访问的接口
const noTokenUrl = [
	`/marketall/btc/address`,
	`/marketall/list/interface?req=price&`,
	`/marketall/BTC/csupply`,
	`/marketall/btc/mintusd`,
	`/marketall/btc/marketcap`,
	`/marketall/BTC/mvrv`,
	`/marketall/BTC/btcbigtxcount`,
	`/marketall/BTC/bigamountvout`,
	`/marketall/BTC/arh99`,
	`/marketall/BTC/arh99day`,
	`/marketall/BTC/jzr60`,
	`/marketall/BTC/jzr60day`,
	`/marketall/BTC/ma730`,
	`marketall/BTC/ma730day`,
	`/marketall/ETH/csupply`,
	`/marketall/ETH/reward`,
	`/marketall/eth/ETHVolume`,
	`/marketall/eth/ETHFees`,
	`/marketall/eth/address`,
	`/marketall/ETH/ethbigtxcount`,
	`/marketall/ETH/ethbigtx`,
	`/eth/ethTopAddrList`,
	`/marketall/ETH/tronUsdtVolume`,
	`/marketall/eth/usdtVolume`,
	`/marketall/eth/usdcVolume`,
	`/marketall/ETH/tronUsdcVolume`,
	`/marketall/market/NDAQohlc`,
	`/marketall/market/NDAQma`,

]

let overtime = "" //同页面多次请求超时只报错一次
window.addEventListener("setItem", () => {
	 overtime = localStorage.getItem("overtime");
});
Message.customClass = "messageClass"
let message = '' //登录过期控制只提示一次报错

//开发环境 development
if (process.env.NODE_ENV == 'development') {
	// axios.defaults.baseURL = 'http://10.168.2.197:7001'
	// axios.defaults.baseURL = 'https://13.214.133.132:11447'
	// axios.defaults.baseURL = 'http://10.168.2.125:7101'
	axios.defaults.baseURL = 'https://coinbus.cc/api/v1'

}
//生产环境 production
if (process.env.NODE_ENV == 'production') {
	axios.defaults.baseURL = 'https://coinbus.cc/api/v1'
	// xios.defaults.baseURL = 'https://13.214.133.132:11447'
}
//测试环境
if (process.env.NODE_ENV === "staging") {
	axios.defaults.baseURL = "https://coinbus.cc/api/v1"
}
//创建一个axios对象
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API,
	timeout: 1000,// 10000
});
// 添加请求拦截器(post)
service.interceptors.request.use( config =>{
	if (config.url.includes('/fapi/v1/fundingRate') || config.url.includes('/fapi/v1/openInterest') || config.url.includes('/futures/data/takerlongshortRatio')) {
		config.baseURL = baseURL
		// config.baseURL = `https://fapi.binance.com`
		// config.baseURL = 'https://binancezh.jp'
	}
	else if(config.url.includes('transfer/endOrder')){
		config.timeout = 60000//充值确认接口单独设置响应时间1分钟
	
	
	}else if(config.url.includes('levelUp')){
		config.timeout = 30000//消费升级接口改为30秒
	}else{
		config.timeout = 10000
	}

	// token 
	if (!noTokenUrl.includes(config.url)) {
		const token = localStorage.token;
		if (token) {

			config.headers.Authorization = `Bearer ${token}`
		}
	}

	return config
},error=> {
	// if (error.code == "ECONNABORTED") {
	// 	console.log(overtime,"几个都降低");
	// 	if (!overtime) {
	// 		overtime ="请求超时"
	// 		Message({//请求超时
	// 			showClose: true,
	// 			message: window.vm.$i18n.t('login.timeout'),
	// 			type: 'error',
	// 			customClass: "messageClass",
	// 			duration: 10000,
	// 		});
	// 	}
	
	// }

	// if (error.response.status >= 500) {//服务器错误  	
	// 	console.log("甲方劲夫劲夫附件");
	// 	Message({
	// 		showClose: true,
	// 		message: window.vm.$i18n.t('login.server'),
	// 		type: 'error',
	// 		customClass: "messageClass"
	// 	});
	// }

	// 对请求错误做些什么
	return Promise.reject(error)
})


// 添加请求拦截器
// token注入
axios.interceptors.request.use(function (config) {
	if (config.url.includes('/fapi/v1/fundingRate') || config.url.includes('/fapi/v1/openInterest') || config.url.includes('/futures/data/takerlongshortRatio')) {
		config.baseURL = baseURL
		// config.baseURL = `https://fapi.binance.com`
		// config.baseURL = 'https://binancezh.jp'
	}
	// config.headers={
	// 	appid:"565656"
	// }w'i'zhi
	// token 
	if (!noTokenUrl.includes(config.url)) {
		const token = localStorage.token;
		if (token) {

			config.headers.Authorization = `Bearer ${token}`
		}
	}



	return config
}, (error) => {
	// 对请求错误做些什么
	return Promise.reject(error)
})


//响应超时的时间
axios.defaults.timeout = 10000;
service.defaults.timeout = 10000;

// 设置请求次数，请求的间隙
axios.defaults.retry = 1;
axios.defaults.retryDelay = 1000;
var axiosResError = ""
// 添加响应拦截器
axios.interceptors.response.use(
	
	res => {
		
			// console.log(res,"响应数据111");
		if (res.config.baseURL !== "https://fapi.binance.com") {
		
				if (res.data.code == 421) {//登录过期删除token 421
					//清空就是拦截到过期就删除了token 把两外两个存成空
					console.log("登录过期");			
					localStorage.removeItem("token");	
					$addStorageEvent(1, "username", '')
					$addStorageEvent(1, "loginTime", '')			
					localStorage.setItem("identity", JSON.stringify({}))
					$addStorageEvent(1, "dialogLoginVisible",JSON.stringify(true) );//弹出登录
					
				if(!message){
					message = res.data.msg
					Message({
						message: res.data.msg,
						type: 'warning',
						customClass: "messageClass",
						duration: 3000,
						showClose: true,
					});
				}

				}else if(res.data.code == 401){//登录才能查看的页面
					if (!overtime) {
						overtime ="登录才能查看的页面"
						Message({
							message: window.vm.$i18n.t('login.viewPage'),
							type: 'error',
							customClass: "messageClass",
							showClose: true,
	
						});
					}
				
				}else if(res.data.code !== 200){
					console.log(`!== 200`,res);
					Message({
						message: res.data.msg,
						type: 'error',
						customClass: "messageClass"

					});
				}

		}

		return res;
	}, error => {

		if (error.code == "ECONNABORTED") {
			if (!overtime) {
				overtime ="请求超时"
				Message({//请求超时
					showClose: true,
					message: window.vm.$i18n.t('login.timeout'),
					type: 'error',
					customClass: "messageClass",
					showClose: true,
					duration: 4000,
				});
			
			}
		}

		console.log('err' + error)
		let { message } = error;
		if (message == "Network Error") {//后端接口连接异常,请刷新重试
		  message = window.vm.$i18n.t('login.linkError') 
		}
		else if (message.includes("timeout")) {//超时
		  message = window.vm.$i18n.t('login.timeout') 
		}
		else if (message.includes("Request failed with status code")) {//系统接口异常5...
		  message = window.vm.$i18n.t('login.system') + message.substr(message.length - 3);
		}
		if (!overtime) {
			overtime=message
			Message({
				message: message,
				type: 'error',
				showClose: true,
				duration: 5 * 1000
			  })
		}
		// Message({
		//   message: message,
		//   type: 'error',
		//   duration: 5 * 1000
		// })
		return Promise.reject(error)

	}

);
var serviceResError=""
// 添加响应拦截器 post
service.interceptors.response.use(
	
	res=>{	
	
		if (res.data.code == 421) {//登录过期删除token 421
			//清空就是拦截到过期就删除了token 把两外两个存成空			
			localStorage.removeItem("token");		

			$addStorageEvent(1, "username", '')
			$addStorageEvent(1, "loginTime", '')			
			localStorage.setItem("identity", JSON.stringify({}))
			$addStorageEvent(1, "dialogLoginVisible",JSON.stringify(true) );
          
         
          
       
			console.log(message,"service 1 ");
			if(!message){//登录过期 控制报错信息只提示一次

				message = res.data.msg
				Message({
					message: res.data.msg,
					type: 'error',
					customClass: "messageClass",
					duration: 3000,
					showClose: true,
				});
			}

		}else if(res.data.code == 401){//登录才能查看的页面
			if  (!overtime) {
				overtime=`登录才能查看的页面`
				Message({
					message: window.vm.$i18n.t('login.viewPage'),
					type: 'error',
					customClass: "messageClass",
					showClose: true,
	
				});
			}
		
		}else if(res.data.code !== 200){
			console.log(`!== 200`,res);
			Message({
				message: res.data.msg,
				type: 'error',
				customClass: "messageClass",
				showClose: true,

			});
		}

	



		return res;
	},
	error=>{
		
		
		if (error.code == "ECONNABORTED") {
			if (!overtime) {
				overtime ="请求超时"
				Message({//请求超时
					showClose: true,
					message: window.vm.$i18n.t('login.timeout'),
					type: 'error',
					customClass: "messageClass",
					showClose: true,
					duration: 4000,
				});
			
			}
		}

		

		console.log('err5555555555555' + error)
		let { message } = error;
		if (message == "Network Error") {
			message = window.vm.$i18n.t('login.linkError') 
		}
		else if (message.includes("timeout")) {
			message = window.vm.$i18n.t('login.timeout') 
		}
		else if (message.includes("Request failed with status code")) {
			message = window.vm.$i18n.t('login.system') + message.substr(message.length - 3);
		}
		if (!overtime) {
			overtime=message
			Message({
				message: message,
				type: 'error',
				showClose: true,
				duration: 5 * 1000
			  })
		}
		// Message({
		//   message: message,
		//   type: 'error',
		//   duration: 5 * 1000
		// })
		return Promise.reject(error)
		
		
	}
)

// 封装 get 方法
export function get(url, params) {
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: params
		}).then(res => {
			resolve(res)
		}).catch(err => {
			reject(err)
			return
		})
	})
}

// 封装 post方法
export function POST(url, data) {
	return new Promise((resolve, reject) => {
		axios.post(url, data)
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}

// 封装 delete方法
export function Delete(url) {
	return new Promise((resolve, reject) => {
		axios.delete(url)
			.then(res => {
				resolve(res)
			})
			.catch(err => {
				reject(err)
			})
	})
}


export default service;

