import axios from 'axios'
import { Notification, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'

let pending = []
let cancelToken = axios.CancelToken
let removePending = (config) => {
	for (let p in pending) {
		let key = +p
		let item = pending[key]
		if (item.url === config.url && item.method === config.method && JSON.stringify(item.params) === JSON.stringify(config.params) && JSON.stringify(item.data) === JSON.stringify(config.data)) {
			item.cancel('操作太频繁，请稍后再试')
			pending.splice(item, 1)
		}
	}
}

// axios 配置
var instance = axios.create({
	headers: {
		'Content-Type': 'application/json;charset=UTF-8'
	},
	timeout: 1000 * 30, //请求超时时间
	baseURL: process.env.VUE_APP_BASE_API, //请求默认地址
	withCredentials: true //允许请求携带cookie信息
})

instance.interceptors.request.use(
	(config) => {
		removePending(config)
		config.cancelToken = new cancelToken((c) => {
			pending.push({
				url: config.url,
				method: config.method,
				params: config.params,
				data: config.data,
				cancel: c
			})
		})
		if (getToken()) {
			config.headers['Authorization'] = 'Bearer ' + getToken()
		}
		// get请求映射params参数
		if (config.method === 'get' && config.params) {
			let url = config.url + '?' + tansParams(config.params)
			url = url.slice(0, -1)
			config.params = {}
			config.url = url
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

instance.interceptors.response.use(
	(response) => {
		removePending(response.config)
		const code = response.status || 200
		const msg = errorCode[code] || response.data.msg || errorCode['default']
		if (code === 401) {
			MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
				confirmButtonText: '重新登录',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				store.dispatch('LogOut').then(() => {
					location.href = '/index'
				})
			})
		} else if (code === 500) {
			Notification({
				title: 'code500',
				message: msg,
				type: 'error',
				duration: 2000,
				customClass: 'elemsg-notify'
			})
			return Promise.reject(new Error(msg))
		} else if (code === 501) {
			return { code: 501, data: {} }
		} else if (code !== 200) {
			return { code: 0, data: {} }
		} else {
			return response.data
		}
	},
	(error) => {
		console.log('err:' + error)
		let { message } = error
		if (message == 'Network Error') {
			message = '后端接口连接异常'
		} else if (message.includes('timeout')) {
			message = '系统接口请求超时'
		} else if (message.includes('Request failed with status code')) {
			message = '系统接口' + message.substr(message.length - 3) + '异常'
		} else if (error.includes('Cancel')) {
			message = '操作太频繁，请稍后再试'
		} else {
			message = '系统错误，请联系管理员'
		}
		notif(message)
	}
)
function notif(msg) {
	Notification({
		message: msg,
		type: 'error',
		duration: 3000,
		customClass: 'elemsg-notify'
	})
}
function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + '='
		if (value !== null && typeof value !== 'undefined') {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && typeof value[key] !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + '='
						result += subPart + encodeURIComponent(value[key]) + '&'
					}
				}
			} else {
				result += part + encodeURIComponent(value) + '&'
			}
		}
	}
	return result
}
export default instance
