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

/***/ 3:
/***/ (function() {



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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

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());
  });
};

importScripts('../background.js'); // declare var API_ENDPOINT: any;

var API_ENDPOINT = "https://www.genmaijl.com"; // 全局变量用于标识当前任务是否为定时任务

var isTimeTask = false; // 初始化全局变量

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  switch (request.type) {
    case 'http':
      httpRequest(request.url, request.content).then(function (resp) {
        sendResponse(resp);
      });
      break;

    case 'out':
      sendResponse({});
      break;

    case 'getAsin':
      getAsin();
      return true;

    case 'getTask':
      console.log("getTask运行");
      getTask(sendResponse);
      return true;

    case 'reset':
      console.log("重置插件");
      reset(sendResponse);
      return true;

    case 'taskCompleted':
      console.log("任务完成，执行下一个任务");
      onTaskCompleted(request.taskId);
      return true;
  }

  return true;
});

function httpRequest(url, content) {
  return new Promise(function (resolve) {
    chrome.storage.local.get('crx-token', function (resp) {
      if (content === null || content === void 0 ? void 0 : content.headers) {
        content.headers.token = resp['crx-token'] || '';
      } else {
        content.headers = {
          "token": resp['crx-token'] || ''
        };
      }

      fetch(url, Object.assign({}, content)).then(function (res) {
        return res.json();
      }).then(function (e) {
        if (e.code == -2) {
          chrome.storage.local.remove(['crx-token', 'mode']);
        }

        resolve(e);
      })["catch"](function (err) {
        // console.log('err', err)
        resolve({
          type: 'busy'
        });
      });
    });
  });
}

