/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ 2:
/***/ ((__unused_webpack_module, exports) => {



Object.defineProperty(exports, "__esModule", ({
  value: true
}));
exports.waitDom = exports.sleep = exports.setStorage = exports.getStorage = exports.getCurrentDate = exports.addToClipBoard = exports.showMsg = void 0; // 添加消息

var style = document.createElement('style');
style.innerText = "\n@media (min-width: 100px){\n  .plugin-pop-cls{\n    position: fixed;\n    width:100vw;\n    top:0vh;\n    height: 1px;\n    text-align: center;\n    z-index:100000;\n    left: 0;\n  }\n}\n\n@media (min-width: 900px){\n  .plugin-pop-cls{\n    position: fixed;\n    width:30vw;\n    top:15vh;\n    height: 1px;\n    left:34vw;\n    text-align: center;\n    z-index:100000\n  }\n}\n\n\n.plugin-alert{\n  width:100%;\n  font-size:14px;\n  padding:10px;\n  text-align: center;\n  margin-bottom: 20px;\n  border-width: 1px;\n  border-style: solid;\n  border-radius: 4px;\n}\n.plugin-success{\n  color:rgb(60, 118, 61);\n  background-color: rgb(223, 240, 216);\n  border-color: rgb(214, 233, 198);\n}\n.plugin-warning{\n  color: #a94442;\n  background-color: #f2dede;\n  border-color: #ebccd1;\n}\ninput,button,select,textarea{outline:none}";

var _interval = setInterval(function () {
  if (document.head) {
    clearInterval(_interval);
    document.head.appendChild(style);
  }
}, 2000);

function showMsg(title) {
  var status = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "success";
  var during = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2000;

  if ($('.plugin-pop-cls').length == 0) {
    $('body').append('<div class="plugin-pop-cls"></div>');
  }

  var cls = "cls" + new Date().getTime();
  var statusClass = '';

  if (status == 'success') {
    statusClass = 'plugin-success';
  } else {
    statusClass = 'plugin-warning';
  }

  $('.plugin-pop-cls').append("<div class=\"plugin-alert ".concat(cls, " ").concat(statusClass, "\">").concat(title, "</div>"));
  setTimeout(function () {
    $(".".concat(cls)).remove();
  }, during);
}

exports.showMsg = showMsg; // 复制到剪切板

function addToClipBoard(str) {
  var transfer = document.createElement('input');
  $('body').append(transfer);
  transfer.value = str;
  transfer.focus();
  transfer.select();

  if (document.execCommand('copy')) {
    document.execCommand('copy');
  }

  transfer.blur();
  $('body input').remove();
}

exports.addToClipBoard = addToClipBoard; // 获取当前日期

function getCurrentDate() {
  var current_date = new Date();
  var years = current_date.getFullYear();
  var month = current_date.getMonth() + 1;
  month = month < 10 ? '0' + month : month;
  var day = current_date.getDate();
  day = day < 10 ? '0' + day : day;
  var hours = current_date.getHours();
  var minute = current_date.getMinutes();
  return [years, month, day, hours, minute];
}

exports.getCurrentDate = getCurrentDate;

function getClipInfo() {
  var helperdiv = document.createElement("div");
  document.body.appendChild(helperdiv);
  helperdiv.contentEditable = true; // focus the helper div's content

  var range = document.createRange();
  range.selectNode(helperdiv);
  var selection = window.getSelection();
  selection && selection.removeAllRanges();
  selection && selection.addRange(range);
  helperdiv.focus(); // trigger the paste action

  document.execCommand("Paste"); // read the clipboard contents from the helperdiv

  var clipboardContents = helperdiv.innerHTML;
  console.log("\u5F53\u524D\u526A\u5207\u677F\u5185\u5BB9\u4E3A:".concat(clipboardContents));
  document.body.removeChild(helperdiv);
  return clipboardContents;
}

function getStorage(_arr) {
  return new Promise(function (resolve) {
    chrome.storage.local.get(_arr, function (res) {
      resolve(res);
    });
  });
}

exports.getStorage = getStorage;

function setStorage(obj) {
  return new Promise(function (resolve) {
    chrome.storage.local.set(obj, function () {
      resolve('');
    });
  });
}

exports.setStorage = setStorage;

function sleep(ts) {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve('');
    }, ts);
  });
}

exports.sleep = sleep;

function waitDom(dom) {
  return new Promise(function (resolve) {
    var interval = setInterval(function () {
      if ($(dom).length) {
        clearInterval(interval);
        resolve('');
      }
    }, 100);
  });
}

exports.waitDom = waitDom;

/***/ }),

/***/ 16:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {



function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return generator._invoke = function (innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; }(innerFn, self, context), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; this._invoke = function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) { if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; } return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) { "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); } }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function (resolve) {
      resolve(value);
    });
  }

  return new (P || (P = Promise))(function (resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }

    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }

    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }

    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};

Object.defineProperty(exports, "__esModule", ({
  value: true
}));

var tools_1 = __webpack_require__(2);

