!(function () {
  // 检查是否为1688页面，如果不是则直接返回
  if (location.href.indexOf(".1688.com") == -1 && location.href.indexOf("1688.com") == -1) {
    console.log("❌ 非1688页面，脚本退出");
    return;
  }
  
  // 添加明显的调试信息
  console.log("🎯 1688.js 脚本开始执行！");
  console.log("📍 当前页面URL:", location.href);
  console.log("🔧 Chrome对象类型:", typeof chrome);
  console.log("📦 Chrome runtime类型:", typeof chrome.runtime);
  
  // 在Manifest V3和Edge浏览器中，chrome.extension不存在，所以移除这个条件判断
  // 直接执行主要逻辑，确保在所有浏览器中都能正常工作
  console.log("✅ 开始执行主要逻辑");
  
  // tiddp 已抽到 common/js/order-scraper-common.js

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

  let tewceds = setInterval(function () {
    if ($("#xq-login-main")[0]) {
      clearInterval(tewceds);
      console.log("🔍 找到登录主容器，添加控制面板");
      $("#xq-login-main").append(vad);
      
      if (sessionStorage.ahacefwe == "1") {
        sessionStorage.ahacefwe = 0;
        offs = !0;
        vad
          .find("#poacewew")
          .text("停止上传")
          .css("background-color", "#F44336");
        tmoce = setInterval(function () {
          if ($(".order-logistics-container").length) {
            clearInterval(tmoce);
            tmoce = setTimeout(function () {
              opacewe = sinda1d.val() | 0;
              opacewe2 = sessionStorage.fsdgfdsgfdsg | 0;
              bdcwewe();
            }, 800);
          }
        }, 500);
      }
    }
  }, 500);
  
  let sinda1d = vad.find("#sinda1d").val(localStorage.poacewe || 2000),
    sinda2d = vad.find("#sinda2d").val(localStorage.poacewe2 || 30),
    boysew = 0,
    boyecw = 0,
    xuaweew = 0;

  let offs = false,
    tmoce = 0,
    opacewe,
    opacewe2;
    
  // 初始化按钮状态
  vad.find("#poacewew").text("上传订单").css("background-color", "#2A62FF");
    
  vad.find("#poacewew").click(async function () {
    clearTimeout(tmoce);
    if (offs) {
      offs = false;
      $(this).text("上传订单").css("background-color", "#2A62FF");
      sessionStorage.ahacefwe = 0;
      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('.1688.com') !== -1,
      siteMismatchMsg: '请在1688订单页面使用此功能',
      getCount: () => opacewe2,
      emptyCountMsg: '请输入页数',
    });
    if (!token) return;
    sessionStorage.setItem('token', token); // 翻页后继续使用
    offs = true;
    bdcwewe(token);
  });

  function bdcwewe(token) {
    console.log("🚀 开始处理订单数据");
    if (offs) {
      // 只在1688页面使用新的处理逻辑
      if (location.href.indexOf(".1688.com") != -1) {
        // 直接尝试查找Shadow DOM中的订单
        let foundInShadow = 0;
        let shadowOrderItems = [];

        try {
          let appRoot = document.querySelector("body > article > app-root");
          if (appRoot && appRoot.shadowRoot) {
            let orderList = appRoot.shadowRoot.querySelector(
              "div > main > q-theme > order-list"
            );
            if (orderList && orderList.shadowRoot) {
              let orderItems = orderList.shadowRoot.querySelectorAll(
                "div > div.order-list-content > order-item"
              );
              foundInShadow = orderItems.length;
              shadowOrderItems = Array.from(orderItems);
              console.log(`🔍 在Shadow DOM中找到${foundInShadow}个订单`);
            }
          }
        } catch (e) {
          console.log("❌ Shadow DOM查找出错:", e);
        }

        if (foundInShadow > 0) {
          processShadowOrderItems(shadowOrderItems, token);
        } else {
          processDataTrackerElements(token);
        }
        return; // 重要：直接返回，不执行下面的旧逻辑
      }
    }
  }

  // 处理Shadow DOM中的order-item元素
  function processShadowOrderItems(orderItems, token) {
    console.log(`🔄 开始处理${orderItems.length}个Shadow DOM订单`);
    let uyae = [];
    let pendingRequests = []; // 存储待完成的快递号获取请求

    // 获取快递单号的Promise函数
    function getTrackingNumberPromise(detailUrl, orderId) {
      return new Promise((resolve) => {
        sendMessageToBackgroudScript({
          action: "getTrackingNumber1688",
          url: detailUrl
        }, function(response) {
          // 不再单独打印快递号响应，而是在后续合并打印
          if (response && response.trackingNumber) {
            resolve({ orderId, trackingNumber: response.trackingNumber });
          } else {
            resolve({ orderId, trackingNumber: null, error: response ? response.error : '无响应' });
          }
        });
      });
    }

    orderItems.forEach((orderElement, index) => {
      let orderId = orderElement.getAttribute("data-tracker");
      if (orderId) {
        // 尝试从Shadow DOM中获取更多订单信息
        try {
          if (orderElement.shadowRoot) {
            // 尝试获取订单号 - 适配新版结构
            let actualOrderId = orderId; // 默认使用data-tracker值
            
            // 方法1：查找新版结构 <span class="order-id"><copy-to-clipboard text="订单号">
            let orderIdSpan = orderElement.shadowRoot.querySelector(".order-id");
            if (orderIdSpan) {
              let copyToClipboard = orderIdSpan.querySelector("copy-to-clipboard");
              if (copyToClipboard) {
                let textAttr = copyToClipboard.getAttribute("text");
                if (textAttr && textAttr.length > 10) {
                  actualOrderId = textAttr.trim();
                  console.log(`📋 从text属性获取订单号: ${actualOrderId}`);
                } else {
                  // 如果text属性没有，尝试从内容中提取
                  let copyText = copyToClipboard.textContent || '';
                  let orderMatch = copyText.match(/(\d{13,})/); // 匹配13位以上数字
                  if (orderMatch) {
                    actualOrderId = orderMatch[1];
                    console.log(`📋 从内容提取订单号: ${actualOrderId}`);
                  }
                }
              }
            }
            
            // 方法2：兼容旧版结构
            if (actualOrderId === orderId) {
              let orderIdElement = orderElement.shadowRoot.querySelector(
                ".order-id copy-to-clipboard a"
              );
              if (orderIdElement) {
                actualOrderId = orderIdElement.textContent.trim();
                console.log(`📋 从旧版结构获取订单号: ${actualOrderId}`);
              }
            }

            // 尝试获取价格信息
            let price = "0.00";

            // 方法1：查找order-item-total-price组件
            let totalPriceComponent = orderElement.shadowRoot.querySelector(
              "order-item-total-price"
            );
            if (totalPriceComponent && totalPriceComponent.shadowRoot) {
              let priceDiv =
                totalPriceComponent.shadowRoot.querySelector(".total-price");
              if (priceDiv) {
                price = priceDiv.textContent.replace(/[^\d.]/g, "");
              }
            }

            // 尝试获取物流信息
            let trackingNumber = "";
            let orderStatusPrompt = "未发货";

            // 查找物流状态信息，适配新的DOM结构
            try {
              // 方法1：查找order-item-status元素（根据截图中的结构）
              let orderItemStatus = orderElement.shadowRoot.querySelector('order-item-status');
              if (orderItemStatus && orderItemStatus.shadowRoot) {
                console.log(orderItemStatus);
                
                // 方法1.1：查找popup-logistics元素（根据用户提供的结构）
                let popupLogistics = orderItemStatus.shadowRoot.querySelector('popup-logistics');
                if (popupLogistics && popupLogistics.shadowRoot) {
                  // 查找 a > span > span.logistics-status 结构
                  let statusSpan = popupLogistics.shadowRoot.querySelector('a span span.logistics-status');
                  if (statusSpan) {
                    let statusText = statusSpan.textContent || '';
                    console.log('🔍 popup-logistics物流状态文本:', statusText);
                    
                    // 判断物流状态
                    if (statusText.includes("已签收") || statusText.includes("签收")) {
                      orderStatusPrompt = "已签收";
                    } else if (statusText.includes("已发货") || statusText.includes("发货")) {
                      orderStatusPrompt = "已发货";
                    }
                  }
                  
                  // 查找快递单号（可能在同一个a标签内）
                  let logisticsLink = popupLogistics.shadowRoot.querySelector('a');
                  // if (logisticsLink && !trackingNumber) {
                  //   let linkText = logisticsLink.textContent || '';
                  //   console.log('🔍 物流链接文本:', linkText);
                    
                  //   // 提取快递单号（匹配10位以上字母数字组合）
                  //   let trackingMatch = linkText.match(/[A-Za-z0-9]{10,}/);
                  //   if (trackingMatch) {
                  //     trackingNumber = trackingMatch[0];
                  //     console.log('🔍 提取的快递单号:', trackingNumber);
                  //   }
                  // }
                }
                
                // 方法1.2：如果popup-logistics没找到，回退到查找.logistics-status
                if (orderStatusPrompt === "未发货") {
                  let logisticsStatus = orderItemStatus.shadowRoot.querySelector('.logistics-status');
                  if (logisticsStatus) {
                    let statusText = logisticsStatus.textContent || '';
                    console.log('🔍 物流状态文本:', statusText);
                    
                    // 判断物流状态
                    if (statusText.includes("已签收") || statusText.includes("签收")) {
                      orderStatusPrompt = "已签收";
                    } else if (statusText.includes("已发货") || statusText.includes("发货")) {
                      orderStatusPrompt = "已发货";
                    }
                  }
                }
                
                // 查找物流详情元素获取快递单号
                let logisticsStr = orderItemStatus.shadowRoot.querySelector('.logistics-str');
                if (logisticsStr && !trackingNumber) {
                  let logisticsText = logisticsStr.textContent || '';
                  console.log('🔍 物流详情文本:', logisticsText);
                  
                  // 提取快递单号（匹配10位以上字母数字组合）
                  let trackingMatch = logisticsText.match(/[A-Za-z0-9]{10,}/);
                  if (trackingMatch) {
                    trackingNumber = trackingMatch[0];
                    console.log('🔍 提取的快递单号:', trackingNumber);
                  }
                }
              }
              
              // 方法2：如果方法1失败，尝试查找buyer-order-logistics-status-info元素
              if (orderStatusPrompt === "未发货") {
                let logisticsContainer = orderElement.shadowRoot.querySelector('.buyer-order-logistics-status-info');
                if (logisticsContainer) {
                  // 直接从第一个子DIV元素提取快递单号
                  let firstChildDiv = logisticsContainer.querySelector('div:first-child');
                  
                  if (firstChildDiv) {
                    let firstDivText = firstChildDiv.textContent || '';
                    console.log('🔍 物流文本:', firstDivText);
                    
                    // 简单提取冒号后面的内容作为快递单号
                    let colonIndex = firstDivText.indexOf('：');
                    if (colonIndex === -1) {
                      colonIndex = firstDivText.indexOf(':');
                    }
                    
                    if (colonIndex !== -1) {
                      trackingNumber = firstDivText.substring(colonIndex + 1).trim();
                    }
                  }

                  // 判断物流状态
                  let logisticsText = logisticsContainer.textContent || '';
                  if (
                    logisticsText.includes("已领取") ||
                    logisticsText.includes("签收") ||
                    logisticsText.includes("包裹已签收") ||
                    logisticsText.includes("已投递")
                  ) {
                    orderStatusPrompt = "已签收";
                  } else if (trackingNumber) {
                    orderStatusPrompt = "已发货";
                  }
                }
              }
            } catch (e) {
              console.log(`⚠️ 获取物流信息出错:`, e.message);
            }

            let orderInfo = {
              orderid: actualOrderId,
              pic: price || "0.00",
              number: trackingNumber,
              prompt: orderStatusPrompt,
            };

            // 为Shadow DOM元素添加标记（通过设置属性）
            orderElement.setAttribute("processed", "true");
            orderElement.style.border = "3px solid #4ECDC4";

            // 如果没有获取到快递单号，添加到待处理队列
            if (!orderInfo.number || orderInfo.number === "") {
              console.log(`🔍 未获取到快递单号，尝试从详情页获取: ${actualOrderId}`);
              
              // 构造详情页URL
              let orderIdPart = actualOrderId.match(/\d+/)?.[0] || actualOrderId;
              let detailUrl = `https://air.1688.com/app/ctf-page/trade-order-detail/index.html?orderId=${orderIdPart}`;
              console.log(`🔧 构造详情页链接: ${detailUrl}`);
              
              // 添加到Promise队列
              pendingRequests.push({
                promise: getTrackingNumberPromise(detailUrl, actualOrderId),
                orderId: actualOrderId
              });
            }

            uyae.push(orderInfo);
            console.log(`✅ 处理订单${index + 1}:`, orderInfo);
            console.log(`� 订单号获取详情 - data-tracker: ${orderId}, 实际订单号: ${actualOrderId}`);
          }
        } catch (e) {
          // 回退到基本信息
          let orderInfo = {
            orderid: orderId,
            pic: "0.00",
            number: "",
            prompt: "未发货",
          };
          uyae.push(orderInfo);
          console.log(`⚠️ 订单${index + 1}处理出错，使用基本信息:`, orderInfo);
        }
      }
    });

    // 处理所有待完成的快递号请求
    if (pendingRequests.length > 0) {
      console.log(`⏳ 开始处理${pendingRequests.length}个待获取快递号的订单`);
      
      Promise.all(pendingRequests.map(item => item.promise))
        .then(results => {
          console.log(`📦 所有快递号请求完成，结果:`, results);
          
          // 更新快递号到对应订单
          results.forEach(result => {
            if (result.trackingNumber) {
              const orderIndex = uyae.findIndex(item => item.orderid === result.orderId);
              if (orderIndex !== -1) {
                uyae[orderIndex].number = result.trackingNumber;
                uyae[orderIndex].prompt = "已发货";
                console.log(`� 订单${result.orderId}信息与快递号:`, {
                  orderInfo: uyae[orderIndex],
                  trackingNumber: result.trackingNumber
                });
              }
            } else {
              console.warn(`⚠️ 订单${result.orderId}获取快递号失败`);
            }
          });
          
          // 所有数据准备好后发送
          sendOrderData(uyae, token);
        })
        .catch(error => {
          console.error(`❌ 获取快递号过程出错:`, error);
          // 即使出错也发送数据
          sendOrderData(uyae, token);
        });
    } else {
      // 没有待处理请求，直接发送数据
      sendOrderData(uyae, token);
    }
  }

  // 处理data-tracker元素作为备选方案
  function processDataTrackerElements(token) {
    console.log("🔄 开始处理data-tracker元素");
    let trackerElements = document.querySelectorAll("[data-tracker]");

    let uyae = [];
    let pendingRequests = []; // 存储待完成的快递号获取请求
    let processedIds = new Set(); // 避免重复处理相同ID

    // 获取快递单号的Promise函数
    function getTrackingNumberPromise(detailUrl, orderId) {
      return new Promise((resolve) => {
        sendMessageToBackgroudScript({
          action: "getTrackingNumber1688",
          url: detailUrl
        }, function(response) {
          // 不再单独打印快递号响应，而是在后续合并打印
          if (response && response.trackingNumber) {
            resolve({ orderId, trackingNumber: response.trackingNumber });
          } else {
            resolve({ orderId, trackingNumber: null, error: response ? response.error : '无响应' });
          }
        });
      });
    }

    trackerElements.forEach((element, index) => {
      let orderId = element.getAttribute("data-tracker");
      let textContent = element.textContent || "";
      let className = element.className || "";

      // 更智能的过滤条件
      let isOrderElement =
        orderId &&
        orderId.length > 10 && // ID长度合理
        !processedIds.has(orderId) && // 未处理过
        (textContent.includes("订单") ||
          textContent.includes("交易") ||
          className.includes("order") ||
          element.tagName.toLowerCase().includes("order") ||
          orderId.match(/^\d{13,}/)); // 看起来像时间戳的长数字ID

      if (isOrderElement) {
        processedIds.add(orderId);
        let orderInfo = {
          orderid: orderId,
          pic: "0.00",
          number: "",
          prompt: "未发货",
        };

        element.style.backgroundColor = "#b3ffcb";
        element.style.border = "2px solid #4ECDC4";

        // 如果没有获取到快递单号，添加到待处理队列
        if (!orderInfo.number || orderInfo.number === "") {
          console.log(`🔍 订单${orderId}未获取到快递单号，添加到待处理队列`);
          
          // 构造详情页URL
          let orderIdPart = orderId.match(/\d+/)?.[0] || orderId;
          let detailUrl = `https://air.1688.com/app/ctf-page/trade-order-detail/index.html?orderId=${orderIdPart}`;
          console.log(`🔧 构造详情页链接: ${detailUrl}`);
          
          // 添加到Promise队列
          pendingRequests.push({
            promise: getTrackingNumberPromise(detailUrl, orderId),
            orderId: orderId
          });
        }

        uyae.push(orderInfo);
        console.log(`✅ 处理订单${index + 1}:`, orderInfo);
      }
    });

    // 处理所有待完成的快递号请求
    if (pendingRequests.length > 0) {
      console.log(`⏳ 开始处理${pendingRequests.length}个待获取快递号的订单`);
      
      Promise.all(pendingRequests.map(item => item.promise))
        .then(results => {
          console.log(`📦 所有快递号请求完成，结果:`, results);
          
          // 更新快递号到对应订单
          results.forEach(result => {
            if (result.trackingNumber) {
              const orderIndex = uyae.findIndex(item => item.orderid === result.orderId);
              if (orderIndex !== -1) {
                uyae[orderIndex].number = result.trackingNumber;
                uyae[orderIndex].prompt = "已发货";
                console.log(`� 订单${result.orderId}信息与快递号:`, {
                  orderInfo: uyae[orderIndex],
                  trackingNumber: result.trackingNumber
                });
              }
            } else {
              console.warn(`⚠️ 订单${result.orderId}获取快递号失败`);
            }
          });
          
          // 所有数据准备好后发送
          sendOrderData(uyae, token);
        })
        .catch(error => {
          console.error(`❌ 获取快递号过程出错:`, error);
          // 即使出错也发送数据
          sendOrderData(uyae, token);
        });
    } else {
      // 没有待处理请求，直接发送数据
      sendOrderData(uyae, token);
    }
  }

  // getCookies 已抽到 common/js/order-scraper-common.js

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

  // 完成订单处理的公共逻辑
  function finishOrderProcessing() {
    // 先更新页数计数器
    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;
    }
    let orderListFooter = null;
    try {
      let appRoot = document.querySelector("body > article > app-root");
      if (appRoot && appRoot.shadowRoot) {
        let orderList = appRoot.shadowRoot.querySelector(
          "div > main > q-theme > order-list"
        );
        if (orderList && orderList.shadowRoot) {
          orderListFooter =
            orderList.shadowRoot.querySelector("order-list-footer");
        }
      }
    } catch (e) {
      console.log("❌ Shadow DOM查找出错:", e);
    }

    if (orderListFooter && orderListFooter.shadowRoot) {
      // 递归遍历Shadow DOM查找翻页按钮
      function findNextButtonInShadowDOM(element, depth = 0) {
        if (!element || !element.shadowRoot) {
          return null;
        }
        
        // 在当前Shadow DOM中查找翻页按钮
        let buttons = element.shadowRoot.querySelectorAll('button, [role="button"], a, [class*="next"], [class*="page"], [class*="ui-page"]');
        
        // 检查当前层的按钮
        for (let btn of buttons) {
          let btnText = btn.textContent || '';
          let btnClass = btn.className || '';
          let btnAriaLabel = btn.getAttribute('aria-label') || '';
          
          // 检查是否是翻页按钮
          if (btnText.includes('下一页') || btnText.includes('Next') || 
              btnClass.includes('next') || btnClass.includes('ui-page-next') ||
              btnAriaLabel.includes('下一页') || btnAriaLabel.includes('Next')) {
            return btn;
          }
        }
        
        // 如果当前层没找到，递归查找子元素的Shadow DOM
        let allElements = element.shadowRoot.querySelectorAll('*');
        
        for (let el of allElements) {
          // 跳过已经检查过的按钮元素
          if (el.tagName === 'BUTTON' || el.tagName === 'A' || el.getAttribute('role') === 'button') {
            continue;
          }
          
          // 递归查找子元素的Shadow DOM
          let foundButton = findNextButtonInShadowDOM(el, depth + 1);
          if (foundButton) {
            return foundButton;
          }
        }
        
        return null;
      }
      
      // 开始递归查找
      let nextButton = findNextButtonInShadowDOM(orderListFooter);
      
      if (nextButton) {
        // 检查按钮是否可用
        if (!nextButton.disabled) {
          tmoce = setTimeout(function () {
            sessionStorage.ahacefwe = 1;
            sessionStorage.fsdgfdsgfdsg = opacewe2;
            nextButton.click();
            
            // 翻页后等待页面加载完成，然后重新开始采集
            setTimeout(function() {
              let checkCount = 0;
              // 等待页面元素加载
              let checkInterval = setInterval(function() {
                checkCount++;
                
                let appRoot = document.querySelector("body > article > app-root");
                if (appRoot && appRoot.shadowRoot) {
                  let orderList = appRoot.shadowRoot.querySelector("div > main > q-theme > order-list");
                  if (orderList && orderList.shadowRoot) {
                    let orderItems = orderList.shadowRoot.querySelectorAll("div > div.order-list-content > order-item");
                    
                    if (orderItems.length > 0) {
                      clearInterval(checkInterval);
                      // 重新开始采集流程 - 需要保存token以便后续使用
                      // 从localStorage或sessionStorage中获取token
                      const savedToken = sessionStorage.getItem('token');
                      if (savedToken) {
                        processShadowOrderItems(Array.from(orderItems), savedToken);
                      } else {
                        console.error('❌ 翻页后无法获取token，无法继续处理');
                        // 尝试重新获取token
                        getCookies().then(cookie => {
                          if (cookie && cookie.token) {
                            sessionStorage.setItem('token', cookie.token);
                            processShadowOrderItems(Array.from(orderItems), cookie.token);
                          } else {
                            tiddp('用户登录已过期，请重新登录', 2000);
                            offs = false;
                            vad.find('#poacewew').text('上传订单').css('background-color', '#2A62FF');
                          }
                        });
                      }
                      return;
                    }
                  }
                }
                
                // 如果检查了10次还没找到，尝试手动触发
                if (checkCount >= 10) {
                  clearInterval(checkInterval);
                  // 从localStorage或sessionStorage中获取token
                  const savedToken = sessionStorage.getItem('token');
                  if (savedToken) {
                    bdcwewe(savedToken);
                  } else {
                    console.error('❌ 翻页后无法获取token，无法继续处理');
                    // 尝试重新获取token
                    getCookies().then(cookie => {
                      if (cookie && cookie.token) {
                        sessionStorage.setItem('token', cookie.token);
                        bdcwewe(cookie.token);
                      } else {
                        tiddp('用户登录已过期，请重新登录', 2000);
                        offs = false;
                        vad.find('#poacewew').text('上传订单').css('background-color', '#2A62FF');
                      }
                    });
                  }
                  return;
                }
              }, 2000); // 每2秒检查一次
              
              // 最多等待30秒
              setTimeout(function() {
                clearInterval(checkInterval);
                // 从localStorage或sessionStorage中获取token
                const savedToken = sessionStorage.getItem('token');
                if (savedToken) {
                  bdcwewe(savedToken);
                } else {
                  console.error('❌ 翻页后无法获取token，无法继续处理');
                  // 尝试重新获取token
                  getCookies().then(cookie => {
                    if (cookie && cookie.token) {
                      sessionStorage.setItem('token', cookie.token);
                      bdcwewe(cookie.token);
                    } else {
                      tiddp('用户登录已过期，请重新登录', 2000);
                      offs = false;
                      vad.find('#poacewew').text('上传订单').css('background-color', '#2A62FF');
                    }
                  });
                }
              }, 30000);
            }, 6000); // 等待6秒后开始检查页面加载
          }, opacewe);
          return;
        } else {
          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;
        }
      } else {
        // 如果没找到分页组件，显示完成
        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;
      }
    } else {
      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");
    }
  }
  

  
  function dae() {
    // 只在订单相关页面执行，避免影响首页性能
    if (!location.href.includes('order') && 
        !location.href.includes('trade') && 
        !location.href.includes('transaction') &&
        !document.querySelector('.order-logistics-container') &&
        !document.querySelector('[class*="order"]')) {
      return; // 如果不是订单页面，直接返回
    }
    
    // 处理旧版本的订单列表结构
    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);
      }
    });

    // 处理新版本1688的data-tracker结构
    Array.from(
      document.querySelectorAll('[data-tracker]:not([use="1"])')
    ).forEach((j) => {
      // 只处理看起来像订单元素的
      if (
        j.innerHTML &&
        (j.innerHTML.includes("订单") ||
          j.innerHTML.includes("交易") ||
          j.closest('[class*="order"]'))
      ) {
        j.setAttribute("use", "1");
        let trackerId = j.getAttribute("data-tracker");
        if (trackerId) {
          j.setAttribute("daid", trackerId);
        }
      }
    });
  }
  dae();
  setInterval(dae, 800);
  

})(); 