import axios from 'axios';
import * as typeHelper from '@/utils/typeHelper';
import { warnToast, successToast } from '@/utils/toastHelper';
import { router } from '@/router';
import { createVNode } from 'vue';
import { useCommon } from '@/hooks/useCommon';
let { commomParams, ExclamationCircleOutlined, Modal } = useCommon();

const msgModel = (val) => {
	Modal.confirm({
		title: val,
		centered: true,
		icon: createVNode(ExclamationCircleOutlined),
		okText: '确认',
		onOk() {

		},
		onCancel() {

		},
	});
}

const instance = axios.create({
	// baseURL: 'https://admin1.jcjob.cn/api',
	baseURL: 'https://rcsc-test.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:
			msgModel(response.data.msg)
			break;
		case 0:
			break;
		case 1:
			return response;
			break;
		case 401:
			msgModel(response.data.msg)
		case 403:
			msgModel(response.data.msg)
			break;
		case 404:
			break;
		case 600:
			if (response.data.errors && Object.keys(response.data.errors).length > 0) {
				msgModel(response.data.errors)
			} else {
				msgModel(response.data.msg)
			}
			break;
		default:
			msgModel(response.data.msg)
		// warnToast(response.data.msg);
	}
	// 2xx 范围内的状态码都会触发该函数。
	// 对响应数据做点什么
	return response;
}, function (error) {
	// 超出 2xx 范围的状态码都会触发该函数。
	// 对响应错误做点什么
	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 => {
		console.log(err)
		cb(err.response)
	})
}