!(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: '上传几页' });

		// 只在淘宝页面添加控制面板
		if(location.href.indexOf('taobao.com') != -1 || location.href.indexOf('tmall.com') != -1) {
			let tewceds = setInterval(function(){
				// 尝试多种选择器，找到合适的位置添加控制面板
				if ($("#xq-login-main")[0]) {
				    clearInterval(tewceds);
				    console.log("🔍 找到登录主容器，添加控制面板");
				    $("#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('taobao.com') !== -1 || u.indexOf('tmall.com') !== -1,
				siteMismatchMsg: '请在淘宝订单页面使用此功能',
				getCount: () => opacewe2,
			});
			if (!token) return;
			offs = true;
			processTBOrders(token);
		});

		// 处理淘宝订单
		async function processTBOrders(token) {
			console.log('🚀 开始处理淘宝订单');
			if (!offs) return;
			
			let uyae = [];
			
			// 从页面中提取订单信息
			// 查找所有订单容器
			let orderContainers = $('[id^="orderColContainer_"]');
			console.log(`🔍 找到${orderContainers.length}个订单容器`);
			
			// 使用for循环代替each，以便支持async/await
			for (let i = 0; i < orderContainers.length; i++) {
				if (!offs) break; // 停止处理
				
				let index = i;
				let element = orderContainers[i];
				let orderId = '';
				let trackingNumber = '';
				let status = '未发货';
				let price = '0.00';
				
				// 从容器ID中提取订单号
				let containerId = $(element).attr('id');
				if (containerId) {
					let orderIdMatch = containerId.match(/orderColContainer_(\d+)/);
					if (orderIdMatch && orderIdMatch[1]) {
						orderId = orderIdMatch[1];
					}
				}
				
				// 提取价格
				let priceElement = $(element).find('.trade-price-container.priceReal--WTJj6AoT .trade-price-integer');
				if (priceElement.length > 0) {
					let integerPart = priceElement.text().trim();
					let decimalPart = $(element).find('.trade-price-container.priceReal--WTJj6AoT .trade-price-decimal').text().trim();
					price = integerPart + '.' + decimalPart;
				} else {
					// 尝试其他价格选择器
					let alternativePrice = $(element).text().match(/实付款[:：]\s*￥?(\d+(\.\d+)?)/);
					if (alternativePrice && alternativePrice[1]) {
						price = alternativePrice[1];
					}
				}
				
				// 提取物流状态 - 改进状态识别
				let statusText = '';
				let statusElements = $(element).find('.shopInfoStatus--InnfaPAJ, .order-status, .status-info, .trade-status, [class*="status"], [class*="Status"]');
				if (statusElements.length > 0) {
					statusText = statusElements.text().trim();
				} else {
					// 从整个订单容器中提取状态文本
					statusText = $(element).text().trim();
				}
				
				console.log(`🔍 订单${orderId}状态文本: ${statusText}`);
				
				// 精准匹配状态，确保返回用户期望的三种状态之一
				if (statusText.includes('已签收') || statusText.includes('签收')) {
					status = '已签收';
				} else if (statusText.includes('运输中') || statusText.includes('派送中') || statusText.includes('配送中') || statusText.includes('已发货')) {
					status = '运输中';
				} else if (statusText.includes('待发货') || statusText.includes('未发货')) {
					status = '待发货';
				}
				console.log(`✅ 订单${orderId}状态: ${status}`);
				
				// 提取快递单号 - 重写逻辑，确保每个订单对应正确的快递号
				console.log(`🔍 尝试提取订单${orderId}的快递单号`);
				let trackingNumberFound = false;
				
				// 重要：为每个订单创建独立的快递单号变量，避免共享
				let orderTrackingNumber = '';
				
				// 方法1：在当前订单容器内查找多种文本匹配模式
				let container = $(element);
				let containerText = container.text();
				
				// 多种匹配模式，限制在当前订单容器内
				const patterns = [
					/快递单号[:：]\s*([A-Za-z0-9]{10,})/,
					/物流单号[:：]\s*([A-Za-z0-9]{10,})/,
					/运单号码[:：]\s*([A-Za-z0-9]{10,})/,
					/单号[:：]\s*([A-Za-z0-9]{10,})/,
					/[A-Za-z0-9]{12,}/
				];
				
				for (let pattern of patterns) {
					let textMatch = containerText.match(pattern);
					if (textMatch) {
						orderTrackingNumber = textMatch[1] || textMatch[0];
						if (orderTrackingNumber && /[A-Za-z0-9]{10,}/.test(orderTrackingNumber)) {
							console.log(`✅ 方法1 - 从订单容器文本获取到快递单号: ${orderTrackingNumber}`);
							trackingNumberFound = true;
							break;
						}
					}
				}
				
				// 方法2：查找订单容器内的快递单号元素
				if (!trackingNumberFound) {
					const expressIdSelectors = [
						'.expressId--zegtKfpq',
						'.express-id',
						'.logistics-id',
						'.tracking-number',
						'[class*="express"][class*="id"]',
						'[class*="logistics"][class*="id"]',
						'[class*="tracking"][class*="number"]'
					];
					
					for (let selector of expressIdSelectors) {
						let expressElement = container.find(selector);
						if (expressElement.length > 0) {
							orderTrackingNumber = expressElement.text().trim();
							if (orderTrackingNumber && /[A-Za-z0-9]{10,}/.test(orderTrackingNumber)) {
								console.log(`✅ 方法2 - 从${selector}获取到快递单号: ${orderTrackingNumber}`);
								trackingNumberFound = true;
								break;
							}
						}
					}
				}
				
				// 方法3：尝试鼠标悬浮"查看物流"按钮，显示弹窗后获取
				if (!trackingNumberFound) {
					let logisticsButtons = container.find('.trade-button:contains(查看物流), [text*="查看物流"], [class*="logistics"] a, [class*="express"] a');
					if (logisticsButtons.length > 0) {
						console.log(`🔍 方法3 - 尝试鼠标悬浮查看物流按钮`);
						let button = logisticsButtons[0];
						
						// 先移除所有可能的弹窗，避免干扰
						let existingPopovers = document.querySelectorAll('.ant-popover, .logisticPopoverContent--MaLWhCj9');
						existingPopovers.forEach(popover => {
							popover.remove();
						});
						
						// 模拟鼠标悬浮事件
						let mouseoverEvent = new MouseEvent('mouseover', {
							bubbles: true,
							cancelable: true
						});
						button.dispatchEvent(mouseoverEvent);
						
						// 等待弹窗显示
						await new Promise(resolve => setTimeout(resolve, 800));
						
						// 查找最新显示的弹窗
						let visiblePopovers = document.querySelectorAll('.ant-popover:not(.ant-popover-hidden), .logisticPopoverContent--MaLWhCj9');
						if (visiblePopovers.length > 0) {
							// 只检查最新出现的弹窗
							let latestPopover = visiblePopovers[visiblePopovers.length - 1];
							let popoverText = latestPopover.textContent;
							let textMatch = popoverText.match(/([A-Za-z0-9]{10,})/);
							if (textMatch && textMatch[1]) {
								orderTrackingNumber = textMatch[1];
								console.log(`✅ 方法3 - 从最新弹窗获取到快递单号: ${orderTrackingNumber}`);
								trackingNumberFound = true;
							}
						}
						
						// 关闭弹窗
						let mouseoutEvent = new MouseEvent('mouseout', {
							bubbles: true,
							cancelable: true
						});
						button.dispatchEvent(mouseoutEvent);
					}
				}
				
				// 方法4：实现点击查看物流按钮跳转获取快递号，然后关闭窗口，自动处理跳转提示
				if (!trackingNumberFound) {
					let logisticsButtons = container.find('.trade-button:contains(查看物流), [text*="查看物流"], [class*="logistics"] a, [class*="express"] a');
					if (logisticsButtons.length > 0) {
						console.log(`🔍 方法4 - 尝试点击查看物流按钮跳转获取快递号`);
						let button = logisticsButtons[0];
						
						// 保存当前窗口URL，用于恢复
						let originalUrl = window.location.href;
						
						// 点击物流按钮
						button.click();
						
						// 等待可能的跳转提示框出现
						await new Promise(resolve => setTimeout(resolve, 1000));
						
						// 自动点击"已知晓，立即前往"按钮
						console.log(`🔍 检查并处理跳转提示框`);
						let confirmButtons = document.querySelectorAll('.ant-btn-primary, .ant-modal-confirm-btn-primary, [class*="confirm"]');
						let confirmFound = false;
						let newWindow = null;
						
						for (let confirmBtn of confirmButtons) {
							let buttonText = confirmBtn.textContent || confirmBtn.innerText;
							if (buttonText.includes('已知晓') || buttonText.includes('立即前往')) {
								console.log(`✅ 找到跳转提示框，自动点击确认按钮`);
								confirmBtn.click();
								confirmFound = true;
								break;
							}
						}
						
						// 等待跳转完成
						await new Promise(resolve => setTimeout(resolve, 2000));
						
						// 构造物流详情页URL模板
						const logisticsUrlTemplate = 'https://market.m.taobao.com/app/dinamic/pc-trade-logistics/home.html?orderId={orderId}&entrance=pc&spm=tbpc.boughtlist.order_op';
						
						// 直接构造物流详情页URL并打开
						let logisticsUrl = logisticsUrlTemplate.replace('{orderId}', orderId);
						console.log(`🔍 构造物流详情页URL: ${logisticsUrl}`);
						
						// 打开物流详情页
						let logisticsWindow = window.open(logisticsUrl, '_blank');
						if (logisticsWindow && !logisticsWindow.closed) {
							console.log(`✅ 成功捕获到新打开的窗口`);
							
							// 等待物流详情页加载完成
							await new Promise(resolve => setTimeout(resolve, 3000));
							
							try {
								// 在物流详情页中提取快递单号
								console.log(`🔍 开始从物流详情页提取快递单号`);
									
								// 方法1：查找特定的快递单号元素
								const detailPageSelectors = [
									'.expressId--zegtKfpq',
									'.rax-text-v2.desc',
									'.express-id',
									'.logistics-id',
									'.tracking-number',
									'.order-logistics-info',
									'.logistics-info',
									'[class*="express"][class*="id"]',
									'[class*="logistics"][class*="id"]',
									'[class*="tracking"][class*="number"]',
									'.ant-descriptions-item-content',
									'.desc',
									'.express-num',
									'.logistics-num',
									'.waybill-num',
									'[data-logistics-id]',
									'[class*="bill"]',
									'[class*="express"]'
								];
									
								let foundTracking = false;
								for (let selector of detailPageSelectors) {
									let detailElements = logisticsWindow.document.querySelectorAll(selector);
									for (let detailElement of detailElements) {
										let elementText = detailElement.textContent || detailElement.innerText;
										console.log(`🔍 检查物流详情页元素${selector}: ${elementText}`);
										
										// 直接查找快递单号（支持字母+数字）
										let textMatch = elementText.match(/([A-Za-z0-9]{10,20})/);
										if (textMatch && textMatch[1]) {
											orderTrackingNumber = textMatch[1];
											console.log(`✅ 方法4 - 从物流详情页${selector}获取到快递单号: ${orderTrackingNumber}`);
											trackingNumberFound = true;
											foundTracking = true;
											break;
										}
										
										// 查找包含快递单号的文本
										if (elementText.includes('快递单号') || elementText.includes('物流单号') || elementText.includes('运单号码') || elementText.includes('单号')) {
											let match = elementText.match(/[A-Za-z0-9]{10,20}/);
											if (match && match[0]) {
												orderTrackingNumber = match[0];
												console.log(`✅ 方法4 - 从物流详情页${selector}文本获取到快递单号: ${orderTrackingNumber}`);
												trackingNumberFound = true;
												foundTracking = true;
												break;
											}
										}
									}
									if (foundTracking) break;
								}
								
								// 方法2：从物流详情页文本中提取所有10位以上的快递单号（支持字母+数字）
								if (!trackingNumberFound) {
									let pageText = logisticsWindow.document.body.textContent || logisticsWindow.document.body.innerText;
									let textMatches = pageText.match(/([A-Za-z0-9]{10,20})/g);
									if (textMatches && textMatches.length > 0) {
										// 过滤可能的订单号，只保留快递单号
										let filteredMatches = textMatches.filter(match => {
											// 排除当前订单号
											if (match === orderId) return false;
											// 排除长度超过20位的可能不是快递单号的数字
											if (match.length > 20) return false;
											return true;
										});
																		
										if (filteredMatches.length > 0) {
											orderTrackingNumber = filteredMatches[0];
											console.log(`✅ 方法4 - 从物流详情页文本提取到快递单号: ${orderTrackingNumber}`);
											trackingNumberFound = true;
										}
									}
								}
								
								// 方法3：在物流详情页中查找所有可能包含快递单号的元素
								if (!trackingNumberFound) {
									console.log(`🔍 尝试在物流详情页中进行更广泛的元素查找`);
									let allElements = logisticsWindow.document.querySelectorAll('*');
									for (let element of allElements) {
										let elementText = element.textContent || element.innerText;
										if (elementText.length > 10 && elementText.length < 50) {
											let match = elementText.match(/[A-Za-z0-9]{10,20}/);
											if (match && match[0]) {
												// 排除可能的订单号
												if (match[0] !== orderId) {
													orderTrackingNumber = match[0];
													console.log(`✅ 方法4 - 从物流详情页广泛查找获取到快递单号: ${orderTrackingNumber}`);
													trackingNumberFound = true;
													break;
												}
											}
										}
										if (trackingNumberFound) break;
									}
								}
								
							} catch (e) {
								console.error(`❌ 从物流详情页提取快递单号出错:`, e);
							} finally {
								// 关闭物流详情页
								if (logisticsWindow && !logisticsWindow.closed) {
									logisticsWindow.close();
									console.log(`✅ 已关闭物流详情页`);
								}
							}
						} else {
							// 检查当前窗口是否已经导航到详情页
							let currentWindowUrl = window.location.href;
							if (currentWindowUrl !== originalUrl) {
								console.log(`✅ 当前窗口已导航到详情页: ${currentWindowUrl}`);
								
								// 等待详情页加载完成
								await new Promise(resolve => setTimeout(resolve, 3000));
								
								try {
									// 查找快递单号，增强提取逻辑
									console.log(`🔍 开始从详情页提取快递单号`);
										
									// 方法1：查找特定的快递单号元素
									const detailPageSelectors = [
										'.expressId--zegtKfpq',
										'.rax-text-v2.desc',
										'.express-id',
										'.logistics-id',
										'.tracking-number',
										'.order-logistics-info',
										'.logistics-info',
										'[class*="express"][class*="id"]',
										'[class*="logistics"][class*="id"]',
										'[class*="tracking"][class*="number"]',
										'.ant-descriptions-item-content',
										'.desc',
										'.express-num',
										'.logistics-num',
										'.waybill-num',
										'[data-logistics-id]',
										'[class*="bill"]',
										'[class*="express"]'
									];
										
									let foundTracking = false;
									for (let selector of detailPageSelectors) {
										let detailElements = document.querySelectorAll(selector);
										for (let detailElement of detailElements) {
											let elementText = detailElement.textContent || detailElement.innerText;
											console.log(`🔍 检查元素${selector}: ${elementText}`);
											
											// 直接查找快递单号（支持字母+数字）
											let textMatch = elementText.match(/([A-Za-z0-9]{10,20})/);
											if (textMatch && textMatch[1]) {
												orderTrackingNumber = textMatch[1];
												console.log(`✅ 方法4 - 从${selector}获取到快递单号: ${orderTrackingNumber}`);
												trackingNumberFound = true;
												foundTracking = true;
												break;
											}
																					
											// 查找包含快递单号的文本
											if (elementText.includes('快递单号') || elementText.includes('物流单号') || elementText.includes('运单号码') || elementText.includes('单号')) {
												let match = elementText.match(/[A-Za-z0-9]{10,20}/);
												if (match && match[0]) {
													orderTrackingNumber = match[0];
													console.log(`✅ 方法4 - 从${selector}文本获取到快递单号: ${orderTrackingNumber}`);
													trackingNumberFound = true;
													foundTracking = true;
													break;
												}
											}
										}
										if (foundTracking) break;
									}
									
									// 方法2：从页面文本中提取所有10位以上的快递单号（支持字母+数字）
									if (!trackingNumberFound) {
										let pageText = document.body.textContent || document.body.innerText;
										let textMatches = pageText.match(/([A-Za-z0-9]{10,20})/g);
										if (textMatches && textMatches.length > 0) {
											// 过滤可能的订单号，只保留快递单号
											let filteredMatches = textMatches.filter(match => {
												// 排除当前订单号
												if (match === orderId) return false;
												// 排除长度超过20位的可能不是快递单号的数字
												if (match.length > 20) return false;
												return true;
											});
																				
											if (filteredMatches.length > 0) {
												orderTrackingNumber = filteredMatches[0];
												console.log(`✅ 方法4 - 从详情页文本提取到快递单号: ${orderTrackingNumber}`);
												trackingNumberFound = true;
											}
										}
									}
									
									// 方法3：查找所有可能包含快递单号的元素
									if (!trackingNumberFound) {
										console.log(`🔍 尝试更广泛的元素查找`);
										let allElements = document.querySelectorAll('*');
										for (let element of allElements) {
											let elementText = element.textContent || element.innerText;
											if (elementText.length > 10 && elementText.length < 50) {
												let match = elementText.match(/[A-Za-z0-9]{10,20}/);
												if (match && match[0]) {
													// 排除可能的订单号
													if (match[0] !== orderId) {
														orderTrackingNumber = match[0];
														console.log(`✅ 方法4 - 从广泛查找获取到快递单号: ${orderTrackingNumber}`);
														trackingNumberFound = true;
														break;
													}
												}
											}
											if (trackingNumberFound) break;
										}
									}
									
								} catch (e) {
									console.error(`❌ 从详情页提取快递单号出错:`, e);
								}
								
								// 返回原始页面
								window.history.back();
								// 等待页面返回
								await new Promise(resolve => setTimeout(resolve, 1000));
							} else {
								console.log(`⚠️ 当前窗口未导航，也未捕获到新窗口`);
							}
						}
					}
				}
				
				// 将独立变量赋值给全局变量
				trackingNumber = orderTrackingNumber;
				
				// 清理快递单号，移除可能的"2026"后缀和特殊字符，但保留字母和数字
				if (trackingNumber) {
					// 移除可能的"2026"后缀
					trackingNumber = trackingNumber.replace(/2026$/, '');
					// 移除所有非字母数字字符（保留字母和数字）
					trackingNumber = trackingNumber.replace(/[^A-Za-z0-9]/g, '');
					// 只保留10位以上的快递单号
					let match = trackingNumber.match(/[A-Za-z0-9]{10,}/);
					if (match) {
						trackingNumber = match[0];
					} else {
						trackingNumber = '';
						trackingNumberFound = false;
					}
					console.log(`✅ 清理后快递单号: ${trackingNumber}`);
				}
				
				if (!trackingNumberFound) {
					console.log(`❌ 未找到订单${orderId}的快递单号`);
					trackingNumber = '';
				}
				
				// 如果找到了订单号，添加到订单列表
				if (orderId) {
					let orderInfo = {
						orderid: orderId,
						pic: price,
						number: trackingNumber,
						prompt: status
					};
					uyae.push(orderInfo);
					console.log(`✅ 处理订单${index + 1}:`, orderInfo);
				}
			}
			
			// 发送订单数据
			sendOrderData(uyae, token);
		}

		// 发送订单数据到后台 —— 底层上传逻辑走 common/js/order-scraper-common.js
		async function sendOrderData(orderData, token) {
			console.log(`📤 准备发送${orderData.length}个淘宝订单到后台`);
			await submitDomesticOrdersBatch(orderData, token, {
				qtype: 2,
				statusMap: { _default: 1, _empty: 4, '运输中': 2, '已签收': 3 },
				getRemaining: () => opacewe2,
				shouldContinue: () => offs,
				intervalMs: opacewe,
			});
			finishOrderProcessing(token);
		}

		// 完成订单处理的公共逻辑
		function finishOrderProcessing(token) {
			// 先更新页数计数器
			opacewe2--;
			
			// 检查是否还有剩余页数
			if (opacewe2 <= 0) {
				vad
					.find("#poacewew")
					.text("已全部上传成功")
					.css("background-color", "#4CAF50");
				setTimeout(function () {
					vad
						.find("#poacewew")
						.text("上传订单")
						.css("background-color", "#2A62FF");
					// 重置offs状态，确保下次点击可以直接开始上传
					offs = false;
					console.log("✅ 所有订单上传完成，重置offs状态为false");
				}, 3000);
				// 立即重置offs状态，避免在延迟期间点击按钮出现问题
				offs = false;
				console.log("✅ 所有订单上传完成，立即重置offs状态为false");
				return;
			}
			
			// 查找并点击下一页按钮
			console.log("🔍 寻找下一页按钮");
			
			// 尝试多种选择器查找分页元素
			let nextPageButton = null;
			const paginationSelectors = [
				'.ant-pagination-next:not(.ant-pagination-disabled) button',
				'.pagination-next a',
				'.page-next a',
				'[class*="next"]:not([disabled])',
				'[text*="下一页"]:not([disabled])'
			];
			
			for (let selector of paginationSelectors) {
				if ($(selector)[0]) {
					nextPageButton = $(selector);
					console.log("✅ 找到下一页按钮:", selector);
					break;
				}
			}
			
			if (nextPageButton) {
				// 点击下一页按钮
				console.log("✅ 点击下一页按钮");
				nextPageButton.click();
				
				// 等待页面加载完成，然后继续处理
				tmoce = setTimeout(function() {
					// 等待新页面内容加载
					let checkCount = 0;
					let checkInterval = setInterval(function() {
						checkCount++;
						
						// 检查是否有新的订单容器加载
						let newOrderContainers = $('[id^="orderColContainer_"]');
						if (newOrderContainers.length > 0) {
							clearInterval(checkInterval);
							console.log("✅ 新页面订单加载完成，继续处理");
							// 继续处理订单
							processTBOrders(token);
						} else if (checkCount >= 20) {
							// 最多检查20次，每次间隔1秒
							clearInterval(checkInterval);
							console.log("⚠️ 无法加载新页面订单，停止处理");
							// 重置状态
							offs = false;
							vad.find("#poacewew").text("上传订单").css("background-color", "#2A62FF");
						}
					}, 1000);
				}, opacewe);
			} else {
				// 没有找到下一页按钮，停止处理
				console.log("⚠️ 未找到下一页按钮，停止处理");
				offs = false;
				vad.find("#poacewew").text("上传订单").css("background-color", "#2A62FF");
			}
		}
		// sendMessageToBackgroudScript 用全局版本（js/sendmessage.js，支持 2 参数和 3 参数调用）
	}
})();