import axios from 'axios'
import { baseURL } from './base.js'
import router from '../router/index.js'
import store from '@/store'
import qs from 'qs'
import elementui from 'element-ui'
// 创建 axios 实例
const service = axios.create({
	baseURL: baseURL,
	withCredentials: false,// 是否跨站点访问控制请求
	timeout: 60000,
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded',//x-www-form-urlencoded
		// 'User_tokey':''
	}
})


// 请求拦截器
service.interceptors.request.use((config) => {
	config.data.User_tokey = store.state.userInfo.token
	config.data = qs.stringify(config.data)
	// config.headers['Authorization'] = '1' // 让每个请求携带自定义token  //设置请求头
	return config
}, (error) => {
	// 错误抛到业务代码
	error.data = {}
	return Promise.resolve(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
	showStatus(response.data)
	return response
}, (error) => {
	// 错误抛到业务代码
	// router.push({
	// 	path:'/error'
	// })
	elementui.Message.error('系统异常，联系管理员处理')
	error.data = {}
	return Promise.resolve(error)
})

const showStatus = (status) => {//状态码
	switch (status.Code) {
		case 200:
			break
		case 201:
			elementui.Message.error('登录过期，请重新登陆')
			store.commit('setuserInfo', {
				username: store.state.userInfo.bzd_username,
				password: store.state.userInfo.bzd_password,
				token: ''
			})
			setTimeout(function() {
				router.replace({
					name: 'login',
				})
			}, 1000)
			break	
		case 202:
			elementui.Message.error(status.Msg + '[' + status.Code + ']')
			break
		case 500:
			elementui.Message.error('服务器错误[' + status.Code + ']')
			break
		case 501:
			elementui.Message.error('服务未实现[' + status.Code + ']')
			break
		case 502:
			elementui.Message.error('网络错误[' + status.Code + ']')
			break
		default:
		elementui.Message.error(status.Msg + '[' + status.Code + ']')
	}
}

export {
	service as axios
}
