!(function(){
	if(chrome.extension || typeof chrome === 'undefined'){
		// tiddp、getCookies 已抽到 common/js/order-scraper-common.js，通过作用域链引用

		// 控制面板（通过 common/js/order-scraper-common.js 的 createOrderPanel 工厂）
		var vad = createOrderPanel({ countLabel: '上传前面几个' });

		// 只在content script上下文中动态注入脚本到页面
		if((location.href.indexOf('pdd.com') != -1 || location.href.indexOf('yangkeduo.com') != -1) && !window.pddScriptInjected) {
			window.pddScriptInjected = true;
			var a = document.createElement("script");
			a.type = "text/javascript", a.charset = "UTF-8", a.src = chrome.runtime.getURL("product/pdd.js"), document.documentElement.appendChild(a);
		}

		// 只在拼多多页面添加控制面板
		if(location.href.indexOf('pdd.com') != -1 || location.href.indexOf('yangkeduo.com') != -1) {
			let tewceds = setInterval(function(){
				if($('#xq-login-main')[0]){
					clearInterval(tewceds);
					$('#xq-login-main').append(vad);
				}
			},500);
		}

		let sinda1d = vad.find('#sinda1d').val(localStorage.poacewe||2000);
		let sinda2d = vad.find('#sinda2d').val(localStorage.poacewe2||30);
		let offs, tmoce=0, opacewe, opacewe2;
		var OPACEW;

		vad.find('#poacewew').click(async function(){
			clearTimeout(tmoce);
			if(offs){
				offs = false;
				$(this).text('上传订单').css('background-color','#2A62FF');
				return;
			}
			localStorage.poacewe = opacewe = sinda1d.val()|0;
			localStorage.poacewe2 = opacewe2 = sinda2d.val()|0;
			// 前置检查走 common/js/order-scraper-common.js 的 preflightUpload
			const token = await preflightUpload($(this), {
				siteMatch: u => u.indexOf('pdd.com') !== -1 || u.indexOf('yangkeduo.com') !== -1,
				siteMismatchMsg: '请在拼多多订单页面使用此功能',
				getCount: () => opacewe2,
			});
			if (!token) return;
			offs = true;
			OPACEW = $('.react-base-list>div[daid][yse!="1"]').map(function(){
				return $(this);
			}).get();
			opacewe2 = opacewe2 - $('.react-base-list>div[daid][yse="1"]').length;
			if(opacewe2 >= 0){
				poacwewe(0, token);
			}else{
				tiddp('全部数量上传完成');
			}
		});

		function poacwewe(i,token,oy){
			if(offs){
				if(OPACEW[i]){
					let tese = OPACEW[i].find('[data-test="订单状态"]').text();
					if(tese.includes('交易已取消')){
						OPACEW[i].attr('yse','1');
						tmoce = setTimeout(function(){
							poacwewe(i+1, token);
						},opacewe);
					}else{
						let id = OPACEW[i][0].getAttribute('daid');
						ajaxs('/order.html?order_sn='+id,e=>{
							if(e.includes('"交易已取消"')){
								OPACEW[i].attr('yse','1');
								tmoce = setTimeout(function(){
									poacwewe(i+1, token);
								},opacewe);
							}else{
								let trackingNumber = e.match(/"key":"快递单号：","value":"([^"]*)"/);
								let orderStatusPrompt = '未发货';
								if(trackingNumber){
									trackingNumber = trackingNumber[1];
									if(e.includes('包裹已签收！') || e.includes('"已签收"')){
										orderStatusPrompt = '已签收';
									}else{
										orderStatusPrompt = '已发货';
									}
								}else{
									trackingNumber = '';
									
									// 尝试其他可能的快递单号格式
									let alternativeTracking = e.match(/"快递单号":"([^"]*)"/);
									if(alternativeTracking){
										trackingNumber = alternativeTracking[1];
									}else{
										// 尝试更宽松的匹配
										let looseTracking = e.match(/快递单号[：:]\s*"?([^"\s]+)"?/);
										if(looseTracking){
											trackingNumber = looseTracking[1];
										}
									}
								};

								let orderpic = OPACEW[i].text().match(/实付:￥(\d+(\.\d+)?)/);
								if(orderpic){
									orderpic = orderpic[1];
									// 检查是否为先用后付的情况（实付价格为0）
									if(orderpic === '0'){
										// 尝试从括号中提取实际价格，支持多种格式
										let actualPriceMatch = OPACEW[i].text().match(/确认收货后自动付款[¥￥](\\d+(\\.\\d+)?)/);
										if(!actualPriceMatch){
											// 尝试其他可能的格式
											actualPriceMatch = OPACEW[i].text().match(/自动付款[¥￥](\\d+(\\.\\d+)?)/);
										}
										if(!actualPriceMatch){
											// 尝试匹配括号内的价格
											actualPriceMatch = OPACEW[i].text().match(/\\([^)]*[¥￥](\\d+(\\.\\d+)?)[^)]*\\)/);
										}
										if(actualPriceMatch){
											orderpic = actualPriceMatch[1];
										}
									}
									
									// 订单上传走 common/js/order-scraper-common.js
									submitDomesticOrder(
										{ orderid: id, pic: orderpic, number: trackingNumber, prompt: orderStatusPrompt },
										token,
										{
											qtype: 1,
											statusMap: { _default: 1, '已发货': 2, '已签收': 3 },
											getRemaining: () => opacewe2,
										}
									);

									opacewe2--;
									OPACEW[i].attr('yse','1').css('background-color','#b3ffcb');
									if(opacewe2>0){
										tmoce = setTimeout(function(){
											poacwewe(i+1, token);
										},opacewe);
									}else{
										tiddp('全部数量上传完成');
										vad.find('#poacewew').text('已全部上传成功').css('background-color','#4CAF50');
										setTimeout(function(){
											vad.find('#poacewew').text('上传订单').css('background-color','#2A62FF');
										}, 3000);
									} 
								}else{
									tiddp('没查到实付价格，可能网站改版本',100000);
								}
							}
						})
					}
				}else{	
					$('html').animate({scrollTop: document.documentElement.scrollHeight}, 500);
					tiddp('滚动');
					tmoce = setTimeout(function(){
						OPACEW = $('.react-base-list>div[daid][yse!="1"]').map(function(){
							return $(this);
						}).get();
						if(OPACEW.length){
							poacwewe(0, token);
						}else{
							if(oy){
								tiddp('全部上传完成');
								vad.find('#poacewew').text('已全部上传成功').css('background-color','#4CAF50');
								setTimeout(function(){
									vad.find('#poacewew').text('上传订单').css('background-color','#2A62FF');
								}, 3000);
							}else{
								poacwewe(0, token, true);
							}
						}
					},2000);
				}
			}
		};

		function ajaxs(url, ck) {
			fetch(url)
				.then(function(resp) { return resp.text(); })
				.then(function(text) { ck(text); })
				.catch(function() { ck(false); });
		};

	}else{
		// 拼多多页面注入的脚本部分
		function dae(){
			// 处理拼多多订单列表结构
			Array.from(document.querySelectorAll('.react-base-list>div[data]:not([use="1"])')).forEach(j => {
				j.setAttribute('use','1');
				
				let reactFiberKey = Object.keys(j).find(key => key.startsWith('__reactInternalInstance$'));
				if(reactFiberKey){
					j.setAttribute('daid',j[reactFiberKey].return.key);
				}
			});
		};
		dae();
		setInterval(dae,800);
	}
})();
	
