
function addXMLRequestCallback(callback) {
	var oldSend, i;
	if (XMLHttpRequest.callbacks) {
		XMLHttpRequest.callbacks.push(callback);
	} else {
		XMLHttpRequest.callbacks = [callback];
		oldSend = XMLHttpRequest.prototype.send;
		XMLHttpRequest.prototype.send = function() {
			for (i = 0; i < XMLHttpRequest.callbacks.length; i++) {
				XMLHttpRequest.callbacks[i](this);
			}
			oldSend.apply(this, arguments);
		};
	}
}

function getUrlParams(url) {
	let params = {};

	function urlDecode(str) {
		return decodeURIComponent(
			String(str)
			.replace(/%(?![\da-f]{2})/gi, () => {
				return "%25";
			})
			.replace(/\+/g, "%20")
		);
	}
	url.replace(/[?&]+([^=&]+)=([^&]*)/gi, (str, key, value) => {
		params[key] = urlDecode(value);
	});
	return params;
}

addXMLRequestCallback(function(xhr) {
	xhr.addEventListener("load", function() {
		if (xhr.readyState == 4 && xhr.status == 200) {
			if (xhr.responseURL.indexOf("/ecom/captain/selection_pool/product_list") > -1) {
				// 团长选品库接口
				const querty = getUrlParams(xhr.responseURL);
				console.log('querty: ', querty)
				// 如果query_info为空，则不进行处理
				if (!querty.query_info) return;
				let { data } = JSON.parse(xhr.response);
				window.postMessage({
					action: 'onSelectionPoolProductList',
					data: data
				}, '*');
			} else if (xhr.responseURL.indexOf("/ecom/captain/captain_goods_pool/get_captain_goods_detail") > -1) {
				// 团长选品详情接口
				const querty = getUrlParams(xhr.responseURL);
				console.log('querty: ', querty)
				let { data } = JSON.parse(xhr.response);
				setTimeout(() => {
					window.postMessage({
						action: 'onSelectionPoolProductDetail',
						data: data
					}, '*');
				}, 500);
			} else if (xhr.responseURL.indexOf("/selection_cart_pc_api/card/m_get_card") > -1) {
				// 达人选品车接口
				console.log('达人选品车接口: ', xhr)
				const querty = getUrlParams(xhr.responseURL);
				// if (querty.status == 0) return;
				let { data } = JSON.parse(xhr.response);
				console.log('达人选品车接口data: ', data)
				window.postMessage({
					action: 'onGetGoodsCarList',
					data: {
						responseData: data?.cart_view_card[0] ?? {},
						params: xhr._data ? JSON.parse(xhr._data) : {}
					}
				}, '*');
			}
		}
	});
})
