import axios from 'axios';
import * as typeHelper from '@/utils/typeHelper';
import { message } from 'ant-design-vue';
import { router } from '@/router';

const instance = axios.create({
	baseURL: 'https://rcsc-test.jcjob.cn/api',
	// baseURL: 'https://admin1.jcjob.cn/api',
	timeout: 30000,
	headers: {
		'Content-Type': 'application/json'
	},
	withCredentials: false,
})
// 请求拦截
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
	sessionStorage.getItem('token') ? config.headers.Authorization = sessionStorage.getItem('token') : '';
	// 在发送请求之前做些什么
	return config;
}, function (error) {
	// 对请求错误做些什么
	return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
	switch (response.data.code) {
		case -1:
			message.warning(response.data.msg);
			break;
		case 0:

			break;
		case 1:
			return response;
			break;
		case 401:
			message.warning(response.data.msg);
			sessionStorage.clear();
			window.location.reload();
			router.replace('/login');
		case 403:
			message.warning(response.data.msg);
			break;
		case 600:
			if(response.data.errors) {
				response.data.errors.forEach((item:String) => {
					message.warning(item);
				})
			} else {
				message.warning(response.data.msg);
			}
			break;
		default: 
			console.log(response)

	}
	// 2xx 范围内的状态码都会触发该函数。
	// 对响应数据做点什么
	return response;
}, function (error) {
	// 超出 2xx 范围的状态码都会触发该函数。
	// 对响应错误做点什么
	console.log(error)
	return Promise.reject(error);
});

export const httpGet : Function = (url : string, data : object, cb : Function) => {
	instance.get(url, {
		params: data
	}).then(res => {
		const resData = res;
		typeHelper.isFunction(cb) && cb(resData);
	}).catch(err => {
		cb(err.response)
	})
}

export const httpPost : Function = (url : string, data : object, cb : Function) => {
	instance.post(url, data).then(res => {
		const resData = res;
		typeHelper.isFunction(cb) && cb(resData);
	}).catch(err => {
		cb(err.response)
	})
}