import axios from 'axios'
import {Message} from 'element-ui'
import {getToken,setToken} from './auth.js'
import qs from 'qs'
import Router from '@/router'
const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, 
	// baseURL:'https://app109758.eapps.dingtalkcloud.com/',
	timeout: 20000,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded',
	},
	transformRequest: [function(data) {
		return qs.stringify(data)
	}]
})
let url='';
let data='';
service.interceptors.request.use(
	config => {
		url=config.url;
		data=qs.parse(config.data)
		if (getToken()) {
			config.headers['A-Token'] = getToken()
		}
		return config
	},
	error => {
		Promise.reject(error)
	}
)

service.interceptors.response.use(
	response => {
		if (response.data.code === 1) {
			if(response.data.data.token&&url!='/api/per/user/download_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 if(response.data.code === 5555){ //免登时用，5555为过期
			if(url=='/api/ding/login'){
				return response;
			}else{
				Message({
					message: response.data.msg,
					type: 'error',
				})
				Router.push({
				  path: '/noAccess'
				})
			}
		}else if(response.data.code === 4000||response.data.code === 4001){ //4000 ，4001 企业信息未同步
			return response
		}else{
			Message({
				message: response.data.msg,
				type: 'error',
			})
			return Promise.reject(response.data.msg)
		}
	},
	error => {
		if(error.message=='interrupt'){
			// Message({
			// 	message: '请勿频繁切换页面',
			// 	type: 'warning',
			// })
			return Promise.reject(error.message)
		}else if(error.message=='Network Error'){
			// Message({
			// 	message: '网络异常，请检查网络是否畅通，再重新进入应用',
			// 	type: 'error',
			// })
			console.log('网络异常，请检查网络是否畅通，再重新进入应用')
			return Promise.reject(error.message)
		}else if(error.message=='timeout of 20000ms 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