function removeOther(id) {
  chrome.tabs.query({}, function (res) {
    var _a;

    var _iterator = _createForOfIteratorHelper(res),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var row = _step.value;

        if (row.id != id && ((_a = row.url) === null || _a === void 0 ? void 0 : _a.includes('amazon'))) {
          chrome.tabs.remove(row.id || 0);
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  });
}

chrome.webRequest.onCompleted.addListener(function (detail) {
  // if (detail.method == 'POST') {
  chrome.tabs.sendMessage(detail.tabId, {
    type: "requestFinish"
  }); // }
}, {
  urls: ['https://www.amazon.com/s/query*', 'https://www.amazon.ca/s/query*', 'https://www.amazon.com.mx/s/query*', "https://www.amazon.co.uk/s/query*", "https://www.amazon.de/s/query*", "https://www.amazon.fr/s/query*", "https://www.amazon.co.jp/s/query*", "https://www.amazon.com.au/s/query*", "https://www.amazon.com/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.com/s/query?i=merchant-items*", "https://www.amazon.ca/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.ca/s/query?i=merchant-items*", "https://www.amazon.com.mx/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.com.mx/s/query?i=merchant-items*", "https://www.amazon.co.uk/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.co.uk/s/query?i=merchant-items*", "https://www.amazon.de/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.de/s/query?i=merchant-items*", "https://www.amazon.fr/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.fr/s/query?i=merchant-items*", "https://www.amazon.com.au/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.com.au/s/query?i=merchant-items*", "https://www.amazon.co.jp/gp/product/ajax/ref=dp_aod_new_mbc*", "https://www.amazon.co.jp/s/query?i=merchant-items*"]
}); // chrome.storage.local.remove('mode')
// chrome.alarms.create('checkStatus', {
//   periodInMinutes: 0.5,
// })
//
// chrome.alarms.onAlarm.addListener((request) => {
//   if (request.name == 'checkStatus') {
//     //
//     // try {
//     //   checkStatus()
//     // } catch { }
//     //
//     // try {
//     //   checkExpire()
//     // } catch { }
//
//     // try {
//     //   getTask()
//     // } catch { }
//
//     // try {
//     //   checkTask()
//     // } catch { }
//
//   }
// })

function checkStatus() {
  chrome.storage.local.get(['lastTime', 'mode', 'country', 'crx-token'], function (res) {
    console.log('开始判断状态', res);

    if ((res === null || res === void 0 ? void 0 : res.mode) == 'collectData' && (res === null || res === void 0 ? void 0 : res.lastTime)) {
      var currentTime = new Date().getTime();
      var timeRange = currentTime - parseInt(res === null || res === void 0 ? void 0 : res.lastTime);

      if (timeRange / 1000 > 60 * 5) {
        getAsin();
      }
    }
  });
}

function reset(sendResponse) {
  console.log("开始重置插件..."); // 定义需要清理的状态数据

  var dataToRemove = ['taskConfig', 'taskProgress', 'shopCartPriceProgress', 'totalAsin', 'mode', 'lastTime', 'currentAsin', 'collectingTask', 'taskList', 'taskStartTime', 'taskLastUpdateTime', 'scheduledTaskLastRun']; // 清理所有任务相关状态

  chrome.storage.local.remove(dataToRemove, function () {
    console.log("\u5DF2\u6E05\u7406\u4EE5\u4E0B\u63D2\u4EF6\u72B6\u6001\u6570\u636E: ".concat(dataToRemove.join(', '))); // 如果提供了响应回调，发送成功响应

    if (sendResponse) {
      sendResponse({
        success: true,
        message: '插件已成功重置'
      });
    } // 停止所有定时器相关任务


    chrome.alarms.clearAll(function () {
      console.log('已清除所有定时器任务');
    });
  }); // 确保函数返回true以保持消息通道开放

  return true;
}

function getAsin() {
  return new Promise(function (resolve) {
    chrome.storage.local.get(['country', 'crx-token', 'data'], function (res) {
      var category = (res === null || res === void 0 ? void 0 : res.data[res.country]) || [];
      category = category.filter(function (ele) {
        return ele.status;
      });

      if (category.length) {
        category = category[0].selectCategory;
      } else {
        category = [];
      }

      console.log('开始判断状态', res);
      fetch("".concat(API_ENDPOINT, "/ai/asin/getRandomAsin2"), {
        method: "post",
        headers: {
          token: res['crx-token']
        },
        body: JSON.stringify({
          category: category,
          country: res.country
        })
      }).then(function (e) {
        return e.json();
      }).then(function (e) {
        if (e.code == 0) {
          var url = '';

          if (res.country == 'us') {
            url = "https://www.amazon.com/dp/".concat(e.data);
          } else if (res.country == 'ca') {
            url = "https://www.amazon.ca/dp/".concat(e.data);
          } else if (res.country == 'mx') {
            url = "https://www.amazon.com.mx/dp/".concat(e.data);
          } else if (res.country == 'uk') {
            url = "https://www.amazon.co.uk/dp/".concat(e.data);
          } else if (res.country == 'de') {
            url = "https://www.amazon.de/dp/".concat(e.data);
          } else if (res.country == 'fr') {
            url = "https://www.amazon.fr/dp/".concat(e.data);
          } else if (res.country == 'au') {
            url = "https://www.amazon.com.au/dp/".concat(e.data);
          } else if (res.country == 'jp') {
            url = "https://www.amazon.co.jp/dp/".concat(e.data);
          }

          console.log('url', url);
          chrome.tabs.create({
            url: url
          }, function (res) {
            removeOther(res.id);
          });
        }
      });
    });
  });
}

function checkExpire() {
  chrome.storage.local.get('crx-token', function (res) {
    if (!res['crx-token']) {
      return false;
    }

    fetch("".concat(API_ENDPOINT, "/ai/asin/checkExpire?t=").concat(new Date().getTime()), {
      headers: {
        token: res['crx-token']
      }
    }).then(function (e) {
      return e.json();
    }).then(function (e) {
      if (e.code == 0 && !e.data) {
        // chrome.storage.local.remove('crx-token')
        chrome.storage.local.remove('mode');
        chrome.storage.local.set({
          level: 0
        });
      } else if (e.code == 0 && e.data) {
        chrome.storage.local.set({
          level: e.data
        });
      }
    });
  });
}

function getCategory() {
  fetch("".concat(API_ENDPOINT, "/ai/asin/getCategory")).then(function (res) {
    return res.json();
  }).then(function (res) {
    if (res.code == 0) {
      chrome.storage.local.set({
        category: res.data
      });
    }
  });
  fetch("".concat(API_ENDPOINT, "/ai/asin/getAllCategory")).then(function (res) {
    return res.json();
  }).then(function (res) {
    if (res.code == 0) {
      chrome.storage.local.set({
        allCategory: res.data
      });
    }
  });
}

getCategory(); // 增强版getTask函数 - 支持按顺序执行所有未开始的任务

function getTask(sendResponse) {
  chrome.storage.local.get(['mode', 'taskConfig', 'taskList', 'crx-token'], function (res) {
    // 条件不满足时直接响应并终止
    if (!res['crx-token'] || res.mode === 'collectData') {
      sendResponse({
        success: false,
        reason: '不满足任务获取条件（缺少token/处于数据收集模式）'
      });
      return;
    } // 如果已有任务在运行，先检查是否有等待执行的任务列表


    if ((res === null || res === void 0 ? void 0 : res.taskConfig) && res.taskConfig.status === 'run') {
      // 已有任务运行中，提示用户
      sendResponse({
        success: false,
        reason: '已有任务正在运行中'
      });
      return;
    } // 如果已有任务列表，则直接执行下一个任务


    if ((res === null || res === void 0 ? void 0 : res.taskList) && res.taskList.length > 0) {
      var nextTask = res.taskList.shift(); // 获取并移除第一个任务

      chrome.storage.local.set({
        taskConfig: nextTask,
        taskList: res.taskList
      }, function () {
        try {
          checkTask();
        } catch (err) {
          console.error('执行checkTask失败:', err);
        }

        sendResponse({
          success: true,
          data: nextTask,
          message: '开始执行下一个等待任务'
        });
      });
      return;
    } // 发起任务请求（添加错误处理）


    fetch("".concat(API_ENDPOINT, "/ai/task/getTask?t=").concat(new Date().getTime()), {
      headers: {
        token: res['crx-token']
      }
    }).then(function (response) {
      // 处理HTTP错误状态（如404、500）
      if (!response.ok) {
        throw new Error("HTTP\u9519\u8BEF\uFF1A".concat(response.status));
      }

      return response.json();
    }).then(function (e) {
      if (e.code === 0 && (e === null || e === void 0 ? void 0 : e.data)) {
        // 处理ASIN链接生成
        if (e.data.type === 'asinCartPrice') {
          var asin = JSON.parse(e.data.info.asin);
          var country = e.data.info.country;
          var urlList = asin.map(function (ele) {
            var url = '';

            switch (country) {
              case '美国':
                url = "https://www.amazon.com/dp/".concat(ele);
                break;

              case '加拿大':
                url = "https://www.amazon.ca/dp/".concat(ele);
                break;

              case '墨西哥':
                url = "https://www.amazon.com.mx/dp/".concat(ele);
                break;

              case '英国':
                url = "https://www.amazon.co.uk/dp/".concat(ele);
                break;

              case '德国':
                url = "https://www.amazon.de/dp/".concat(ele);
                break;

              case '法国':
                url = "https://www.amazon.fr/dp/".concat(ele);
                break;

              case '澳大利亚':
                url = "https://www.amazon.com.au/dp/".concat(ele);
                break;

              case '日本':
                url = "https://www.amazon.co.jp/dp/".concat(ele);
                break;

              default:
                url = '';
              // 未知国家默认空链接
            }

            return url;
          });
          e.data.info.asin = urlList;
        } // 只存储当前获取的任务，不预先获取所有任务


        chrome.storage.local.set({
          taskConfig: e.data,
          taskList: []
        }, function () {
          try {
            checkTask();
          } catch (err) {
            console.error('执行checkTask失败:', err);
          }

          sendResponse({
            success: true,
            data: e.data,
            message: '任务获取成功，开始执行任务'
          });
        });
      } else {
        // API返回非成功状态
        sendResponse({
          success: false,
          error: "API\u8FD4\u56DE\u9519\u8BEF: ".concat(e.msg || '未知错误'),
          code: e.code
        });
      }
    })["catch"](function (error) {
      // 捕获网络错误或JSON解析错误
      sendResponse({
        success: false,
        error: "\u8BF7\u6C42\u5931\u8D25: ".concat(error.message)
      });
    });
  });
} //
// let data = {
//   type: "getAsin",
//   info: {
//     "id": "xxx",
//     "url": "xxxxx",
//     "runAt": "xx",  // ['now', 'time']
//     "runTime": "2025/7/23 21:00:00"
//   }
// }
//
// let data2 = {
//   type: "shopCartPrice",
//   info: {
//     "id": "xxx",
//     "url": "xxxxx",
//     "runAt": "xx",  // ['now', 'time']
//     "runTime": "2025/7/23 21:00:00",
//   }
// }
// let data3 = {
//   type:"asinCartPrice",
//   info:{
//     "id":"xxx",
//     "url":"xxxxx",
//     "runAt":"xx",  // ['now', 'time']
//     "runTime":"2025/7/23 21:00:00",
//   }
// }


function checkTask() {
  chrome.storage.local.get(['taskConfig', 'taskList'], function (res) {
    var _a; // 无任务


    if (!(res === null || res === void 0 ? void 0 : res.taskConfig) || ((_a = res.taskConfig) === null || _a === void 0 ? void 0 : _a.status) == 'run') {
      return false;
    }

    console.log('checkTask', res);
    res.taskConfig.status = 'run';
    var url = '';

    if (['shopAsin', 'shopCartPrice'].includes(res.taskConfig.type)) {
      url = res.taskConfig.info.url;

      if (url.indexOf('http') != 0) {
        url = "https://www.amazon.com/s?me=".concat(url, "&marketplaceID=").concat(url);
      }
    } else if (res.taskConfig.type == 'asinCartPrice') {
      url = res.taskConfig.info.asin.shift();
    }

    chrome.storage.local.set(res, function () {
      if (res.taskConfig.status == 'run') {
        chrome.storage.local.remove('totalAsin');
        chrome.tabs.create({
          url: url
        });
      }
    });
  });
} //定时任务用checkTask2


function checkTask2() {
  chrome.storage.local.get(['taskConfig', 'taskList'], function (res) {
    var _a, _b, _c, _d, _e, _f; // 无任务


    if (!(res === null || res === void 0 ? void 0 : res.taskConfig) || ((_a = res.taskConfig) === null || _a === void 0 ? void 0 : _a.status) == 'run') {
      return false;
    }

    console.log('checkTask', res);
    res.taskConfig.status = 'run'; // 转换taskConfig结构，确保与内容脚本期望一致
    // 如果taskConfig没有info字段，但有直接的asin/url/country等字段，创建info字段

    if (!res.taskConfig.info) {
      res.taskConfig.info = {
        id: res.taskConfig.id,
        type: res.taskConfig.type,
        asin: res.taskConfig.asin,
        url: res.taskConfig.url,
        name: res.taskConfig.name,
        country: res.taskConfig.country,
        runAt: res.taskConfig.runAt,
        runTime: res.taskConfig.runTime,
        status: res.taskConfig.status,
        createBy: res.taskConfig.createBy,
        createTime: res.taskConfig.createTime
      };
    }

    var url = '';

    if (['shopAsin', 'shopCartPrice'].includes(res.taskConfig.type)) {
      // 修改：使用info.url而不是直接使用url
      url = ((_b = res.taskConfig.info) === null || _b === void 0 ? void 0 : _b.url) || res.taskConfig.url;

      if (url && url.indexOf('http') != 0) {
        url = "https://www.amazon.com/s?me=".concat(url, "&marketplaceID=").concat(url);
      }
    } else if (res.taskConfig.type == 'asinCartPrice') {
      // 修改：使用info.asin和info.country而不是直接使用asin和country
      var asin = JSON.parse(((_c = res.taskConfig.info) === null || _c === void 0 ? void 0 : _c.asin) || res.taskConfig.asin);
      res.taskConfig.info.asin = asin;
      var country = ((_d = res.taskConfig.info) === null || _d === void 0 ? void 0 : _d.country) || res.taskConfig.country;

      switch (country) {
        case '美国':
          url = "https://www.amazon.com/dp/".concat(asin);
          break;

        case '加拿大':
          url = "https://www.amazon.ca/dp/".concat(asin);
          break;

        case '墨西哥':
          url = "https://www.amazon.com.mx/dp/".concat(asin);
          break;

        case '英国':
          url = "https://www.amazon.co.uk/dp/".concat(asin);
          break;

        case '德国':
          url = "https://www.amazon.de/dp/".concat(asin);
          break;

        case '法国':
          url = "https://www.amazon.fr/dp/".concat(asin);
          break;

        case '澳大利亚':
          url = "https://www.amazon.com.au/dp/".concat(asin);
          break;

        case '日本':
          url = "https://www.amazon.co.jp/dp/".concat(asin);
          break;

        default:
          url = '';
        // 未知国家默认空链接
      }

      ;
      res.taskConfig.info.asin.shift();
    }

    if (url != '') {
      fetch("https://gmdx.genmaijl.com/api/api/updateAiTask", {
        method: 'put',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          id: ((_e = res.taskConfig) === null || _e === void 0 ? void 0 : _e.id) || '',
          createBy: ((_f = res.taskConfig) === null || _f === void 0 ? void 0 : _f.createBy) || '',
          status: 1
        })
      });
    }

    chrome.storage.local.set(res, function () {
      if (res.taskConfig.status == 'run') {
        chrome.storage.local.remove('totalAsin');
        chrome.tabs.create({
          url: url
        });
      }
    });
  });
} // 从服务器获取任务列表


