import axios from 'axios'
import {Message} from 'element-ui'
import {
	getToken,
	setToken
} from './auth.js'
import qs from 'qs'
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // api的base_url
	// baseURL:'https://ding.insys.g107.com/',
	timeout: 15000,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded',
	},
	transformRequest: [function(data) {
		return qs.stringify(data)
	}]
})
service.interceptors.request.use(
	config => {
		if (getToken()) {
			config.headers['A-Token'] = getToken()
			// config.headers['A-Token'] = ' eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvdGVzdC1kaW5nLmcxMDcuY29tXC9hcGlcL2RpbmdcL2xvZ2luIiwiaWF0IjoxNjA4MTAxMTUwLCJleHAiOjE2MDg3MDExNTAsIm5iZiI6MTYwODEwMTE1MCwianRpIjoiRzd0VURhUmNaYTg4bjF2cyIsInN1YiI6MTY2LCJwcnYiOiJjYTY0ODlkNTBmMjQwN2E2NzgzMGU4MDkwZDAxNDg4MzU2ODU5NjJiIiwicm9sZSI6ImVtcGxveWVlIn0.RIZhoHAsj4Ru_Ap3sKgyfiG1fayG1Hgw7si9aekU8eE'
		}
		// if (config.url == '/api/integral/statistics/ranking' || config.url == '/api/integral/review/apply'|| config.url == '/api/rule/import') {
		//   config.headers['Accept'] = 'application/vnd.test.v2+json'
		// }
		// if (config.url == '/api/integral/statistics/integral') {
		//   config.headers['Accept'] = 'application/json, text/plain, */*';
		// }
		return config
	},
	error => {
		Promise.reject(error)
	}
)

// respone interceptor
service.interceptors.response.use(
	response => {
		if (response.data.code === 1) {
			if(response.data.data.token){
				setToken(response.data.data.token);
			}else if (response.data.refresh_token) {
				if (response.data.refresh_token !== getToken()) {
					setToken(response.data.refresh_token);
				}
			}
			return response;
		} else if (response.data.code === 401) {
			Message({
				message: response.data.msg,
				type: 'error',
			})
			return Promise.reject(response.data.msg)
		}else{
			Message({
				message: response.data.msg,
				type: 'error',
			})
			return Promise.reject(response.data.msg)
		}
	},
	error => {
		// console.log(error)
		if(error.message=='interrupt'){
			// Message({
			// 	message: '请勿频繁切换页面',
			// 	type: 'warning',
			// })
			return Promise.reject(error.message)
		}else if(error.message=='Network Error'){
			Message({
				message: '网络异常，请检查网络是否畅通，再重新进入应用',
				type: 'error',
			})
			return Promise.reject(error.message)
		}else if(error.message=='timeout of 15000ms exceeded'){
			Message({
				message: '请求超时，请稍后再试',
				type: 'error',
			})
			return Promise.reject(error.message)
		}else{
			Message({
				message: error.message,
				type: 'error',
			})
			return Promise.reject(error.message)
		}
	}
)

export default service
