import axios from 'axios';
import {stringify} from 'qs'
import {BizError} from './types';
import {getAuthToken} from "@/hooks/useAuth.ts";
import useGlobalConfig from '@/hooks/useGlobalConfig';

const JSON_FORMAT: string = 'application/json';
const REQUEST_TIMEOUT = 300000; // 超时时长5min

const Axios = axios.create({
	timeout: REQUEST_TIMEOUT,
	headers: {'Content-Type': JSON_FORMAT}
})

const {globalConfig} = useGlobalConfig();
// 请求前拦截
Axios.interceptors.request.use(config => {
	const token = getAuthToken();
	if (globalConfig.i18n){
		let url = config.url;
		if(url){
			url += (url.indexOf('?') == -1?'?':'&') + `lang=${globalConfig.i18n || ''}`
			config.url = url;
		}

		//config.headers['language'] = globalConfig.i18n;
	}
	if (token) {
		config.headers['Token'] = `${token}`;
	}
	if (config.data && config.data instanceof FormData) {
		config.headers['Content-Type'] = 'multipart/form-data';
	}
	return config
}, err => {
	console.log('请求拦截器报错',err)
	return Promise.reject(err)
})


export function request<T>(options: RequestOption) {
	return new Promise<T>((resolve, reject) => {
		const {url, method, data, baseURL, getOriginResult} = options;

		Axios.request<APIResponse<T>>({
			url,
			method: method || 'get',
			data,
			baseURL: baseURL || AppConfig.API_PREFIX,
		}).then(res => {
			if (res.status != 200) {
				reject(new BizError("Service Internal Exception,Please Try Later!", res.status))
				return;
			}
			if (getOriginResult) {
				resolve(res.data as unknown as T)
				return;
			}
			// const
			const {code, msg, data, trace_id} = res.data
			if (code == 0) {
				resolve(data as unknown as T)
			} else {
				reject(new BizError(msg, code, trace_id, data as unknown as AllType))
			}
		}).catch(e => {
			reject(new BizError(e.message, 500))
		})
	})
}


export function post<T>(params: RequestOption | string, _data?: AllType) {
	const options = typeof params === 'string' ? {url: params} : params;
	if (_data) {
		options.data = _data
	}
	return request<T>({
		...options,
		method: 'post'
	})
}

export function get<T>(params: RequestOption|string) {
	const options = typeof params === 'string' ? {url: params} : params;
	if (options.data) {
		options.url += (options.url.indexOf('?') === -1 ? '?' : '&') + stringify(options.data)
	}
	return request<T>({
		...options,
		method: 'get'
	})
}

export function put<T>(params: RequestOption) {
	return request<T>({
		...params,
		method: 'put'
	})
}

export function getFileBlob(url: string) {
	return new Promise<Blob>((resolve, reject) => {
		fetch(url).then(res => res.blob()).then(res => {
			resolve(res)
		}).catch(reject);
	});
}