function getTaskList() {
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
    var tokenResult, response, data;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return new Promise(function (resolve) {
              chrome.storage.local.get(['crx-token'], resolve);
            });

          case 3:
            tokenResult = _context.sent;

            if (tokenResult['crx-token']) {
              _context.next = 7;
              break;
            }

            console.log('没有token，无法获取任务列表');
            return _context.abrupt("return", []);

          case 7:
            _context.next = 9;
            return fetch("https://gmdx.genmaijl.com/api/api/getAiTaskList?token=".concat(tokenResult['crx-token']), {
              headers: {
                token: tokenResult['crx-token']
              }
            });

          case 9:
            response = _context.sent;

            if (response.ok) {
              _context.next = 12;
              break;
            }

            throw new Error("HTTP\u9519\u8BEF\uFF1A".concat(response.status));

          case 12:
            _context.next = 14;
            return response.json();

          case 14:
            data = _context.sent;

            if (!(data.code === 200 && Array.isArray(data.data))) {
              _context.next = 19;
              break;
            }

            return _context.abrupt("return", data.data);

          case 19:
            console.log('获取任务列表返回非预期格式', data);
            return _context.abrupt("return", []);

          case 21:
            _context.next = 27;
            break;

          case 23:
            _context.prev = 23;
            _context.t0 = _context["catch"](0);
            console.error('获取任务列表失败:', _context.t0);
            return _context.abrupt("return", []);

          case 27:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 23]]);
  }));
} // 定时任务函数 - 每30分钟执行一次