var ContentScript = /*#__PURE__*/function () {
  function ContentScript() {
    _classCallCheck(this, ContentScript);

    // 新增：任务状态管理
    this.taskStatus = 'running';
    this.currentProgress = {
      currentAsinIndex: 0,
      totalCompleted: 0
    }; // 购物车页面

    this.cartPageFinish = false;
    this.cartPageWaitLoadTime = 20; // 智赢加载失败计数

    this.loadFailCount = 0; // 监听页面加载

    this.listenAjaxPage = false; // interval

    this.requestInterval = '5-8';
    this.listenPaginationTimeout = ''; // 停滞监控变量

    this.lastActivityTime = Date.now();
    this.watchdogTimer = null;
    this.watchdogTimeout = 60 * 1000; // 60秒停滞超时阈值（延长超时时间减少误判）

    this.minPriceObj = {
      com: 7,
      jp: 800,
      ca: 10
    };
    this.minPriceVal = 0;
    this.category = [];
    this.blockCategory = [];
    this.blockTitle = [];
    this.task_id = '';
    this.shopSeller = ''; // 初始化时从localStorage加载失败次数

    var failCount = localStorage.getItem('failCount');
    this.loadFailCount = failCount ? parseInt(failCount, 10) : 0;
  } // 标记活动（更新最后活动时间）


  _createClass(ContentScript, [{
    key: "markActivity",
    value: function markActivity() {
      this.lastActivityTime = Date.now();
      console.log("\u6D3B\u52A8\u6807\u8BB0\u66F4\u65B0: ".concat(new Date().toLocaleTimeString()));
    } // 启动看门狗定时器监控停滞

  }, {
    key: "startWatchdog",
    value: function startWatchdog() {
      var _this = this;

      console.log("shopCartPrice startWatchdog启动"); // 清除之前的定时器（如果有）

      if (this.watchdogTimer) {
        clearInterval(this.watchdogTimer);
      }

      this.watchdogTimer = setInterval(function () {
        var now = Date.now();
        var elapsed = now - _this.lastActivityTime; // 只在任务运行中且停滞超过阈值时触发

        if (_this.taskStatus === 'running' && elapsed > _this.watchdogTimeout) {
          console.log("\u68C0\u6D4B\u5230\u4EFB\u52A1\u505C\u6EDE\uFF1A".concat(Math.round(elapsed / 1000), "\u79D2\u672A\u54CD\u5E94\uFF0C\u5F00\u59CB\u81EA\u52A8\u6062\u590D..."));
          console.log("\u6700\u540E\u6D3B\u52A8\u65F6\u95F4: ".concat(new Date(_this.lastActivityTime).toLocaleTimeString()));
          console.log("\u5F53\u524D\u4EFB\u52A1\u72B6\u6001: ".concat(_this.taskStatus, ", \u5F53\u524D\u8FDB\u5EA6: ").concat(_this.currentProgress.currentAsinIndex));

          _this.handleTaskStagnation();
        }
      }, 3000); // 缩短检查间隔以便更早检测到问题
    } // 处理任务停滞情况

  }, {
    key: "handleTaskStagnation",
    value: function handleTaskStagnation() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                // 停止当前任务的看门狗定时器
                if (this.watchdogTimer) {
                  clearInterval(this.watchdogTimer);
                  this.watchdogTimer = null;
                } // 保存当前进度


                _context.prev = 1;
                _context.t0 = chrome.storage.local;
                _context.t1 = this.currentProgress;
                _context.next = 6;
                return this.getTotalAsinCount();

              case 6:
                _context.t2 = _context.sent;
                _context.t3 = {
                  shopCartPriceProgress: _context.t1,
                  totalAsin: _context.t2
                };
                _context.next = 10;
                return _context.t0.set.call(_context.t0, _context.t3);

              case 10:
                console.log('任务停滞，已保存当前进度');
                _context.next = 16;
                break;

              case 13:
                _context.prev = 13;
                _context.t4 = _context["catch"](1);
                console.error('保存进度时出错:', _context.t4);

              case 16:
                // 刷新页面以恢复任务
                console.log('3秒后刷新页面以恢复任务...');
                setTimeout(function () {
                  location.reload();
                }, 3000);

              case 18:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this, [[1, 13]]);
      }));
    } // 获取总ASIN数量（辅助方法）

  }, {
    key: "getTotalAsinCount",
    value: function getTotalAsinCount() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                return _context2.abrupt("return", new Promise(function (resolve) {
                  chrome.storage.local.get('totalAsin', function (res) {
                    resolve(res.totalAsin || 0);
                  });
                }));

              case 1:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));
    } // 停止看门狗定时器

  }, {
    key: "stopWatchdog",
    value: function stopWatchdog() {
      console.log("shopCartPrice stopWatchdog关闭");

      if (this.watchdogTimer) {
        clearInterval(this.watchdogTimer);
        this.watchdogTimer = null;
      }
    }
  }, {
    key: "init",
    value: function init() {
      var _this2 = this;

      if (location.href.includes('https://www.amazon.com/s?')) {
        chrome.storage.local.get(['taskConfig'], function (res) {
          return __awaiter(_this2, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
            var _this3 = this;

            var _a, _b, urlObj;

            return _regeneratorRuntime().wrap(function _callee3$(_context3) {
              while (1) {
                switch (_context3.prev = _context3.next) {
                  case 0:
                    if (!(!(res === null || res === void 0 ? void 0 : res.taskConfig) || ((_a = res.taskConfig) === null || _a === void 0 ? void 0 : _a.type) != 'shopCartPrice' || ((_b = res.taskConfig) === null || _b === void 0 ? void 0 : _b.status) != 'run')) {
                      _context3.next = 2;
                      break;
                    }

                    return _context3.abrupt("return", false);

                  case 2:
                    urlObj = new URL(res.taskConfig.info.url);
                    this.shopSeller = urlObj.searchParams.get('me');
                    console.log('this.shopSeller', this.shopSeller);
                    this.task_id = res.taskConfig.info.id; // 恢复进度

                    chrome.storage.local.get('shopCartPriceProgress', function (progressRes) {
                      if (progressRes.shopCartPriceProgress) {
                        _this3.currentProgress = progressRes.shopCartPriceProgress;
                      }
                    });
                    console.log('开始执行shopCartPrice任务');

                    this._startCollect();

                    if (res.taskConfig.type == 'shopCartPrice') {
                      // 初始化停滞监控
                      this.startWatchdog();
                      this.addControlUI(); // 添加控制UI
                    }

                  case 10:
                  case "end":
                    return _context3.stop();
                }
              }
            }, _callee3, this);
          }));
        }); // 监听消息

        this.listenBgMessage();
      }

      if (location.href.includes('https://www.amazon.com/sp')) {
        chrome.storage.local.get(['taskConfig'], function (res) {
          return __awaiter(_this2, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
            var _c, _d;

            return _regeneratorRuntime().wrap(function _callee4$(_context4) {
              while (1) {
                switch (_context4.prev = _context4.next) {
                  case 0:
                    if (!(!(res === null || res === void 0 ? void 0 : res.taskConfig) || ((_c = res.taskConfig) === null || _c === void 0 ? void 0 : _c.type) != 'shopCartPrice' || ((_d = res.taskConfig) === null || _d === void 0 ? void 0 : _d.status) != 'run')) {
                      _context4.next = 2;
                      break;
                    }

                    return _context4.abrupt("return", false);

                  case 2:
                    setInterval(function () {
                      if (location.href.includes('https://www.amazon.com/sp') && $('#seller-info-storefront-link').length) {
                        $('#seller-info-storefront-link a').eq(0)[0].click();
                      }
                    }, 10 * 1000);

                  case 3:
                  case "end":
                    return _context4.stop();
                }
              }
            }, _callee4);
          }));
        });
      }
    } // 新增：添加控制按钮UI

  }, {
    key: "addControlUI",
    value: function addControlUI() {
      var _this4 = this;

      var _a, _b, _c; // 避免重复添加


      if (document.getElementById('shop-cart-price-control-panel')) return;
      var panel = document.createElement('div');
      panel.id = 'shop-cart-price-control-panel';
      panel.style.position = 'fixed';
      panel.style.top = '20px';
      panel.style.right = '20px';
      panel.style.zIndex = '999999';
      panel.style.backgroundColor = 'white';
      panel.style.border = '1px solid #ddd';
      panel.style.borderRadius = '8px';
      panel.style.padding = '15px';
      panel.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
      panel.innerHTML = "\n      <div style=\"margin-bottom: 10px; font-weight: bold;\">\u8D2D\u7269\u8F66\u4EF7\u683C\u4EFB\u52A1\u63A7\u5236</div>\n      <div style=\"display: flex; gap: 10px;\">\n        <button id=\"shop-cart-price-pause\" style=\"padding: 5px 10px; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer;\">\u6682\u505C</button>\n        <button id=\"shop-cart-price-resume\" style=\"padding: 5px 10px; background: #34a853; color: white; border: none; border-radius: 4px; cursor: pointer; display: none;\">\u7EE7\u7EED</button>\n        <button id=\"shop-cart-price-stop\" style=\"padding: 5px 10px; background: #ea4335; color: white; border: none; border-radius: 4px; cursor: pointer;\">\u505C\u6B62</button>\n      </div>\n      <div id=\"shop-cart-price-status\" style=\"margin-top: 10px; font-size: 12px; color: #666;\">\u72B6\u6001\uFF1A\u8FD0\u884C\u4E2D</div>\n    ";
      document.body.appendChild(panel); // 绑定事件

      (_a = document.getElementById('shop-cart-price-pause')) === null || _a === void 0 ? void 0 : _a.addEventListener('click', function () {
        return _this4.pauseTask();
      });
      (_b = document.getElementById('shop-cart-price-resume')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', function () {
        return _this4.resumeTask();
      });
      (_c = document.getElementById('shop-cart-price-stop')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', function () {
        return _this4.stopTask();
      });
    } // 新增：暂停任务

  }, {
    key: "pauseTask",
    value: function pauseTask() {
      var _this5 = this;

      if (this.taskStatus !== 'running') return;
      this.taskStatus = 'paused';
      this.stopWatchdog(); // 停止看门狗定时器

      console.log('任务已暂停（shopCartPrice）');
      this.updateControlUI(); // 保存当前进度

      chrome.storage.local.get('totalAsin', function (res) {
        _this5.currentProgress.totalCompleted = res.totalAsin || 0;
        chrome.storage.local.set({
          shopCartPriceProgress: _this5.currentProgress
        });
      }); // 发送暂停状态到背景页

      chrome.runtime.sendMessage({
        type: "taskStatus",
        status: "paused",
        task_id: this.task_id,
        taskType: 'shopCartPrice'
      });
    } // 新增：恢复任务

  }, {
    key: "resumeTask",
    value: function resumeTask() {
      if (this.taskStatus !== 'paused') return;
      this.taskStatus = 'running';
      console.log('任务已恢复（shopCartPrice）');
      this.updateControlUI(); // 发送恢复状态到背景页

      chrome.runtime.sendMessage({
        type: "taskStatus",
        status: "running",
        task_id: this.task_id,
        taskType: 'shopCartPrice'
      }); // 继续执行任务

      this._startCollect();
    } // 新增：停止任务

  }, {
    key: "stopTask",
    value: function stopTask() {
      var _a;

      this.taskStatus = 'stopped';
      this.stopWatchdog(); // 停止看门狗定时器

      this.updateControlUI(); // 清理存储

      chrome.storage.local.remove('taskConfig');
      chrome.storage.local.remove('totalAsin');
      chrome.storage.local.remove('shopCartPriceProgress'); // 发送停止状态到背景页

      chrome.runtime.sendMessage({
        type: "taskStatus",
        status: "stopped",
        task_id: this.task_id,
        taskType: 'shopCartPrice'
      }); // 通知服务器任务已停止

      chrome.runtime.sendMessage({
        type: "http",
        url: "".concat("https://www.genmaijl.com", "/ai/task/finish"),
        content: {
          method: 'put',
          body: JSON.stringify({
            id: this.task_id
          })
        }
      }, function () {}); // 移除控制UI

      (_a = document.getElementById('shop-cart-price-control-panel')) === null || _a === void 0 ? void 0 : _a.remove(); // 显示停止提示

      (0, tools_1.showMsg)('shopCartPrice任务已停止: ' + this.task_id);
    } // 新增：更新控制UI状态

  }, {
    key: "updateControlUI",
    value: function updateControlUI() {
      var statusEl = document.getElementById('shop-cart-price-status');
      var pauseBtn = document.getElementById('shop-cart-price-pause');
      var resumeBtn = document.getElementById('shop-cart-price-resume');
      if (!statusEl || !pauseBtn || !resumeBtn) return;

      switch (this.taskStatus) {
        case 'running':
          statusEl.textContent = '状态：运行中';
          pauseBtn.style.display = 'block';
          resumeBtn.style.display = 'none';
          break;

        case 'paused':
          statusEl.textContent = '状态：已暂停';
          pauseBtn.style.display = 'none';
          resumeBtn.style.display = 'block';
          break;

        case 'stopped':
          statusEl.textContent = '状态：已停止';
          pauseBtn.style.display = 'none';
          resumeBtn.style.display = 'none';
          break;
      }
    } // 开始收集数据（添加状态检查）

  }, {
    key: "_startCollect",
    value: function _startCollect() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
        var _this6 = this;

        var _timeout, loadSuccess;

        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                if (!(this.taskStatus !== 'running')) {
                  _context6.next = 2;
                  break;
                }

                return _context6.abrupt("return");

              case 2:
                // 标记活动开始
                this.markActivity(); // 等待30s 如果页面没有出现商品 切换店铺

                _timeout = setTimeout(function () {
                  return __awaiter(_this6, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
                    return _regeneratorRuntime().wrap(function _callee5$(_context5) {
                      while (1) {
                        switch (_context5.prev = _context5.next) {
                          case 0:
                            if (!(this.taskStatus !== 'running')) {
                              _context5.next = 2;
                              break;
                            }

                            return _context5.abrupt("return");

                          case 2:
                            // 已暂停/停止则不刷新
                            console.log('加载失败 开始刷新');
                            location.reload();

                          case 4:
                          case "end":
                            return _context5.stop();
                        }
                      }
                    }, _callee5, this);
                  }));
                }, 100 * 1000); // 等待加载完成

                _context6.next = 6;
                return this.sellerLoadFinish();

              case 6:
                loadSuccess = _context6.sent;

                if (loadSuccess && this.taskStatus === 'running') {
                  clearTimeout(_timeout);
                  this.circulationRequest();
                } else {
                  clearTimeout(_timeout);
                }

              case 8:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this);
      }));
    }
  }, {
    key: "circulationRequest",
    value: function circulationRequest() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
        var _this7 = this;

        var domList, totalAsin, _loop, i, _ret;

        return _regeneratorRuntime().wrap(function _callee7$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                if (!(this.taskStatus !== 'running')) {
                  _context8.next = 2;
                  break;
                }

                return _context8.abrupt("return");

              case 2:
                // 标记活动
                this.markActivity();
                domList = Array.from($('[role="listitem"].s-result-item'));

                if (!(!$('[aria-label="exclamation-circle"]:visible, [aria-label="check-circle"]:visible').length && $('._1wyo2vd6._1wyo2vdv._1wyo2vd1j._1wyo2vd1h').length)) {
                  _context8.next = 7;
                  break;
                }

                this.zhiyinglogin();
                return _context8.abrupt("return", false);

              case 7:
                _context8.next = 9;
                return chrome.storage.local.get('totalAsin');

              case 9:
                totalAsin = _context8.sent;
                totalAsin = (totalAsin === null || totalAsin === void 0 ? void 0 : totalAsin.totalAsin) || 0; // 从当前进度继续处理

                _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(i) {
                  var row, asin, sell_number, cartInfo, market_id, sort, month_sell, brand, brand_status, data, hasMatchingSeller, testDataResult;
                  return _regeneratorRuntime().wrap(function _loop$(_context7) {
                    while (1) {
                      switch (_context7.prev = _context7.next) {
                        case 0:
                          row = domList[i]; // 状态检查

                          if (!(_this7.taskStatus !== 'running')) {
                            _context7.next = 5;
                            break;
                          }

                          _this7.currentProgress.currentAsinIndex = i;
                          chrome.storage.local.set({
                            shopCartPriceProgress: _this7.currentProgress
                          });
                          return _context7.abrupt("return", {
                            v: void 0
                          });

                        case 5:
                          totalAsin += 1;

                          if (!(totalAsin > 500)) {
                            _context7.next = 9;
                            break;
                          }

                          chrome.storage.local.set({
                            totalAsin: totalAsin
                          });
                          return _context7.abrupt("return", "break");

                        case 9:
                          asin = $(row).attr('data-asin');
                          sell_number = $(row).find('[data-action="show-all-offers-display"]').text() || '';
                          sell_number = sell_number.match(/\d+/);
                          sell_number = sell_number ? sell_number[0] : '0';
                          console.log('asin', asin);
                          _context7.next = 16;
                          return _this7.asinCartData2($(row).find('[data-action="show-all-offers-display"]'));

                        case 16:
                          cartInfo = _context7.sent;

                          if (cartInfo) {
                            _context7.next = 19;
                            break;
                          }

                          return _context7.abrupt("return", "continue");

                        case 19:
                          market_id = document.documentElement.innerHTML.match(/(?<=ObfuscatedMarketplaceId': ')[\s\S]*?(?=')/gi);
                          market_id = market_id ? market_id[0] : "";
                          sort = [];
                          $(row).find('.ranktag').each(function () {
                            sort.push($(this).text().trim() + $(this).next().text().trim());
                          });
                          month_sell = $(row).find('span._1wyo2vd18._1wyo2vdw._1wyo2vd1 > span').text() || '';
                          month_sell = month_sell.match(/[\d]+/);
                          month_sell = month_sell ? month_sell[0] : '0';
                          brand = $(row).find('._1wyo2vd18._1wyo2vdw._1wyo2vd6').text().trim() || '';
                          brand_status = $(row).find('._1wyo2vd0._1wyo2vd1j._1wyo2vdc').length ? 'normal' : "已注册";
                          data = {
                            asin: asin,
                            mainImg: $(row).find('img.s-image').attr('src'),
                            seller_number: sell_number,
                            task_id: _this7.task_id,
                            country: _this7.getCountry(),
                            market_id: market_id,
                            sort: JSON.stringify(sort),
                            month_sell: month_sell,
                            brand: brand,
                            brand_status: brand_status
                          };
                          cartInfo = cartInfo.map(function (ele) {
                            return Object.assign(Object.assign({}, data), ele);
                          }); // 检查是否包含匹配的卖家名称

                          console.log('Checking for matching seller. this.shopSeller:', _this7.shopSeller);
                          console.log('Current cartInfo seller names:', cartInfo.map(function (item) {
                            return item.seller_id;
                          }));
                          hasMatchingSeller = cartInfo.some(function (item) {
                            var hasMatch = item.seller_id && _this7.shopSeller && item.seller_id.includes(_this7.shopSeller);
                            console.log("Check for item: ".concat(item.seller_id, " includes ").concat(_this7.shopSeller, ": ").concat(hasMatch));
                            return hasMatch;
                          }); // 如果没有匹配的卖家名称，调用testData方法并将结果添加到cartInfo

                          if (!hasMatchingSeller && _this7.shopSeller) {
                            console.log('未采集到当前店铺的商品,调用额外采集方法testData');
                            testDataResult = _this7.testData($(row));
                            console.log('testDataResult', testDataResult);
                            cartInfo.push(testDataResult);
                          }

                          console.log(cartInfo);
                          chrome.runtime.sendMessage({
                            type: "http",
                            url: "".concat("https://www.genmaijl.com", "/ai/task/uploadAsinPrice"),
                            content: {
                              method: 'post',
                              body: JSON.stringify(cartInfo)
                            }
                          }, function () {}); // 更新进度

                          _this7.currentProgress.currentAsinIndex = i + 1;
                          _this7.currentProgress.totalCompleted = totalAsin;
                          chrome.storage.local.set({
                            totalAsin: totalAsin,
                            shopCartPriceProgress: _this7.currentProgress
                          });
                          _context7.next = 41;
                          return (0, tools_1.sleep)(5000);

                        case 41:
                          // 标记活动
                          _this7.markActivity();

                        case 42:
                        case "end":
                          return _context7.stop();
                      }
                    }
                  }, _loop);
                });
                i = this.currentProgress.currentAsinIndex;

              case 13:
                if (!(i < domList.length)) {
                  _context8.next = 25;
                  break;
                }

                return _context8.delegateYield(_loop(i), "t0", 15);

              case 15:
                _ret = _context8.t0;

                if (!(_ret === "break")) {
                  _context8.next = 18;
                  break;
                }

                return _context8.abrupt("break", 25);

              case 18:
                if (!(_ret === "continue")) {
                  _context8.next = 20;
                  break;
                }

                return _context8.abrupt("continue", 22);

              case 20:
                if (!(_typeof(_ret) === "object")) {
                  _context8.next = 22;
                  break;
                }

                return _context8.abrupt("return", _ret.v);

              case 22:
                i++;
                _context8.next = 13;
                break;

              case 25:
                _context8.next = 27;
                return (0, tools_1.sleep)(2000);

              case 27:
                // 标记活动
                this.markActivity();
                _context8.next = 30;
                return chrome.storage.local.set({
                  totalAsin: totalAsin
                });

              case 30:
                console.log('此页面采集结束'); // 状态检查

                if (this.taskStatus === 'running') {
                  this.runNext();
                }

              case 32:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee7, this);
      }));
    }
  }, {
    key: "testData",
    value: function testData(that) {
      var asin = that.attr('data-asin');
      var priceText = that.find('.a-offscreen').eq(0).text() || '';
      var priceMatch = priceText.match(/[\d,.]+/);
      var price = priceMatch ? priceMatch[0] : "0";
      var sellNumberText = that.find('a[data-action="show-all-offers-display"]').eq(0).text() || '0';
      var sellNumberMatch = sellNumberText.match(/[\d]+/);
      var sell_number = sellNumberMatch ? sellNumberMatch[0] : '0';
      var sell_type = that.find('.zying-tag-ship._1wyo2vd2g').text();
      var sort = [];
      that.find('.ranktag').each(function () {
        sort.push($(this).text().trim() + $(this).next().text().trim());
      });
      var market_idMatch = document.documentElement.innerHTML.match(/(?<=ObfuscatedMarketplaceId': ')[\s\S]*?(?=')/gi);
      var market_id = market_idMatch ? market_idMatch[0] : "";
      var monthSellText = that.find('span._1wyo2vd18._1wyo2vdw._1wyo2vd1 > span').text() || '';
      var monthSellMatch = monthSellText.match(/[\d]+/);
      var month_sell = monthSellMatch ? monthSellMatch[0] : '0';
      var feedbackScoreText = that.find('[data-cy="reviews-ratings-slot"]').text();
      var feedbackScoreMatch = feedbackScoreText.match(/[\d.]+/);
      var feedback_score = feedbackScoreMatch ? feedbackScoreMatch[0] : 0;
      var delivery = that.find('.a-column.a-span12').text();

      if (delivery.includes('FREE')) {
        delivery = 0;
      } else {
        var _priceMatch = delivery.match(/\d+\.\d+/);

        delivery = _priceMatch ? _priceMatch[0] : 0;
      }

      var data = {
        asin: asin,
        brand: that.find('._1wyo2vd18._1wyo2vdw._1wyo2vd6').text().trim() || '',
        brand_status: that.find('._1wyo2vd0._1wyo2vd1j._1wyo2vdc').length ? 'normal' : "已注册",
        cart_price: parseFloat(price),
        cart_seller_name: that.find('._1wyo2vd18._1wyo2vd2h._1wyo2vd6').text(),
        cart_status: 1,
        comment_number: that.find('[data-component-type="s-client-side-analytics"]').text(),
        country: this.getCountry(),
        delivery: delivery,
        feedback_score: feedback_score,
        mainImg: that.find('img.s-image').attr('src'),
        market_id: market_id,
        month_sell: month_sell,
        seller_id: this.shopSeller,
        seller_number: sell_number,
        seller_type: sell_type,
        sort: JSON.stringify(sort),
        task_id: this.task_id
      };
      return data;
    }
  }, {
    key: "listenBgMessage",
    value: function listenBgMessage() {
      var _this8 = this;

      chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
        // 过滤任务类型，避免冲突
        if (request.taskType !== 'shopCartPrice') return;

        switch (request.type) {
          case 'requestFinish':
            if (_this8.listenAjaxPage && _this8.taskStatus === 'running') {
              setTimeout(function () {
                return _this8._startCollect();
              }, 2000);
            } else if (_this8.cartPageFinish) {
              _this8.cartPageFinish = false;
            }

            break;

          case 'taskControl':
            switch (request.action) {
              case 'pause':
                _this8.pauseTask();

                break;

              case 'resume':
                _this8.resumeTask();

                break;

              case 'stop':
                _this8.stopTask();

                break;
            }

            break;
        }
      });
    } // 检查智赢加载状态，加载失败时刷新页面（最多5次）

  }, {
    key: "checkSellerLoadStatus",
    value: function checkSellerLoadStatus() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
        var failCount, isLoaded;
        return _regeneratorRuntime().wrap(function _callee8$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                // 从localStorage中获取失败次数
                failCount = localStorage.getItem('failCount');
                this.loadFailCount = failCount ? parseInt(failCount, 10) : 0; // 检查智赢是否加载成功

                _context9.next = 4;
                return this.sellerLoadFinish();

              case 4:
                isLoaded = _context9.sent;

                if (!isLoaded) {
                  _context9.next = 12;
                  break;
                }

                // 加载成功，重置失败计数
                this.loadFailCount = 0;
                localStorage.removeItem('failCount');
                console.log('智赢加载成功，可以进入购物车');
                return _context9.abrupt("return", true);

              case 12:
                // 加载失败，增加失败计数
                this.loadFailCount++;
                localStorage.setItem('failCount', this.loadFailCount.toString());
                console.log("\u667A\u8D62\u52A0\u8F7D\u5931\u8D25\uFF0C\u5F53\u524D\u6B21\u6570: ".concat(this.loadFailCount)); // 如果失败次数小于5，刷新页面并重试

                if (!(this.loadFailCount < 5)) {
                  _context9.next = 26;
                  break;
                }

                console.log("\u667A\u8D62\u52A0\u8F7D\u5931\u8D25\uFF0C\u5C06\u57282\u79D2\u540E\u5237\u65B0\u9875\u9762\u91CD\u8BD5\uFF08\u5F53\u524D".concat(this.loadFailCount, "\u6B21\uFF0C\u6700\u591A5\u6B21\uFF09")); // 状态检查

                if (!(this.taskStatus !== 'running')) {
                  _context9.next = 20;
                  break;
                }

                localStorage.removeItem('failCount');
                return _context9.abrupt("return", false);

              case 20:
                _context9.next = 22;
                return (0, tools_1.sleep)(2000);

              case 22:
                location.reload(); // 返回false以中断当前流程

                return _context9.abrupt("return", false);

              case 26:
                // 失败次数达到5次，终止当前任务
                console.log('智赢加载失败5次，终止当前任务');
                this.taskStatus = 'stopped';
                this.loadFailCount = 0;
                this.stopWatchdog(); // 任务完成时停止看门狗

                localStorage.removeItem('failCount'); // 发送任务失败通知

                chrome.runtime.sendMessage({
                  type: 'task_fail',
                  message: '智赢加载失败5次，任务终止'
                });
                return _context9.abrupt("return", false);

              case 33:
              case "end":
                return _context9.stop();
            }
          }
        }, _callee8, this);
      }));
    }
  }, {
    key: "sellerLoadFinish",
    value: function sellerLoadFinish() {
      var _this9 = this;

      return new Promise(function (resolve) {
        return __awaiter(_this9, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
          var _this10 = this;

          var maxCount, sellerInterval, timeout;
          return _regeneratorRuntime().wrap(function _callee9$(_context10) {
            while (1) {
              switch (_context10.prev = _context10.next) {
                case 0:
                  maxCount = 0;
                  sellerInterval = null;
                  timeout = null; // 标记活动开始

                  this.markActivity();
                  sellerInterval = setInterval(function () {
                    // 标记活动
                    _this10.markActivity(); // 状态检查


                    if (_this10.taskStatus !== 'running') {
                      clearInterval(sellerInterval);
                      clearTimeout(timeout);
                      resolve(false);
                      return;
                    }

                    maxCount += 1;

                    if ($('[aria-label="exclamation-circle"], [aria-label="check-circle"]').length / $('[role="listitem"].s-result-item').length > 0.7) {
                      localStorage.removeItem('failCount');
                      console.log('智赢加载完成');
                      clearInterval(sellerInterval);
                      clearTimeout(timeout);
                      setTimeout(function () {
                        return resolve(true);
                      }, 5000);
                    }
                  }, 2000); // 缩短检查间隔并增加活动标记

                  timeout = setTimeout(function () {
                    clearInterval(sellerInterval);

                    if (!$('[aria-label="exclamation-circle"]:visible, [aria-label="check-circle"]:visible').length && $('._1wyo2vd6._1wyo2vdv._1wyo2vd1j._1wyo2vd1h').length) {
                      _this10.zhiyinglogin();

                      resolve(false);
                    } else {
                      resolve(false);
                    }
                  }, 15 * 1000); // 延长超时时间

                case 6:
                case "end":
                  return _context10.stop();
              }
            }
          }, _callee9, this);
        }));
      });
    }
  }, {
    key: "runNext",
    value: function runNext() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
        var _this11 = this;

        var totalAsin, next;
        return _regeneratorRuntime().wrap(function _callee10$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                if (!(this.taskStatus !== 'running')) {
                  _context11.next = 2;
                  break;
                }

                return _context11.abrupt("return");

              case 2:
                // 标记活动
                this.markActivity();
                _context11.next = 5;
                return chrome.storage.local.get('totalAsin');

              case 5:
                totalAsin = _context11.sent;
                totalAsin = (totalAsin === null || totalAsin === void 0 ? void 0 : totalAsin.totalAsin) || 0;
                next = $('span.s-pagination-selected').parents('ul').find('a:contains(Next)');

                if ($(next).length && totalAsin < 500) {
                  console.log('nextPage');
                  this.listenAjaxPage = true; // 重置当前页面进度索引

                  this.currentProgress.currentAsinIndex = 0;
                  chrome.storage.local.set({
                    shopCartPriceProgress: this.currentProgress
                  });
                  $(next)[0].click(); // 添加超时机制，确保即使没有收到requestFinish消息也能继续执行

                  setTimeout(function () {
                    if (_this11.taskStatus === 'running' && _this11.listenAjaxPage) {
                      console.log('翻页超时，手动触发继续采集');
                      _this11.listenAjaxPage = false;

                      _this11._startCollect();
                    }
                  }, 8000); // 10秒超时
                } else {
                  // 任务完成，调用background.ts中的onTaskCompleted函数执行下一个任务
                  chrome.runtime.sendMessage({
                    type: "taskCompleted",
                    taskId: this.task_id
                  });
                  this.taskStatus = 'stopped';
                  this.stopWatchdog(); // 任务完成时停止看门狗

                  this.updateControlUI();
                  this.showCompletionPopup(totalAsin);
                }

              case 9:
              case "end":
                return _context11.stop();
            }
          }
        }, _callee10, this);
      }));
    }
  }, {
    key: "getCountry",
    value: function getCountry() {
      var platform = '';
      var host = window.location.host;
      host = host.split('.').pop();

      if (host == 'ca') {
        platform = "加拿大";
      } else if (host == 'com') {
        platform = '美国';
      } else if (host == 'jp') {
        platform = '日本';
      } else if (host == 'de') {
        platform = '德国';
      } else if (host == 'fr') {
        platform = '法国';
      } else if (host == 'uk') {
        platform = '英国';
      } else if (host == 'mx') {
        platform = '墨西哥';
      } else if (host == 'au') {
        platform = '澳大利亚';
      }

      return platform;
    }
  }, {
    key: "zhiyinglogin",
    value: function zhiyinglogin() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
        var _this12 = this;

        return _regeneratorRuntime().wrap(function _callee12$(_context13) {
          while (1) {
            switch (_context13.prev = _context13.next) {
              case 0:
                if (!(this.taskStatus !== 'running')) {
                  _context13.next = 2;
                  break;
                }

                return _context13.abrupt("return");

              case 2:
                $('._1wyo2vd6._1wyo2vdv._1wyo2vd1j._1wyo2vd1h').eq(0)[0].click();
                _context13.next = 5;
                return waitDom('.zying-login-transform input', 30);

              case 5:
                _context13.next = 7;
                return (0, tools_1.sleep)(2000);

              case 7:
                chrome.storage.local.get('zhiying', function (res) {
                  return __awaiter(_this12, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
                    var zhiying, input, lastValue, tracker, input2, lastValue2, tracker2;
                    return _regeneratorRuntime().wrap(function _callee11$(_context12) {
                      while (1) {
                        switch (_context12.prev = _context12.next) {
                          case 0:
                            zhiying = res === null || res === void 0 ? void 0 : res.zhiying.split('-');

                            if (zhiying) {
                              _context12.next = 3;
                              break;
                            }

                            return _context12.abrupt("return");

                          case 3:
                            input = $('.zying-login-transform input').eq(0)[0];
                            lastValue = input.value;
                            input.value = zhiying[0];
                            tracker = input._valueTracker;

                            if (tracker) {
                              tracker.setValue(lastValue);
                            }

                            input.dispatchEvent(new Event('input', {
                              bubbles: true
                            }));
                            _context12.next = 11;
                            return (0, tools_1.sleep)(3000);

                          case 11:
                            input2 = $('.zying-login-transform input').eq(1)[0];
                            lastValue2 = input2.value;
                            input2.value = zhiying[1];
                            tracker2 = input2._valueTracker;

                            if (tracker2) {
                              tracker2.setValue(lastValue2);
                            }

                            input2.dispatchEvent(new Event('input', {
                              bubbles: true
                            }));
                            _context12.next = 19;
                            return (0, tools_1.sleep)(2000);

                          case 19:
                            $('.zying-login-transform button[type="submit"]')[0].click();
                            _context12.next = 22;
                            return (0, tools_1.sleep)(5000);

                          case 22:
                            location.reload();

                          case 23:
                          case "end":
                            return _context12.stop();
                        }
                      }
                    }, _callee11);
                  }));
                });

              case 8:
              case "end":
                return _context13.stop();
            }
          }
        }, _callee12, this);
      }));
    } // 收集购物车商家（添加状态检查）

  }, {
    key: "asinCartData",
    value: function asinCartData(dom) {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
        var isSellerLoaded, contentStatus, price, delivery, comment, feedback_score, seller_id;
        return _regeneratorRuntime().wrap(function _callee13$(_context14) {
          while (1) {
            switch (_context14.prev = _context14.next) {
              case 0:
                if (!(this.taskStatus !== 'running')) {
                  _context14.next = 2;
                  break;
                }

                return _context14.abrupt("return", null);

              case 2:
                _context14.next = 4;
                return this.checkSellerLoadStatus();

              case 4:
                isSellerLoaded = _context14.sent;

                if (isSellerLoaded) {
                  _context14.next = 8;
                  break;
                }

                console.log('智赢加载失败，取消当前购物车操作');
                return _context14.abrupt("return", null);

              case 8:
                // 标记活动
                this.markActivity();
                this.cartPageFinish = true;
                $(dom)[0].click();
                console.log('开始等待购物车加载');

              case 12:
                if (!(this.cartPageFinish && this.taskStatus === 'running')) {
                  _context14.next = 19;
                  break;
                }

                if ($('[data-action="aod-close-on-esc-action"]:visible').length) {
                  this.cartPageFinish = false;
                }

                _context14.next = 16;
                return (0, tools_1.sleep)(1000);

              case 16:
                // 缩短等待时间
                // 标记活动
                this.markActivity();
                _context14.next = 12;
                break;

              case 19:
                if (!(this.taskStatus !== 'running')) {
                  _context14.next = 21;
                  break;
                }

                return _context14.abrupt("return", null);

              case 21:
                console.log('请求完成');
                _context14.next = 24;
                return waitDom('#aod-container #aod-pinned-offer,  #aod-offer-list > [role="list"] > [role="listitem"]', 20);

              case 24:
                contentStatus = _context14.sent;
                console.log('页面样式加载完成');

                if (contentStatus) {
                  _context14.next = 28;
                  break;
                }

                return _context14.abrupt("return", null);

              case 28:
                price = $('#aod-pinned-offer .aok-offscreen').text() || '';
                price = price.replace(/,/g, '');
                price = price.match(/[\d.]+/);
                price = price ? price[0] : 0;
                delivery = $('#aod-pinned-offer [data-csa-c-delivery-price]').attr('data-csa-c-delivery-price') || '';
                delivery = delivery.replace(/,/g, '');
                delivery = delivery.match(/[\d.]+/);
                delivery = delivery ? delivery[0] : 0;
                comment = $('#aod-pinned-offer #aod-asin-reviews-count-title').text() || '';
                comment = comment.replace(/,/g, '');
                comment = comment.match(/[\d.]+/);
                comment = comment ? comment[0] : 0;
                feedback_score = $('#aod-pinned-offer #aod-asin-reviews-star').text() || '';
                feedback_score = feedback_score.match(/[\d.]+/);
                feedback_score = feedback_score ? feedback_score[0] : 0;
                seller_id = $('#aod-pinned-offer a.a-size-small.a-link-normal').eq(0).attr('href') || '';
                seller_id = seller_id.match(/(?<=seller=).*?(?=&)/);
                seller_id = seller_id ? seller_id[0] : "";
                setTimeout(function () {
                  $('i.a-icon.aod-close-button')[0].click();
                }, 500);
                return _context14.abrupt("return", {
                  cart_price: price,
                  delivery: delivery,
                  comment_number: comment,
                  feedback_score: feedback_score,
                  seller_id: seller_id
                });

              case 48:
              case "end":
                return _context14.stop();
            }
          }
        }, _callee13, this);
      }));
    } // 收集购物车商家（添加状态检查）

  }, {
    key: "asinCartData2",
    value: function asinCartData2(dom) {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
        var isSellerLoaded, arr, price, delivery, comment, feedback_score, seller_id;
        return _regeneratorRuntime().wrap(function _callee14$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                if (!(this.taskStatus !== 'running')) {
                  _context15.next = 2;
                  break;
                }

                return _context15.abrupt("return", null);

              case 2:
                _context15.next = 4;
                return this.checkSellerLoadStatus();

              case 4:
                isSellerLoaded = _context15.sent;

                if (isSellerLoaded) {
                  _context15.next = 8;
                  break;
                }

                console.log('智赢加载失败，取消当前购物车操作');
                return _context15.abrupt("return", null);

              case 8:
                // 标记活动
                this.markActivity();
                this.cartPageFinish = true;
                $(dom)[0].click();
                console.log('开始等待购物车加载');

              case 12:
                if (!(this.cartPageFinish && this.taskStatus === 'running')) {
                  _context15.next = 19;
                  break;
                }

                if ($('[data-action="aod-close-on-esc-action"]:visible').length) {
                  this.cartPageFinish = false;
                }

                _context15.next = 16;
                return (0, tools_1.sleep)(1000);

              case 16:
                // 缩短等待时间
                // 标记活动
                this.markActivity();
                _context15.next = 12;
                break;

              case 19:
                if (!(this.taskStatus !== 'running')) {
                  _context15.next = 21;
                  break;
                }

                return _context15.abrupt("return", null);

              case 21:
                console.log('请求完成');
                _context15.next = 24;
                return (0, tools_1.sleep)(2000);

              case 24:
                if (!(this.taskStatus !== 'running')) {
                  _context15.next = 26;
                  break;
                }

                return _context15.abrupt("return", null);

              case 26:
                arr = [];
                price = $('#aod-pinned-offer .aok-offscreen').text() || '';
                price = price.replace(/,/g, '');
                price = price.match(/[\d.]+/);
                price = price ? price[0] : 0;
                delivery = $('#aod-pinned-offer [data-csa-c-delivery-price]').attr('data-csa-c-delivery-price') || '';
                delivery = delivery.replace(/,/g, '');
                delivery = delivery.match(/[\d.]+/);
                delivery = delivery ? delivery[0] : 0;
                comment = $('#aod-pinned-offer #aod-asin-reviews-count-title').text() || '';
                comment = comment.replace(/,/g, '');
                comment = comment.match(/[\d.]+/);
                comment = comment ? comment[0] : 0;
                feedback_score = $('#aod-pinned-offer #aod-asin-reviews-star').text() || '';
                feedback_score = feedback_score.match(/[\d.]+/);
                feedback_score = feedback_score ? feedback_score[0] : 0;
                seller_id = $('#aod-pinned-offer a.a-size-small.a-link-normal').eq(0).attr('href') || '';
                seller_id = seller_id.match(/(?<=seller=).*?(?=&)/);
                seller_id = seller_id ? seller_id[0] : "";
                arr.push({
                  cart_price: price,
                  delivery: delivery,
                  comment_number: comment,
                  feedback_score: feedback_score,
                  seller_id: seller_id,
                  cart_seller_name: $('#aod-pinned-offer #aod-offer-soldBy a').text(),
                  seller_type: ($('#aod-pinned-offer #aod-offer-shipsFrom span').last().text() || '').toLocaleLowerCase().includes('amazon') ? 'FBA' : 'FBM'
                });
                $('#aod-offer-list > [role="list"] > [role="listitem"]').each(function () {
                  var _cart_price = $(this).find('span.a-price').eq(0).text() || '';

                  _cart_price = _cart_price.replace(/,/g, '');
                  _cart_price = _cart_price.match(/[\d.]+/);
                  _cart_price = _cart_price ? _cart_price[0] : 0;

                  var _delivery = $(this).find('[data-csa-c-delivery-price]').attr('data-csa-c-delivery-price') || '';

                  _delivery = _delivery.replace(/,/g, '');
                  _delivery = _delivery.match(/[\d.]+/);
                  _delivery = _delivery ? _delivery[0] : 0;

                  var _comment = $(this).find('#aod-offer-seller-rating').children().eq(1).text() || '';

                  _comment = _comment.replace(/,/g, '');
                  _comment = _comment.match(/[\d.]+/);
                  _comment = _comment ? _comment[0] : 0;

                  var _feedback_score = $(this).find('#aod-offer-seller-rating').children().eq(0).text() || '';

                  _feedback_score = _feedback_score.match(/[\d.]+/);
                  _feedback_score = _feedback_score ? _feedback_score[0] : 0;
                  var seller_id = $(this).find('#aod-offer-soldBy a').eq(0).attr('href') || '';
                  seller_id = seller_id.match(/(?<=seller=).*?(?=&)/);
                  seller_id = seller_id ? seller_id[0] : "";
                  var cart_seller_name = $(this).find('#aod-offer-soldBy a').eq(0).text();
                  var seller_type = $(this).find('#aod-offer-shipsFrom .a-col-right').eq(0).text() || '';
                  arr.push({
                    cart_price: _cart_price,
                    delivery: _delivery,
                    comment_number: _comment,
                    feedback_score: _feedback_score,
                    seller_id: seller_id,
                    cart_seller_name: cart_seller_name,
                    seller_type: seller_type.toLowerCase().includes('amazon') ? 'FBA' : 'FBM',
                    cart_status: 1
                  });
                }); // 关闭购物车窗口

                setTimeout(function () {
                  $('i.a-icon.aod-close-button')[0].click();
                }, 500);
                return _context15.abrupt("return", arr);

              case 49:
              case "end":
                return _context15.stop();
            }
          }
        }, _callee14, this);
      }));
    } // 显示任务完成弹窗

  }, {
    key: "showCompletionPopup",
    value: function showCompletionPopup(totalCount) {
      var popup = document.createElement('div');
      popup.style.position = 'fixed';
      popup.style.bottom = '20px';
      popup.style.right = '20px';
      popup.style.width = '300px';
      popup.style.backgroundColor = '#ffffff';
      popup.style.borderRadius = '8px';
      popup.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
      popup.style.padding = '16px';
      popup.style.zIndex = '99999';
      popup.style.fontFamily = 'Arial, sans-serif';
      popup.style.border = '1px solid #e0e0e0';
      popup.style.transition = 'all 0.3s ease';
      popup.innerHTML = "\n      <div style=\"display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;\">\n        <h3 style=\"margin: 0; color: #333; font-size: 16px;\">\u4EFB\u52A1\u5DF2\u5B8C\u6210</h3>\n        <button id=\"closePopup\" style=\"background: none; border: none; cursor: pointer; color: #999; font-size: 18px;\">&times;</button>\n      </div>\n      <p style=\"margin: 0 0 15px 0; color: #666; font-size: 14px;\">\u672C\u6B21\u5171\u91C7\u96C6\u5230 <strong style=\"color: #2196F3;\">".concat(totalCount, "</strong> \u6761\u6570\u636E</p>\n      <div style=\"text-align: right;\">\n        <button id=\"confirmBtn\" style=\"background-color: #2196F3; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 14px;\">\u786E\u5B9A</button>\n      </div>\n    ");
      document.body.appendChild(popup);
      var closeBtn = popup.querySelector('#closePopup');
      closeBtn.addEventListener('click', function () {
        return popup.remove();
      });
      var confirmBtn = popup.querySelector('#confirmBtn');
      confirmBtn.addEventListener('click', function () {
        return popup.remove();
      });
      setTimeout(function () {
        if (document.body.contains(popup)) {
          popup.style.opacity = '0';
          setTimeout(function () {
            return popup.remove();
          }, 300);
        }
      }, 10000);
    }
  }]);

  return ContentScript;
}();

function waitDom(dom, time) {
  return new Promise(function (resolve) {
    var interval = setInterval(function () {
      if ($(dom).length) {
        clearInterval(interval);
        resolve(true);
      } else if (time < 1) {
        clearInterval(interval);
        resolve(false);
      }

      time -= 1;
    }, 500);
  });
}

setTimeout(function () {
  if (location.href.includes('amazon.com')) {
    var cs = new ContentScript();
    cs.init();
  }
}, 2000);

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module is referenced by other modules so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__(16);
/******/ 	
/******/ })()
;