import axios from 'axios'
import { Loading, MessageBox } from 'element-ui'
import notifi from '@/plugins/msg.js'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { blobValidate } from '@/utils/tiegu'
import errorCode from '@/utils/errorCode'
let downloadLoadingInstance
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('repeat submission')
			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
			})
		})
		// 是否需要设置 token
		const isToken = (config.headers || {}).isToken === false
		if (getToken() && !isToken) {
			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.data.code || 200
		const message = 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 !== 200) {
			notifi({ message, type: 'error' })
		}
		return response.data
	},
	error => {
		console.log(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 (message.includes('repeat')) {
			message = '操作太频繁，请稍后再试'
		} else {
			message = '系统错误，请联系管理员'
		}
		notifi({ message, type: 'error' })
		return { code: 0 }
	}
)
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 function download(url, params, filename) {
	downloadLoadingInstance = Loading.service({ text: '正在下载数据，请稍候', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' })
	return instance
		.post(url, params, {
			transformRequest: [
				params => {
					return tansParams(params)
				}
			],
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			responseType: 'blob'
		})
		.then(async data => {
			const isLogin = await blobValidate(data)
			if (isLogin) {
				const blob = new Blob([data])
				saveAs(blob, filename)
			} else {
				notifi({ message: '无效的会话，或者会话已过期，请重新登录。', type: 'error' })
			}
			downloadLoadingInstance.close()
		})
		.catch(r => {
			console.error(r)
			notifi({ message: '下载文件出现错误，请联系管理员！', type: 'error' })
			downloadLoadingInstance.close()
		})
}
export default instance