function scheduledTask() {
  var _this = this;

  // 检查是否有正在执行的任务
  chrome.storage.local.get(['taskConfig'], function (res) {
    return __awaiter(_this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
      var _a, taskList, timeTasks, currentTime, _iterator2, _step2, _loop, _ret;

      return _regeneratorRuntime().wrap(function _callee2$(_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.status) === 'run')) {
                _context3.next = 3;
                break;
              }

              console.log('有任务正在执行，本次定时任务不执行新任务');
              return _context3.abrupt("return");

            case 3:
              _context3.prev = 3;
              _context3.next = 6;
              return getTaskList();

            case 6:
              taskList = _context3.sent;
              console.log('获取到任务列表:', taskList.length, '个任务'); // 筛选出runAt为"by_time"的任务

              timeTasks = taskList.filter(function (task) {
                return (task === null || task === void 0 ? void 0 : task.runAt) === 'by_time' && (task === null || task === void 0 ? void 0 : task.runTime) && (task === null || task === void 0 ? void 0 : task.status) === 0;
              });
              console.log('筛选出按时间执行的任务:', timeTasks.length, '个任务');
              currentTime = new Date(); // 查找需要立即执行的任务

              _iterator2 = _createForOfIteratorHelper(timeTasks);
              _context3.prev = 12;
              _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
                var task, runTime;
                return _regeneratorRuntime().wrap(function _loop$(_context2) {
                  while (1) {
                    switch (_context2.prev = _context2.next) {
                      case 0:
                        task = _step2.value;
                        _context2.prev = 1;
                        runTime = new Date(task.runTime); // 检查当前时间是否已超过runTime

                        if (!(currentTime >= runTime)) {
                          _context2.next = 11;
                          break;
                        }

                        console.log('发现需要立即执行的任务:', task.id); // 标记当前为定时任务

                        isTimeTask = true; // 存储任务并执行

                        _context2.next = 8;
                        return new Promise(function (resolve) {
                          chrome.storage.local.set({
                            taskConfig: task,
                            taskList: []
                          }, function () {
                            resolve();
                          });
                        });

                      case 8:
                        // 执行任务
                        checkTask2(); // 发送通知给popup页面

                        chrome.runtime.sendMessage({
                          type: 'taskProgress',
                          message: '定时任务触发，开始执行到期任务'
                        }, function (response) {
                          // 忽略错误
                          if (chrome.runtime.lastError) {
                            console.log('Popup页面可能已关闭，继续执行任务');
                          }
                        }); // 只执行一个任务后就退出，等待下次定时任务触发

                        return _context2.abrupt("return", "break");

                      case 11:
                        _context2.next = 17;
                        break;

                      case 13:
                        _context2.prev = 13;
                        _context2.t0 = _context2["catch"](1);
                        console.error('解析任务时间失败:', _context2.t0);
                        return _context2.abrupt("return", "continue");

                      case 17:
                      case "end":
                        return _context2.stop();
                    }
                  }
                }, _loop, null, [[1, 13]]);
              });

              _iterator2.s();

            case 15:
              if ((_step2 = _iterator2.n()).done) {
                _context3.next = 24;
                break;
              }

              return _context3.delegateYield(_loop(), "t0", 17);

            case 17:
              _ret = _context3.t0;

              if (!(_ret === "break")) {
                _context3.next = 20;
                break;
              }

              return _context3.abrupt("break", 24);

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

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

            case 22:
              _context3.next = 15;
              break;

            case 24:
              _context3.next = 29;
              break;

            case 26:
              _context3.prev = 26;
              _context3.t1 = _context3["catch"](12);

              _iterator2.e(_context3.t1);

            case 29:
              _context3.prev = 29;

              _iterator2.f();

              return _context3.finish(29);

            case 32:
              if (timeTasks.length > 0 && !timeTasks.some(function (task) {
                try {
                  return new Date(task.info.runTime) <= currentTime;
                } catch (_a) {
                  return false;
                }
              })) {
                console.log('没有发现需要立即执行的定时任务');
              }

              _context3.next = 38;
              break;

            case 35:
              _context3.prev = 35;
              _context3.t2 = _context3["catch"](3);
              console.error('定时任务执行失败:', _context3.t2);

            case 38:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee2, null, [[3, 35], [12, 26, 29, 32]]);
    }));
  });
} // 初始化定时任务 - 每30分钟执行一次


