//api路径
import { isNotEmptyUtils } from "@/utils/index";

export default async(url = '', data = {}, type = 'POST', method = 'fetch',server='CONTENT') => {
	type = type.toUpperCase();

	// url = (server==='WECHAT'?wechatUrl:baseUrl) + url;
    if (url.match("^http") == null){
        url = localStorage.getItem("Url") + url;
		}
		
		
	console.log("完整url:",url)
    if (type == 'GET' && data) {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '?' + dataStr;
            // url = encodeURI(url + '?' + dataStr, true);
		}
	}

	if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',
            method: type,
            // mode: "cors",
            headers: {
                // 'Access-Control-Allow-Origin': '*',
                'Accept': '*',
                'Content-Type': 'application/json',
                // 'token': localStorage.getItem('token') || null, //固定传header：
                // 'system_code': 'todo'   //固定传header：系统编号
            },
        }

        if (type == 'POST' || type === 'PUT' || type === 'PATCH' || type === 'DELETE' && data) {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
		try {
			const response = await fetch(url, requestConfig);
			const responseJson = await response.json();

			return responseJson
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST' || type == 'DELETE' || type == 'PUT') {
				sendData = JSON.stringify(data);
			}

			requestObj.open(type, url, true);
			requestObj.setRequestHeader("Content-Type", "application/json");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response
						if (typeof obj !== 'object' && isNotEmptyUtils(obj)) {
							obj = JSON.parse(obj);
						}
						resolve(obj)
					} else {
						reject(requestObj)
					}
				}
			}
		})
	}
}
