import axios from 'axios'
import { layer } from '@layui/layer-vue'

const config = {
	timeout: 600000,
	//baseURL: "http://124.222.104.55:58178/",
	baseURL: "http://localhost:58178/",
	// baseURL: "http://plm-pw-test.hbflavor.com:81/",
	headers: {
		'Content-Type': 'application/json;charset=UTF-8',
	},
	async: false
}
// let userToken = "";
// let userToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJGSUQiOjIsIkZVc2VyIjoib2F0ZXN0MiIsIkZOYW1lIjoi5rWL6K-V5bel5Y6CIiwiRkV4cGlyZVRpbWUiOiIyMDIzLTAxLTE3IDIwOjIwOjA1In0.ZNN-fVE1JJ3tN82pM9DylqqMMpMUVLZWJKTBwz8M3bU"
let userToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJGSUQiOjIsIkZVc2VyIjoib2F0ZXN0MSIsIkZOYW1lIjoi6ZmI5YevX1RFU1QiLCJGRXhwaXJlVGltZSI6IjIwMjMtMDQtMTcgMjA6MjQ6MTYifQ.v00Pm6eqVNlA-TRTBAsmVPw1z7ZbO1Fd0S4mUi-_uzI"

//获取上传信息
export function getUploadInfo(param: any) {
	let temps = param.url;
	param.url = config.baseURL + temps
	if (temps[0] == "/" && config.baseURL[config.baseURL.length - 1] == "/") {
		param.url = param.url.replace("/" + temps, temps);
	}
	param.headers = param.headers || {};
	param.headers.token = localStorage.getItem('token') || userToken;
	param.headers.ticket = getQueryString("ticket") || getQueryString("token") || "";
	return param;
};

export const getQueryString = (name: string) => {
	var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	var r = window.location.search.substr(1).match(reg);
	if (r != null) {
		return decodeURIComponent(r[2]);
	}
	return null;
}

class Http {
	service: any;
	constructor(config: any) {
		this.service = axios.create(config)
		/* 请求拦截 */
		this.service.interceptors.request.use((config: any) => {
			config.headers.token = localStorage.getItem('token') || userToken;
			config.headers.ticket = getQueryString("ticket") || getQueryString("token") || "";
			return config;
		}, error => {
			console.log("error");
			return Promise.reject(error);
		});

		/* 响应拦截 */
		this.service.interceptors.response.use((response: any) => {
			const data = response.data;
			console.log(data)
			let ticket = data.Ticket || "";
			if (ticket && ticket.length > 10) {
				let index = ticket.indexOf("http");
				if (index != -1 && index < 5) window.location.href = ticket;
				else localStorage.setItem('token', ticket);
			}
			if (data.Code != "200") {
				let message = data.Message || `接口异常`;
				if (layer) {
					layer.msg(message, { time: 3000, icon: 2 });
				} else {
					alert(message);
				}
				return data;
			}
			else {
				return data;
			}
		}, error => {
			layer.msg(error, { time: 3000, icon: 2 });
			return Promise.reject(error)
		});
	}

	/* GET 方法 */
	get<T>(url: string, params?: object, _object = {}): Promise<any> {
		return this.service.get(url, { params, ..._object });
	}
	/* POST 方法 */
	post<T>(url: string, params?: object, _object = {}): Promise<any> {
		return this.service.post(url, params, _object);
	}
}

export default new Http(config);