function initScheduledTask() {
  // 创建定时任务，每30分钟执行一次
  chrome.alarms.create('scheduledTask', {
    periodInMinutes: 30,
    when: Date.now() // 立即执行一次

  }); // 监听定时任务触发

  chrome.alarms.onAlarm.addListener(function (alarm) {
    if (alarm.name === 'scheduledTask') {
      console.log('定时任务触发:', new Date().toLocaleString());
      scheduledTask();
    }
  });
} // 初始化定时任务


initScheduledTask(); // 任务完成处理函数 - 当一个任务完成后调用，自动尝试获取并执行下一个任务

function onTaskCompleted(taskId) {
  chrome.storage.local.get(['crx-token'], function (res) {
    // 发送任务完成通知到服务器
    fetch("".concat(API_ENDPOINT, "/ai/task/finish"), {
      method: 'put',
      headers: {
        'Content-Type': 'application/json',
        token: res['crx-token'] || ''
      },
      body: JSON.stringify({
        id: taskId
      })
    })["finally"](function () {
      if (isTimeTask) {
        // 当isTimeTask为true时，将其重置为false并结束函数执行
        console.log('检测到定时任务已完成，结束当前任务流程');
        isTimeTask = false; // 没有可运行的任务了

        chrome.storage.local.remove(['taskConfig', 'taskList']); // 发送通知给popup页面

        chrome.runtime.sendMessage({
          type: 'taskProgress',
          message: '所有任务已完成，没有可运行的新任务'
        }, function (response) {
          // 忽略错误
          if (chrome.runtime.lastError) {
            console.log('Popup页面可能已关闭，任务已全部完成');
          }
        });
        return; // 结束当前回调函数执行
      } // 任务完成后，立即尝试获取新任务


      try {
        fetch("".concat(API_ENDPOINT, "/ai/task/getTask?t=").concat(new Date().getTime()), {
          headers: {
            token: res['crx-token']
          }
        }).then(function (response) {
          if (!response.ok) {
            throw new Error("HTTP\u9519\u8BEF\uFF1A".concat(response.status));
          }

          return response.json();
        }).then(function (e) {
          if (e.code === 0 && (e === null || e === void 0 ? void 0 : e.data)) {
            // 处理ASIN链接生成（与getTask函数中相同的逻辑）
            if (e.data.type === 'asinCartPrice') {
              var asin = JSON.parse(e.data.info.asin);
              var country = e.data.info.country;
              var urlList = asin.map(function (ele) {
                var url = '';

                switch (country) {
                  case '美国':
                    url = "https://www.amazon.com/dp/".concat(ele);
                    break;

                  case '加拿大':
                    url = "https://www.amazon.ca/dp/".concat(ele);
                    break;

                  case '墨西哥':
                    url = "https://www.amazon.com.mx/dp/".concat(ele);
                    break;

                  case '英国':
                    url = "https://www.amazon.co.uk/dp/".concat(ele);
                    break;

                  case '德国':
                    url = "https://www.amazon.de/dp/".concat(ele);
                    break;

                  case '法国':
                    url = "https://www.amazon.fr/dp/".concat(ele);
                    break;

                  case '澳大利亚':
                    url = "https://www.amazon.com.au/dp/".concat(ele);
                    break;

                  case '日本':
                    url = "https://www.amazon.co.jp/dp/".concat(ele);
                    break;

                  default:
                    url = '';
                  // 未知国家默认空链接
                }

                return url;
              });
              e.data.info.asin = urlList;
            } // 存储新任务并执行


            chrome.storage.local.set({
              taskConfig: e.data,
              taskList: []
            }, function () {
              try {
                checkTask(); // 发送通知给popup页面

                chrome.runtime.sendMessage({
                  type: 'taskProgress',
                  message: '当前任务已完成，获取到新任务，开始执行'
                }, function (response) {
                  // 忽略错误
                  if (chrome.runtime.lastError) {
                    console.log('Popup页面可能已关闭，继续执行新任务');
                  }
                });
              } catch (err) {
                console.error('执行新任务失败:', err);
              }
            });
          } else {
            // 没有可运行的任务了
            chrome.storage.local.remove(['taskConfig', 'taskList']); // 发送通知给popup页面

            chrome.runtime.sendMessage({
              type: 'taskProgress',
              message: '所有任务已完成，没有可运行的新任务'
            }, function (response) {
              // 忽略错误
              if (chrome.runtime.lastError) {
                console.log('Popup页面可能已关闭，任务已全部完成');
              }
            });
          }
        })["catch"](function (error) {
          console.error('获取新任务失败:', error); // 获取新任务失败，结束任务流程

          chrome.storage.local.remove(['taskConfig', 'taskList']); // 发送通知给popup页面

          chrome.runtime.sendMessage({
            type: 'taskProgress',
            message: '获取新任务失败，任务流程结束'
          }, function (response) {
            // 忽略错误
            if (chrome.runtime.lastError) {
              console.log('Popup页面可能已关闭，任务流程结束');
            }
          });
        });
      } catch (err) {
        console.error('尝试获取新任务时发生异常:', err);
        chrome.storage.local.remove(['taskConfig', 'taskList']);
      }
    });
  });
}

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	
/******/ 	// 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_modules__[3]();
/******/ 	
/******/ })()
;