(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["chunk-69083aaa"],{

/***/ "2317":
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),

/***/ "2f79":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ cores; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ multiTskHandleMap; });

// EXTERNAL MODULE: ./src/utils/util.js
var util = __webpack_require__("ca00");

// EXTERNAL MODULE: ./src/data/log.js
var log = __webpack_require__("6b23");

// EXTERNAL MODULE: ./src/platform/temu/index.js
var temu = __webpack_require__("c04e");

// CONCATENATED MODULE: ./src/platform/temu/getSupplierPriceByOrder.js
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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }




var CB_ORDER_BATCH_SIZE = 50;
var LOCAL_ORDER_BATCH_SIZE = 100;
var LOCAL_ORDER_PAGE_SIZE = 100;
var CB_ORDER_MIX_AREA = 'US_GLOBAL_MIX';
var CB_ORDER_AREA_HOST_MAP = {
  US: temu["h" /* temu */].cbUsHost,
  EU: temu["h" /* temu */].cbEuHost,
  GLOBAL: temu["h" /* temu */].cbGlobalHost
};
var isOrderSupplierPriceTask = function isOrderSupplierPriceTask(task) {
  return (task === null || task === void 0 ? void 0 : task.task_scene) === 'ORDER_ID' || (task === null || task === void 0 ? void 0 : task.taskScene) === 'ORDER_ID';
};

var getCbOrderArea = function getCbOrderArea(task) {
  return String((task === null || task === void 0 ? void 0 : task.area) || '').toUpperCase();
};

var getCbOrderSupplierPriceHost = function getCbOrderSupplierPriceHost(area) {
  return CB_ORDER_AREA_HOST_MAP[area];
};

var switchCbOrderSupplierPriceHost = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(task, host) {
    var loginRes, msg;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            task.host = host;
            _context.next = 3;
            return Object(temu["g" /* loginCb */])(task);

          case 3:
            loginRes = _context.sent;

            if (!loginRes) {
              _context.next = 6;
              break;
            }

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

          case 6:
            msg = "\u5207\u6362\u5230".concat(host, "\u7AD9\u70B9\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5");
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context.abrupt("return", false);

          case 10:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function switchCbOrderSupplierPriceHost(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

var getOrderSn = function getOrderSn(item) {
  return (item === null || item === void 0 ? void 0 : item.parentOrderSn) && String(item.parentOrderSn);
};

var getReturnedOrderSnSet = function getReturnedOrderSnSet() {
  var list = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  return new Set(list.map(getOrderSn).filter(Boolean));
};

var isEmptySupplierPriceOrder = function isEmptySupplierPriceOrder(item) {
  var orderSn = getOrderSn(item);
  var supplierPriceList = item === null || item === void 0 ? void 0 : item.supplierPriceWithSubOrderRespList;
  return orderSn && Array.isArray(supplierPriceList) && supplierPriceList.length === 0;
};

var buildCbSupplierPriceByOrderResult = function buildCbSupplierPriceByOrderResult(task, orderIds, succOrderList, failOrderIds, lastErrorMsg) {
  if (!succOrderList.length) {
    task.status = 14;
    return {
      code: 2,
      msg: lastErrorMsg || "\u672A\u83B7\u53D6\u5230\u8BA2\u5355\u4F9B\u8D27\u4EF7\u6570\u636E,\u9700\u8981\u83B7\u53D6\u7684\u8BA2\u5355\u53F7:".concat(orderIds.join(','))
    };
  }

  if (failOrderIds.length) {
    task.failOrderIds = _toConsumableArray(new Set(failOrderIds));
    return {
      code: 4,
      msg: '部分订单供货价获取失败',
      result: succOrderList,
      data: {
        failOrderIds: task.failOrderIds,
        order_ids: task.order_ids || task.orderIds || orderIds
      }
    };
  }

  task.failOrderIds = [];
  return {
    code: 0,
    msg: '获取完毕',
    result: succOrderList
  };
};

var pickLocalOrderFields = function pickLocalOrderFields(item) {
  var _item$parentOrderMap;

  var parentOrderSn = item === null || item === void 0 ? void 0 : (_item$parentOrderMap = item.parentOrderMap) === null || _item$parentOrderMap === void 0 ? void 0 : _item$parentOrderMap.parentOrderSn;
  if (!parentOrderSn) return null;
  return {
    parentOrderMap: {
      parentOrderSn: parentOrderSn
    },
    orderList: (item.orderList || []).reduce(function (arr, orderItem) {
      var _orderItem$goodsRetai, _orderItem$skuId, _orderItem$activityGo, _orderItem$goodsBaseP;

      if (!(orderItem !== null && orderItem !== void 0 && orderItem.orderSn)) return arr;
      arr.push({
        goodsRetailPrice: (_orderItem$goodsRetai = orderItem.goodsRetailPrice) !== null && _orderItem$goodsRetai !== void 0 ? _orderItem$goodsRetai : null,
        skuId: (_orderItem$skuId = orderItem.skuId) !== null && _orderItem$skuId !== void 0 ? _orderItem$skuId : null,
        orderSn: orderItem.orderSn,
        activityGoodsBasePrice: (_orderItem$activityGo = orderItem.activityGoodsBasePrice) !== null && _orderItem$activityGo !== void 0 ? _orderItem$activityGo : null,
        goodsBasePrice: (_orderItem$goodsBaseP = orderItem.goodsBasePrice) !== null && _orderItem$goodsBaseP !== void 0 ? _orderItem$goodsBaseP : null
      });
      return arr;
    }, [])
  };
};

var requestCbSupplierPriceByOrder = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(task, parentOrderSnList) {
    var retry,
        _yield$nativeRequest,
        success,
        errorMsg,
        errorCode,
        result,
        msg,
        _msg,
        _args2 = arguments;

    return _regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            retry = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : 0;
            _context2.prev = 1;
            _context2.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/bg-visage-agent-seller/product/sku/supplierPrice/batchQueryByOrder"), 'post', {
              parentOrderSnList: parentOrderSnList
            }, {
              Mallid: task.real_mall_id
            });

          case 4:
            _yield$nativeRequest = _context2.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            errorCode = _yield$nativeRequest.errorCode;
            result = _yield$nativeRequest.result;

            if (!(success && result && Array.isArray(result.querySupplierPriceByOrderRespList))) {
              _context2.next = 11;
              break;
            }

            return _context2.abrupt("return", {
              code: 0,
              list: result.querySupplierPriceByOrderRespList
            });

          case 11:
            msg = "\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u8DE8\u5883\u534A\u6258\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errorMsg || errorCode || JSON.stringify(result));
            log["a" /* default */].setLog(msg);
            return _context2.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 16:
            _context2.prev = 16;
            _context2.t0 = _context2["catch"](1);
            _msg = "\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u8DE8\u5883\u534A\u6258\u4F9B\u8D27\u4EF7\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(_msg);

            if (!(retry < 3)) {
              _context2.next = 25;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context2.next = 24;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 24:
            return _context2.abrupt("return", requestCbSupplierPriceByOrder(task, parentOrderSnList, ++retry));

          case 25:
            return _context2.abrupt("return", {
              code: 1,
              msg: _msg
            });

          case 26:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 16]]);
  }));

  return function requestCbSupplierPriceByOrder(_x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}();

var getCbSupplierPriceByOrder = /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(task) {
    var area, host, msg, orderIds, failOrderIds, succOrderList, lastErrorMsg, batchOrderIdList, i, _i, ids, _yield$requestCbSuppl, code, list, _msg2;

    return _regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            area = getCbOrderArea(task);

            if (!(area === CB_ORDER_MIX_AREA)) {
              _context3.next = 3;
              break;
            }

            return _context3.abrupt("return", getCbSupplierPriceByMixedOrder(task));

          case 3:
            host = getCbOrderSupplierPriceHost(area);

            if (host) {
              _context3.next = 9;
              break;
            }

            msg = "\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u8DE8\u5883\u534A\u6258\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4E0D\u652F\u6301\u7684area:".concat(task.area);
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context3.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 9:
            log["a" /* default */].setLog("\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u8DE8\u5883\u534A\u6258\u4F9B\u8D27\u4EF7\uFF0Carea:".concat(area, "\uFF0Chost:").concat(host));
            _context3.next = 12;
            return switchCbOrderSupplierPriceHost(task, host);

          case 12:
            if (_context3.sent) {
              _context3.next = 14;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 14:
            orderIds = _toConsumableArray(new Set((task.failOrderIds || task.order_ids || task.orderIds || []).map(String).filter(Boolean)));
            failOrderIds = [];
            succOrderList = [];
            lastErrorMsg = '';

            if (orderIds.length) {
              _context3.next = 21;
              break;
            }

            task.status = 14;
            return _context3.abrupt("return", {
              code: 2,
              msg: '未获取到任何订单号，请检查 order_ids'
            });

          case 21:
            batchOrderIdList = [];

            for (i = 0; i < orderIds.length; i += CB_ORDER_BATCH_SIZE) {
              batchOrderIdList.push(orderIds.slice(i, i + CB_ORDER_BATCH_SIZE));
            }

            _i = 0;

          case 24:
            if (!(_i < batchOrderIdList.length)) {
              _context3.next = 40;
              break;
            }

            ids = batchOrderIdList[_i];
            task.currentNum = Math.min((_i + 1) * CB_ORDER_BATCH_SIZE, orderIds.length);
            task.total = orderIds.length;
            _context3.next = 30;
            return Object(util["h" /* delayed */])(500);

          case 30:
            _context3.next = 32;
            return requestCbSupplierPriceByOrder(task, ids);

          case 32:
            _yield$requestCbSuppl = _context3.sent;
            code = _yield$requestCbSuppl.code;
            list = _yield$requestCbSuppl.list;
            _msg2 = _yield$requestCbSuppl.msg;

            if (code === 0) {
              succOrderList.push.apply(succOrderList, _toConsumableArray(list || []));
            } else {
              failOrderIds.push.apply(failOrderIds, _toConsumableArray(ids));
              lastErrorMsg = _msg2;
            }

          case 37:
            _i++;
            _context3.next = 24;
            break;

          case 40:
            return _context3.abrupt("return", buildCbSupplierPriceByOrderResult(task, orderIds, succOrderList, failOrderIds, lastErrorMsg));

          case 41:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function getCbSupplierPriceByOrder(_x5) {
    return _ref3.apply(this, arguments);
  };
}();

var getCbSupplierPriceByMixedOrder = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(task) {
    var orderIds, failOrderIds, succOrderList, lastErrorMsg, batchOrderIdList, i, _loop, _i2, _ret;

    return _regeneratorRuntime().wrap(function _callee4$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            orderIds = _toConsumableArray(new Set((task.failOrderIds || task.order_ids || task.orderIds || []).map(String).filter(Boolean)));
            failOrderIds = [];
            succOrderList = [];
            lastErrorMsg = '';

            if (orderIds.length) {
              _context5.next = 7;
              break;
            }

            task.status = 14;
            return _context5.abrupt("return", {
              code: 2,
              msg: '未获取到任何订单号，请检查 order_ids'
            });

          case 7:
            batchOrderIdList = [];

            for (i = 0; i < orderIds.length; i += CB_ORDER_BATCH_SIZE) {
              batchOrderIdList.push(orderIds.slice(i, i + CB_ORDER_BATCH_SIZE));
            }

            log["a" /* default */].setLog("\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u8DE8\u5883\u534A\u6258\u4F9B\u8D27\u4EF7\uFF0Carea:".concat(CB_ORDER_MIX_AREA, "\uFF0C\u5148\u8BF7\u6C42US\u518D\u8BF7\u6C42GLOBAL"));
            _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(_i2) {
              var ids, usRes, usList, usReturnedOrderSnSet, globalOrderIds, globalRes, globalList, globalReturnedOrderSnSet;
              return _regeneratorRuntime().wrap(function _loop$(_context4) {
                while (1) {
                  switch (_context4.prev = _context4.next) {
                    case 0:
                      ids = batchOrderIdList[_i2];
                      task.currentNum = Math.min((_i2 + 1) * CB_ORDER_BATCH_SIZE, orderIds.length);
                      task.total = orderIds.length;
                      _context4.next = 5;
                      return Object(util["h" /* delayed */])(500);

                    case 5:
                      _context4.next = 7;
                      return switchCbOrderSupplierPriceHost(task, temu["h" /* temu */].cbUsHost);

                    case 7:
                      if (_context4.sent) {
                        _context4.next = 9;
                        break;
                      }

                      return _context4.abrupt("return", {
                        v: {
                          code: 1,
                          msg: task.msg
                        }
                      });

                    case 9:
                      _context4.next = 11;
                      return requestCbSupplierPriceByOrder(task, ids);

                    case 11:
                      usRes = _context4.sent;

                      if (!(usRes.code !== 0)) {
                        _context4.next = 16;
                        break;
                      }

                      failOrderIds.push.apply(failOrderIds, _toConsumableArray(ids));
                      lastErrorMsg = usRes.msg;
                      return _context4.abrupt("return", "continue");

                    case 16:
                      usList = usRes.list || [];
                      usReturnedOrderSnSet = getReturnedOrderSnSet(usList);
                      globalOrderIds = [];
                      usList.forEach(function (item) {
                        if (isEmptySupplierPriceOrder(item)) {
                          globalOrderIds.push(getOrderSn(item));
                        } else {
                          succOrderList.push(item);
                        }
                      });
                      failOrderIds.push.apply(failOrderIds, _toConsumableArray(ids.filter(function (id) {
                        return !usReturnedOrderSnSet.has(String(id));
                      })));
                      log["a" /* default */].setLog("US_GLOBAL_MIX\u7B2C".concat(_i2 + 1, "/").concat(batchOrderIdList.length, "\u6279\uFF0CUS\u8BF7\u6C42").concat(ids.length, "\u4E2A\u8BA2\u5355\uFF0C\u9700\u8F6CGLOBAL\u8BF7\u6C42").concat(globalOrderIds.length, "\u4E2A\u8BA2\u5355"));

                      if (globalOrderIds.length) {
                        _context4.next = 24;
                        break;
                      }

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

                    case 24:
                      _context4.next = 26;
                      return switchCbOrderSupplierPriceHost(task, temu["h" /* temu */].cbGlobalHost);

                    case 26:
                      if (_context4.sent) {
                        _context4.next = 30;
                        break;
                      }

                      failOrderIds.push.apply(failOrderIds, globalOrderIds);
                      lastErrorMsg = task.msg;
                      return _context4.abrupt("return", "continue");

                    case 30:
                      _context4.next = 32;
                      return requestCbSupplierPriceByOrder(task, globalOrderIds);

                    case 32:
                      globalRes = _context4.sent;

                      if (!(globalRes.code !== 0)) {
                        _context4.next = 37;
                        break;
                      }

                      failOrderIds.push.apply(failOrderIds, globalOrderIds);
                      lastErrorMsg = globalRes.msg;
                      return _context4.abrupt("return", "continue");

                    case 37:
                      globalList = globalRes.list || [];
                      globalReturnedOrderSnSet = getReturnedOrderSnSet(globalList);
                      succOrderList.push.apply(succOrderList, _toConsumableArray(globalList));
                      failOrderIds.push.apply(failOrderIds, _toConsumableArray(globalOrderIds.filter(function (id) {
                        return !globalReturnedOrderSnSet.has(String(id));
                      })));
                      log["a" /* default */].setLog("US_GLOBAL_MIX\u7B2C".concat(_i2 + 1, "/").concat(batchOrderIdList.length, "\u6279\uFF0CGLOBAL\u8FD4\u56DE").concat(globalList.length, "\u4E2A\u8BA2\u5355"));

                    case 42:
                    case "end":
                      return _context4.stop();
                  }
                }
              }, _loop);
            });
            _i2 = 0;

          case 12:
            if (!(_i2 < batchOrderIdList.length)) {
              _context5.next = 22;
              break;
            }

            return _context5.delegateYield(_loop(_i2), "t0", 14);

          case 14:
            _ret = _context5.t0;

            if (!(_ret === "continue")) {
              _context5.next = 17;
              break;
            }

            return _context5.abrupt("continue", 19);

          case 17:
            if (!(_typeof(_ret) === "object")) {
              _context5.next = 19;
              break;
            }

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

          case 19:
            _i2++;
            _context5.next = 12;
            break;

          case 22:
            return _context5.abrupt("return", buildCbSupplierPriceByOrderResult(task, orderIds, succOrderList, failOrderIds, lastErrorMsg));

          case 23:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee4);
  }));

  return function getCbSupplierPriceByMixedOrder(_x6) {
    return _ref4.apply(this, arguments);
  };
}();

var requestLocalSupplierPriceByOrder = /*#__PURE__*/function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(task, parentOrderSnList) {
    var pageNumber,
        retry,
        _yield$nativeRequest2,
        success,
        errorMsg,
        errorCode,
        result,
        msg,
        _msg3,
        _args6 = arguments;

    return _regeneratorRuntime().wrap(function _callee5$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            pageNumber = _args6.length > 2 && _args6[2] !== undefined ? _args6[2] : 1;
            retry = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : 0;
            _context6.prev = 2;
            _context6.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/kirogi/local/recentOrderList"), 'post', {
              pageNumber: pageNumber,
              pageSize: LOCAL_ORDER_PAGE_SIZE,
              sortType: 9,
              queryType: 0,
              parentOrderSnList: parentOrderSnList
            }, {
              'Content-Type': 'application/json;charset=UTF-8'
            });

          case 5:
            _yield$nativeRequest2 = _context6.sent;
            success = _yield$nativeRequest2.success;
            errorMsg = _yield$nativeRequest2.errorMsg;
            errorCode = _yield$nativeRequest2.errorCode;
            result = _yield$nativeRequest2.result;

            if (!(success && result && Array.isArray(result.pageItems))) {
              _context6.next = 12;
              break;
            }

            return _context6.abrupt("return", {
              code: 0,
              result: result
            });

          case 12:
            msg = "\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u672C\u571F\u5E97\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errorMsg || errorCode || JSON.stringify(result));
            log["a" /* default */].setLog(msg);
            return _context6.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 17:
            _context6.prev = 17;
            _context6.t0 = _context6["catch"](2);
            _msg3 = "\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u672C\u571F\u5E97\u4F9B\u8D27\u4EF7\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context6.t0, task));
            log["a" /* default */].setLog(_msg3);

            if (!(retry < 3)) {
              _context6.next = 26;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context6.next = 25;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 25:
            return _context6.abrupt("return", requestLocalSupplierPriceByOrder(task, parentOrderSnList, pageNumber, ++retry));

          case 26:
            return _context6.abrupt("return", {
              code: 1,
              msg: _msg3
            });

          case 27:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee5, null, [[2, 17]]);
  }));

  return function requestLocalSupplierPriceByOrder(_x7, _x8) {
    return _ref5.apply(this, arguments);
  };
}();

var getLocalSupplierPriceByOrderBatch = /*#__PURE__*/function () {
  var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(task, parentOrderSnList) {
    var list, pageNumber, totalItemNum, hasMore, _yield$requestLocalSu, code, result, msg, _ref7, _ref7$pageItems, pageItems, _ref7$totalItemNum, total, returnedOrderIdSet, failOrderIds;

    return _regeneratorRuntime().wrap(function _callee6$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            list = [];
            pageNumber = 1;
            totalItemNum = 0;
            hasMore = true;

          case 4:
            if (!hasMore) {
              _context7.next = 24;
              break;
            }

            _context7.next = 7;
            return requestLocalSupplierPriceByOrder(task, parentOrderSnList, pageNumber);

          case 7:
            _yield$requestLocalSu = _context7.sent;
            code = _yield$requestLocalSu.code;
            result = _yield$requestLocalSu.result;
            msg = _yield$requestLocalSu.msg;

            if (!(code !== 0)) {
              _context7.next = 13;
              break;
            }

            return _context7.abrupt("return", {
              code: code,
              msg: msg
            });

          case 13:
            _ref7 = result || {}, _ref7$pageItems = _ref7.pageItems, pageItems = _ref7$pageItems === void 0 ? [] : _ref7$pageItems, _ref7$totalItemNum = _ref7.totalItemNum, total = _ref7$totalItemNum === void 0 ? 0 : _ref7$totalItemNum;
            totalItemNum = total;
            list.push.apply(list, _toConsumableArray(pageItems.map(pickLocalOrderFields).filter(Boolean))); // 实际接口响应的totalItemNumc超过100时，获取下一页数据

            if (!(!pageItems.length || pageNumber * LOCAL_ORDER_PAGE_SIZE >= totalItemNum)) {
              _context7.next = 19;
              break;
            }

            hasMore = false;
            return _context7.abrupt("continue", 4);

          case 19:
            pageNumber++;
            _context7.next = 22;
            return Object(util["h" /* delayed */])(300);

          case 22:
            _context7.next = 4;
            break;

          case 24:
            returnedOrderIdSet = new Set(list.map(function (item) {
              return String(item.parentOrderMap.parentOrderSn);
            })); // 未成功获取的订单ids

            failOrderIds = parentOrderSnList.filter(function (parentOrderSn) {
              return !returnedOrderIdSet.has(String(parentOrderSn));
            });
            return _context7.abrupt("return", {
              code: 0,
              list: list,
              failOrderIds: failOrderIds
            });

          case 27:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee6);
  }));

  return function getLocalSupplierPriceByOrderBatch(_x9, _x10) {
    return _ref6.apply(this, arguments);
  };
}();

var getLocalSupplierPriceByOrder = /*#__PURE__*/function () {
  var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(task) {
    var orderIds, failOrderIds, succOrderList, lastErrorMsg, batchOrderIdList, i, _i3, ids, _yield$getLocalSuppli, code, list, msg, missingOrderIds;

    return _regeneratorRuntime().wrap(function _callee7$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            orderIds = _toConsumableArray(new Set((task.failOrderIds || task.order_ids || task.orderIds || []).map(String).filter(Boolean)));
            failOrderIds = [];
            succOrderList = [];
            lastErrorMsg = '';

            if (orderIds.length) {
              _context8.next = 7;
              break;
            }

            task.status = 14;
            return _context8.abrupt("return", {
              code: 2,
              msg: '未获取到任何订单号，请检查 order_ids'
            });

          case 7:
            batchOrderIdList = [];

            for (i = 0; i < orderIds.length; i += LOCAL_ORDER_BATCH_SIZE) {
              batchOrderIdList.push(orderIds.slice(i, i + LOCAL_ORDER_BATCH_SIZE));
            }

            _i3 = 0;

          case 10:
            if (!(_i3 < batchOrderIdList.length)) {
              _context8.next = 27;
              break;
            }

            ids = batchOrderIdList[_i3];
            task.currentNum = Math.min((_i3 + 1) * LOCAL_ORDER_BATCH_SIZE, orderIds.length);
            task.total = orderIds.length;
            _context8.next = 16;
            return Object(util["h" /* delayed */])(500);

          case 16:
            _context8.next = 18;
            return getLocalSupplierPriceByOrderBatch(task, ids);

          case 18:
            _yield$getLocalSuppli = _context8.sent;
            code = _yield$getLocalSuppli.code;
            list = _yield$getLocalSuppli.list;
            msg = _yield$getLocalSuppli.msg;
            missingOrderIds = _yield$getLocalSuppli.failOrderIds;

            if (code === 0) {
              succOrderList.push.apply(succOrderList, _toConsumableArray(list || []));
              failOrderIds.push.apply(failOrderIds, _toConsumableArray(missingOrderIds || []));
            } else {
              failOrderIds.push.apply(failOrderIds, _toConsumableArray(ids));
              lastErrorMsg = msg;
            }

          case 24:
            _i3++;
            _context8.next = 10;
            break;

          case 27:
            if (succOrderList.length) {
              _context8.next = 30;
              break;
            }

            task.status = 14;
            return _context8.abrupt("return", {
              code: 2,
              msg: lastErrorMsg || "\u672A\u83B7\u53D6\u5230\u8BA2\u5355\u4F9B\u8D27\u4EF7\u6570\u636E,\u9700\u8981\u83B7\u53D6\u7684\u8BA2\u5355\u53F7:".concat(orderIds.join(','))
            });

          case 30:
            if (!failOrderIds.length) {
              _context8.next = 33;
              break;
            }

            task.failOrderIds = _toConsumableArray(new Set(failOrderIds));
            return _context8.abrupt("return", {
              code: 4,
              msg: '部分订单供货价获取失败',
              result: succOrderList,
              data: {
                failOrderIds: task.failOrderIds,
                order_ids: task.order_ids || task.orderIds || orderIds
              }
            });

          case 33:
            task.failOrderIds = [];
            return _context8.abrupt("return", {
              code: 0,
              msg: '获取完毕',
              result: succOrderList
            });

          case 35:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee7);
  }));

  return function getLocalSupplierPriceByOrder(_x11) {
    return _ref8.apply(this, arguments);
  };
}();

var handleGetSupplierPriceByOrder = /*#__PURE__*/function () {
  var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(task) {
    var res, _res, msg;

    return _regeneratorRuntime().wrap(function _callee8$(_context9) {
      while (1) {
        switch (_context9.prev = _context9.next) {
          case 0:
            _context9.prev = 0;

            if (!(task.resCache && task.resCache.code === 0)) {
              _context9.next = 3;
              break;
            }

            return _context9.abrupt("return", task.resCache);

          case 3:
            _context9.t0 = +task.type_id;
            _context9.next = _context9.t0 === 22002 ? 6 : _context9.t0 === 22011 ? 12 : 18;
            break;

          case 6:
            _context9.next = 8;
            return getCbSupplierPriceByOrder(task);

          case 8:
            res = _context9.sent;
            task.status = [1, 2].includes(res.code) ? 14 : 15;
            task.msg = res.msg;
            return _context9.abrupt("return", res);

          case 12:
            _context9.next = 14;
            return getLocalSupplierPriceByOrder(task);

          case 14:
            _res = _context9.sent;
            task.status = [1, 2].includes(_res.code) ? 14 : 15;
            task.msg = _res.msg;
            return _context9.abrupt("return", _res);

          case 18:
            msg = "\u6682\u4E0D\u652F\u6301\u7684\u8BA2\u5355\u4F9B\u8D27\u4EF7\u4EFB\u52A1\u7C7B\u578B\uFF1A".concat(task.type_id);
            task.status = 14;
            task.msg = msg;
            return _context9.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 22:
            _context9.next = 30;
            break;

          case 24:
            _context9.prev = 24;
            _context9.t1 = _context9["catch"](0);
            log["a" /* default */].setLog("handleGetSupplierPriceByOrder error: ".concat(Object(util["u" /* isError */])(_context9.t1)));
            task.status = 14;
            task.msg = "\u6839\u636E\u8BA2\u5355\u53F7\u83B7\u53D6\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A".concat(Object(util["u" /* isError */])(_context9.t1));
            return _context9.abrupt("return", {
              code: 2,
              msg: task.msg
            });

          case 30:
          case "end":
            return _context9.stop();
        }
      }
    }, _callee8, null, [[0, 24]]);
  }));

  return function handleGetSupplierPriceByOrder(_x12) {
    return _ref9.apply(this, arguments);
  };
}();
// CONCATENATED MODULE: ./src/platform/temu/getSupplierPrice.js
function getSupplierPrice_typeof(obj) { "@babel/helpers - typeof"; return getSupplierPrice_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; }, getSupplierPrice_typeof(obj); }

function getSupplierPrice_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getSupplierPrice_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" == getSupplierPrice_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 getSupplierPrice_toConsumableArray(arr) { return getSupplierPrice_arrayWithoutHoles(arr) || getSupplierPrice_iterableToArray(arr) || getSupplierPrice_unsupportedIterableToArray(arr) || getSupplierPrice_nonIterableSpread(); }

function getSupplierPrice_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getSupplierPrice_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getSupplierPrice_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 getSupplierPrice_arrayLikeToArray(o, minLen); }

function getSupplierPrice_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getSupplierPrice_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getSupplierPrice_arrayLikeToArray(arr); }

function getSupplierPrice_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; }

function getSupplierPrice_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getSupplierPrice_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getSupplierPrice_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getSupplierPrice_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }




 // 获取本土供货价

var getLocalSupplierPrice = /*#__PURE__*/function () {
  var _ref = getSupplierPrice_asyncToGenerator( /*#__PURE__*/getSupplierPrice_regeneratorRuntime().mark(function _callee2(task, skuIds) {
    var retry,
        changeStoreId,
        _yield$nativeRequest,
        success,
        error_code,
        result,
        succ,
        fail,
        skuIdSet,
        msg,
        _msg,
        _args2 = arguments;

    return getSupplierPrice_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            retry = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : 0;
            _context2.prev = 1;
            changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            _context2.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/marigold/goods/v2/search#LINGXING"), 'post', {
              page_size: 100,
              page_no: 1,
              order_type: 0,
              order_field: "gmt_create",
              enable_batch_search_text: true,
              goods_search_type: 1,
              search_text: skuIds.join(',')
            });

          case 5:
            _yield$nativeRequest = _context2.sent;
            success = _yield$nativeRequest.success;
            error_code = _yield$nativeRequest.error_code;
            result = _yield$nativeRequest.result;

            if (!(success && result && result.goods_list)) {
              _context2.next = 18;
              break;
            }

            succ = [];
            fail = [];
            skuIdSet = new Set((skuIds || []).map(String));
            _context2.next = 15;
            return Promise.all(result.goods_list.map( /*#__PURE__*/function () {
              var _ref3 = getSupplierPrice_asyncToGenerator( /*#__PURE__*/getSupplierPrice_regeneratorRuntime().mark(function _callee(_ref2) {
                var supplier_price, sku_id_list, commit_id, goods_id, currency, crt_time, variant;
                return getSupplierPrice_regeneratorRuntime().wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        supplier_price = _ref2.supplier_price, sku_id_list = _ref2.sku_id_list, commit_id = _ref2.commit_id, goods_id = _ref2.goods_id, currency = _ref2.currency, crt_time = _ref2.crt_time;

                        if (!supplier_price) {
                          _context.next = 5;
                          break;
                        }

                        succ.push({
                          productSkuId: sku_id_list[0],
                          supplierPrice: supplier_price,
                          currency: currency,
                          crtTime: crt_time
                        });
                        _context.next = 9;
                        break;

                      case 5:
                        _context.next = 7;
                        return getLocalVariantSupplierPrice({
                          commit_id: commit_id,
                          goods_id: goods_id,
                          host: task.host,
                          changeStoreId: changeStoreId,
                          task: task
                        });

                      case 7:
                        variant = _context.sent;

                        if (variant.code === 0) {
                          succ.push.apply(succ, getSupplierPrice_toConsumableArray(variant.result));
                        } else {
                          // 获取失败时，因为不知道是任务下发的是哪个skuid，所以得找一下
                          sku_id_list.forEach(function (sku_id) {
                            if (skuIdSet.has(String(sku_id))) fail.push(sku_id);
                          });
                        }

                      case 9:
                      case "end":
                        return _context.stop();
                    }
                  }
                }, _callee);
              }));

              return function (_x3) {
                return _ref3.apply(this, arguments);
              };
            }()));

          case 15:
            return _context2.abrupt("return", {
              code: 0,
              succ: succ,
              fail: fail
            });

          case 18:
            msg = "\u83B7\u53D6\u672C\u571F\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(result), "-----error_code: ").concat(error_code);
            log["a" /* default */].setLog(msg);
            return _context2.abrupt("return", {
              msg: msg,
              code: 2
            });

          case 21:
            _context2.next = 33;
            break;

          case 23:
            _context2.prev = 23;
            _context2.t0 = _context2["catch"](1);
            _msg = "\u83B7\u53D6\u672C\u571F\u4F9B\u8D27\u4EF7\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(_msg); // 重试三次

            if (!(retry < 3)) {
              _context2.next = 32;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context2.next = 31;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 31:
            return _context2.abrupt("return", getLocalSupplierPrice(task, skuIds, ++retry));

          case 32:
            return _context2.abrupt("return", {
              msg: _msg,
              code: 2
            });

          case 33:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 23]]);
  }));

  return function getLocalSupplierPrice(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}(); // 获取本土变体供货价


var getLocalVariantSupplierPrice = /*#__PURE__*/function () {
  var _ref5 = getSupplierPrice_asyncToGenerator( /*#__PURE__*/getSupplierPrice_regeneratorRuntime().mark(function _callee3(_ref4) {
    var commit_id,
        goods_id,
        host,
        changeStoreId,
        task,
        retry,
        taskId,
        _yield$nativeRequest2,
        result,
        success,
        error_code,
        msg,
        _msg2,
        _args3 = arguments;

    return getSupplierPrice_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            commit_id = _ref4.commit_id, goods_id = _ref4.goods_id, host = _ref4.host, changeStoreId = _ref4.changeStoreId, task = _ref4.task;
            retry = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : 0;
            taskId = task.task_id;
            _context3.prev = 3;
            _context3.next = 6;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/mms/marigold/sku/query#LINGXING"), 'POST', {
              commit_id: commit_id,
              goods_id: goods_id,
              source_type_of_sku_query: 1
            });

          case 6:
            _yield$nativeRequest2 = _context3.sent;
            result = _yield$nativeRequest2.result;
            success = _yield$nativeRequest2.success;
            error_code = _yield$nativeRequest2.error_code;

            if (!(success && result.sku_list && result.sku_list.length)) {
              _context3.next = 14;
              break;
            }

            return _context3.abrupt("return", {
              code: 0,
              result: result.sku_list.map(function (_ref6) {
                var sku_id = _ref6.sku_id,
                    supplier_price = _ref6.supplier_price,
                    currency = _ref6.currency,
                    crt_time = _ref6.crt_time;
                return {
                  productSkuId: sku_id,
                  supplierPrice: supplier_price,
                  currency: currency,
                  crtTime: crt_time
                };
              })
            });

          case 14:
            msg = "\u83B7\u53D6\u672C\u571F\u53D8\u4F53\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(error_code, ",result----").concat(JSON.stringify(result));
            log["a" /* default */].report(msg, 'except', {
              goods_id: goods_id,
              taskId: taskId
            });
            return _context3.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 17:
            _context3.next = 29;
            break;

          case 19:
            _context3.prev = 19;
            _context3.t0 = _context3["catch"](3);
            _msg2 = "\u83B7\u53D6\u672C\u571F\u53D8\u4F53\u4F9B\u8D27\u4EF7\u8BF7\u6C42\u5931\u8D25----".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].report(_msg2, 'except', {
              goods_id: goods_id,
              taskId: taskId
            }); // 重试三次

            if (!(retry < 3)) {
              _context3.next = 28;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context3.next = 27;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 27:
            return _context3.abrupt("return", getLocalVariantSupplierPrice({
              commit_id: commit_id,
              goods_id: goods_id,
              host: host,
              changeStoreId: changeStoreId,
              taskId: taskId
            }, ++retry));

          case 28:
            return _context3.abrupt("return", {
              code: 1,
              msg: _msg2
            });

          case 29:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[3, 19]]);
  }));

  return function getLocalVariantSupplierPrice(_x4) {
    return _ref5.apply(this, arguments);
  };
}(); // 获取跨境供货价


var getCbSupplierPrice = /*#__PURE__*/function () {
  var _ref7 = getSupplierPrice_asyncToGenerator( /*#__PURE__*/getSupplierPrice_regeneratorRuntime().mark(function _callee4(task, skuIds) {
    var retry,
        _yield$nativeRequest3,
        success,
        errorMsg,
        result,
        msg,
        _msg3,
        _args4 = arguments;

    return getSupplierPrice_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            retry = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : 0;
            _context4.prev = 1;
            _context4.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/visage-agent-seller/product/skc/pageQuery"), // host需要改为 cbGLOBALhost
            'post', {
              productSkuIds: skuIds,
              page: 1,
              pageSize: 200
            }, {
              Mallid: task.real_mall_id
            });

          case 4:
            _yield$nativeRequest3 = _context4.sent;
            success = _yield$nativeRequest3.success;
            errorMsg = _yield$nativeRequest3.errorMsg;
            result = _yield$nativeRequest3.result;

            if (!(success && result && result.pageItems)) {
              _context4.next = 12;
              break;
            }

            return _context4.abrupt("return", {
              code: 0,
              succ: result.pageItems.reduce(function (arr, _ref8) {
                var productSkuSummaries = _ref8.productSkuSummaries,
                    createdAt = _ref8.createdAt;
                return arr.concat(productSkuSummaries.map(function (_ref9) {
                  var productSkuId = _ref9.productSkuId,
                      supplierPrice = _ref9.supplierPrice,
                      currencyType = _ref9.currencyType,
                      siteSupplierPrices = _ref9.siteSupplierPrices;
                  return {
                    productSkuId: productSkuId,
                    supplierPrice: supplierPrice,
                    siteSupplierPrices: siteSupplierPrices,
                    crtTime: createdAt,
                    currency: currencyType
                  };
                }));
              }, [])
            });

          case 12:
            msg = "\u83B7\u53D6\u8DE8\u5883\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errorMsg);
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              msg: msg,
              code: 2
            });

          case 15:
            _context4.next = 27;
            break;

          case 17:
            _context4.prev = 17;
            _context4.t0 = _context4["catch"](1);
            _msg3 = "\u83B7\u53D6\u8DE8\u5883\u4F9B\u8D27\u4EF7\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(_msg3); // 重试三次

            if (!(retry < 3)) {
              _context4.next = 26;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context4.next = 25;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 25:
            return _context4.abrupt("return", getCbSupplierPrice(task, skuIds, ++retry));

          case 26:
            return _context4.abrupt("return", {
              msg: _msg3,
              code: 2
            });

          case 27:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[1, 17]]);
  }));

  return function getCbSupplierPrice(_x5, _x6) {
    return _ref7.apply(this, arguments);
  };
}();

var getSupplierPrice = /*#__PURE__*/function () {
  var _ref10 = getSupplierPrice_asyncToGenerator( /*#__PURE__*/getSupplierPrice_regeneratorRuntime().mark(function _callee5(task) {
    var num, handle, _res, skuIds, failSkuIds, succSkuIds, msg, res, count, batchSkuIds, i, ids, _yield$handle, code, errormMsg, fail, succ;

    return getSupplierPrice_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            // 获取单次请求skuid数量&不同类型方法
            if (+task.platform_code === 10022) {
              num = 200;
              handle = getCbSupplierPrice;
            } else {
              _res = {
                'GLOBAL': {
                  num: 200,
                  handle: getCbSupplierPrice
                },
                'LOCAL': {
                  num: 100,
                  handle: getLocalSupplierPrice
                }
              }[task.store_type];
              num = _res.num;
              handle = _res.handle;
            }

            skuIds = task.failSkuIds || task.skuIds || [];
            failSkuIds = [];
            succSkuIds = [];
            res = {
              code: 0,
              msg: ''
            };
            count = Math.ceil(skuIds.length / num);
            batchSkuIds = Array(count).fill(1).map(function (i, key) {
              return skuIds.slice(key * 200, (key + 1) * 200);
            }); // 分批遍历获取，一次性拿完后再上报

            i = 0;

          case 8:
            if (!(i < batchSkuIds.length)) {
              _context5.next = 23;
              break;
            }

            ids = batchSkuIds[i]; // 等待5s

            _context5.next = 12;
            return Object(util["h" /* delayed */])(5);

          case 12:
            _context5.next = 14;
            return handle(task, ids);

          case 14:
            _yield$handle = _context5.sent;
            code = _yield$handle.code;
            errormMsg = _yield$handle.errormMsg;
            fail = _yield$handle.fail;
            succ = _yield$handle.succ;

            if (code === 0) {
              // 执行前记录当前已获取数据
              task.currentNum = (i + 1) * 200;
              task.total = skuIds.length;
              succSkuIds.push.apply(succSkuIds, getSupplierPrice_toConsumableArray(succ || []));
            } else {
              failSkuIds.push.apply(failSkuIds, getSupplierPrice_toConsumableArray(fail || ids)); // 错误消息的话就取最后一个就行，一搬有报错都是一样的报错

              msg = errormMsg;
            }

          case 20:
            i++;
            _context5.next = 8;
            break;

          case 23:
            if (!succSkuIds.length) {
              _context5.next = 27;
              break;
            }

            // 上报的数据
            res.result = succSkuIds;
            _context5.next = 31;
            break;

          case 27:
            // 一条都没获取到，上报异常
            res.code = 2;
            res.msg = "\u672A\u83B7\u53D6\u5230\u4EFB\u4F55\u6570\u636E,\u9700\u8981\u83B7\u53D6\u7684skuId:".concat(skuIds.join(','));
            task.status = 14;
            return _context5.abrupt("return", res);

          case 31:
            // 记录获取失败的skuid
            if (failSkuIds.length) {
              task.failSkuIds = failSkuIds;
              res.code = 4;
              res.data = {
                failSkuIds: failSkuIds,
                skuIds: task.skuIds
              };
              res.msg = msg;
            } else {
              res.msg = '获取完毕';
            }

            return _context5.abrupt("return", res);

          case 33:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getSupplierPrice(_x7) {
    return _ref10.apply(this, arguments);
  };
}();

var handleGetSupplierPrice = /*#__PURE__*/function () {
  var _ref11 = getSupplierPrice_asyncToGenerator( /*#__PURE__*/getSupplierPrice_regeneratorRuntime().mark(function _callee6(task) {
    var loginRes, msg, res;
    return getSupplierPrice_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;

            if (!isOrderSupplierPriceTask(task)) {
              _context6.next = 3;
              break;
            }

            return _context6.abrupt("return", handleGetSupplierPriceByOrder(task));

          case 3:
            if (!(task.resCache && task.resCache.code === 0)) {
              _context6.next = 5;
              break;
            }

            return _context6.abrupt("return", task.resCache);

          case 5:
            if (!(task.platform_code === 10022 || task.store_type === 'GLOBAL')) {
              _context6.next = 14;
              break;
            }

            _context6.next = 8;
            return Object(temu["g" /* loginCb */])(task);

          case 8:
            loginRes = _context6.sent;

            if (loginRes) {
              _context6.next = 14;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context6.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 14:
            _context6.next = 16;
            return getSupplierPrice(task);

          case 16:
            res = _context6.sent;
            task.status = [1, 2].indexOf(res.code) > -1 ? 14 : 15;
            task.msg = res.msg;
            return _context6.abrupt("return", res);

          case 22:
            _context6.prev = 22;
            _context6.t0 = _context6["catch"](0);
            log["a" /* default */].setLog("handleGetSupplierPrice error: ".concat(Object(util["u" /* isError */])(_context6.t0)));
            task.status = 14;
            task.msg = "\u83B7\u53D6\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A".concat(Object(util["u" /* isError */])(_context6.t0));
            return _context6.abrupt("return", {
              code: 2,
              msg: task.msg
            });

          case 28:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[0, 22]]);
  }));

  return function handleGetSupplierPrice(_x8) {
    return _ref11.apply(this, arguments);
  };
}();

/* harmony default export */ var temu_getSupplierPrice = (handleGetSupplierPrice);
// EXTERNAL MODULE: ./node_modules/moment/moment.js
var moment = __webpack_require__("c1df");
var moment_default = /*#__PURE__*/__webpack_require__.n(moment);

// EXTERNAL MODULE: ./src/platform/common/newTask.js
var common_newTask = __webpack_require__("5e61");

// CONCATENATED MODULE: ./src/platform/temu/getSaleVolume.js
function getSaleVolume_typeof(obj) { "@babel/helpers - typeof"; return getSaleVolume_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; }, getSaleVolume_typeof(obj); }

function getSaleVolume_toConsumableArray(arr) { return getSaleVolume_arrayWithoutHoles(arr) || getSaleVolume_iterableToArray(arr) || getSaleVolume_unsupportedIterableToArray(arr) || getSaleVolume_nonIterableSpread(); }

function getSaleVolume_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getSaleVolume_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getSaleVolume_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 getSaleVolume_arrayLikeToArray(o, minLen); }

function getSaleVolume_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getSaleVolume_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getSaleVolume_arrayLikeToArray(arr); }

function getSaleVolume_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; }

function getSaleVolume_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getSaleVolume_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" == getSaleVolume_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 getSaleVolume_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getSaleVolume_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getSaleVolume_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getSaleVolume_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





 // 获取销量列表的页数

var $count = 40;
/**
 * @description 获取近三十天销量
 * @param {*} task
 * @returns res object  code: 0: 成功 1:失败 2：异常 5：无销量
 */

var requestSaleVolumeBySkuId = /*#__PURE__*/function () {
  var _ref = getSaleVolume_asyncToGenerator( /*#__PURE__*/getSaleVolume_regeneratorRuntime().mark(function _callee(task, skuIds, retry) {
    var curDate, endDate, startDate, _yield$nativeRequest, success, errorMsg, result, msg, _msg, _msg2;

    return getSaleVolume_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["t" /* getServiceTime */])();

          case 3:
            curDate = _context.sent;
            endDate = moment_default()(curDate).format('YYYY-MM-DD');
            startDate = moment_default()(curDate).subtract(30, 'days').format('YYYY-MM-DD');
            _context.next = 8;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/venom/api/supplier/sales/management/querySkuSalesNumber"), // host需要改为 cbGlobalHost
            'post', {
              productSkuIds: skuIds,
              startDate: startDate,
              endDate: endDate
            }, {
              Mallid: task.real_mall_id
            });

          case 8:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            result = _yield$nativeRequest.result;

            if (!(success && result)) {
              _context.next = 22;
              break;
            }

            if (!result.length) {
              _context.next = 17;
              break;
            }

            return _context.abrupt("return", {
              code: 0,
              result: result
            });

          case 17:
            msg = "".concat(skuIds.splice(0, 3).join(','), "\u7B49skuid\u65E0\u9500\u91CF");
            log["a" /* default */].setLog(msg);
            return _context.abrupt("return", {
              msg: msg,
              code: 5
            });

          case 20:
            _context.next = 25;
            break;

          case 22:
            _msg = "\u83B7\u53D6\u5168\u6258\u7BA1\u9500\u91CF\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].setLog(_msg);
            return _context.abrupt("return", {
              msg: _msg,
              code: 1
            });

          case 25:
            _context.next = 37;
            break;

          case 27:
            _context.prev = 27;
            _context.t0 = _context["catch"](0);
            _msg2 = "\u83B7\u53D6\u8FD1\u4E09\u5341\u5929\u9500\u91CF\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context.t0));
            log["a" /* default */].setLog(_msg2); // 重试三次

            if (!(retry < 3)) {
              _context.next = 36;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context.next = 35;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 35:
            return _context.abrupt("return", requestSaleVolumeBySkuId(task, skuIds, ++retry));

          case 36:
            return _context.abrupt("return", {
              msg: _msg2,
              code: 2
            });

          case 37:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 27]]);
  }));

  return function requestSaleVolumeBySkuId(_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}();
/**
 * @description 获取全托管近三十天销量列表&供货价&供货价
 * @param {*} task
 * @returns
 */


var requestSkuid = /*#__PURE__*/function () {
  var _ref2 = getSaleVolume_asyncToGenerator( /*#__PURE__*/getSaleVolume_regeneratorRuntime().mark(function _callee2(task) {
    var pageNo,
        retry,
        _yield$nativeRequest2,
        success,
        errorMsg,
        result,
        subOrderList,
        info,
        total,
        msg,
        _msg3,
        _args2 = arguments;

    return getSaleVolume_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            pageNo = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 1;
            retry = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : 0;
            _context2.prev = 2;
            _context2.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/venom/api/supplier/sales/management/listWarehouse"), // host需要改为 cbGlobalHost
            'post', {
              pageNo: pageNo,
              pageSize: $count,
              isLack: 0,
              priceAdjustRecentDays: 7,
              thirtyDaysSaleVolumMin: 1,
              advancedSort: {
                firstOrderByDesc: 1,
                firstOrderByParam: 'lastThirtyDaysSaleVolume',
                secondOrderByDesc: 1,
                secondOrderByParam: 'lastThirtyDaysSaleVolume'
              }
            }, {
              Mallid: task.real_mall_id
            });

          case 5:
            _yield$nativeRequest2 = _context2.sent;
            success = _yield$nativeRequest2.success;
            errorMsg = _yield$nativeRequest2.errorMsg;
            result = _yield$nativeRequest2.result;

            if (!(success && result && result.subOrderList)) {
              _context2.next = 19;
              break;
            }

            subOrderList = result.subOrderList;
            info = [];
            total = result.total || 0;

            if (subOrderList.length) {
              _context2.next = 15;
              break;
            }

            return _context2.abrupt("return", {
              code: 0,
              msg: '获取完毕',
              info: info,
              total: total
            });

          case 15:
            // 收集skuid&供货价
            subOrderList.forEach(function (_ref3) {
              var skuQuantityDetailList = _ref3.skuQuantityDetailList;

              if (skuQuantityDetailList.length) {
                info.push.apply(info, getSaleVolume_toConsumableArray(skuQuantityDetailList.map(function (_ref4) {
                  var productSkuId = _ref4.productSkuId,
                      supplierPrice = _ref4.supplierPrice,
                      currencyType = _ref4.currencyType,
                      skuExtCode = _ref4.skuExtCode;
                  return {
                    productSkuId: productSkuId,
                    supplierPrice: supplierPrice,
                    currencyType: currencyType,
                    skuExtCode: skuExtCode
                  };
                })));
              }
            });
            return _context2.abrupt("return", {
              code: 0,
              info: info,
              total: total,
              pageNo: pageNo
            });

          case 19:
            msg = "\u83B7\u53D6\u5168\u6258\u7BA1\u8FD130\u5929\u9500\u91CF\u5217\u8868\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].setLog(msg);
            return _context2.abrupt("return", {
              msg: msg,
              pageNo: pageNo,
              code: 1
            });

          case 22:
            _context2.next = 34;
            break;

          case 24:
            _context2.prev = 24;
            _context2.t0 = _context2["catch"](2);
            _msg3 = "\u83B7\u53D6\u5168\u6258\u7BA1\u8FD1\u4E09\u5341\u5929\u9500\u91CF\u5217\u8868&\u4F9B\u8D27\u4EF7\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(_msg3); // 重试三次

            if (!(retry < 3)) {
              _context2.next = 33;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context2.next = 32;
            return Object(util["h" /* delayed */])(5 * 1000);

          case 32:
            return _context2.abrupt("return", requestSkuid(task, pageNo, ++retry));

          case 33:
            return _context2.abrupt("return", {
              msg: _msg3,
              pageNo: pageNo,
              code: 2
            });

          case 34:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[2, 24]]);
  }));

  return function requestSkuid(_x4) {
    return _ref2.apply(this, arguments);
  };
}();
/**
 * 获取全托管skuid&供货价 - 用户单独勾选sku获取销量时用到
 * @param {*} task
 * @param {*} retry
 * @returns
 */


var getSaleVolume_getCbSupplierPrice = /*#__PURE__*/function () {
  var _ref5 = getSaleVolume_asyncToGenerator( /*#__PURE__*/getSaleVolume_regeneratorRuntime().mark(function _callee3(task) {
    var retry,
        pageNo,
        _yield$nativeRequest3,
        success,
        errorMsg,
        result,
        skuIdSet,
        msg,
        _msg4,
        _args3 = arguments;

    return getSaleVolume_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            retry = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : 0;
            pageNo = task.pageNo || 1;
            _context3.prev = 2;
            _context3.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/visage-agent-seller/product/skc/pageQuery"), // host需要改为 cbGlobalHost
            'post', {
              productSkuIds: task.skuIds,
              page: pageNo,
              pageSize: $count
            }, {
              Mallid: task.real_mall_id
            });

          case 5:
            _yield$nativeRequest3 = _context3.sent;
            success = _yield$nativeRequest3.success;
            errorMsg = _yield$nativeRequest3.errorMsg;
            result = _yield$nativeRequest3.result;

            if (!(success && result && result.pageItems)) {
              _context3.next = 14;
              break;
            }

            skuIdSet = new Set((task.skuIds || []).map(String));
            return _context3.abrupt("return", {
              code: 0,
              info: result.pageItems.reduce(function (arr, _ref6) {
                var productSkuSummaries = _ref6.productSkuSummaries;
                return arr.concat(productSkuSummaries.filter(function (_ref7) {
                  var productSkuId = _ref7.productSkuId;
                  return skuIdSet.has(String(productSkuId));
                }).map(function (_ref8) {
                  var productSkuId = _ref8.productSkuId,
                      supplierPrice = _ref8.supplierPrice,
                      currencyType = _ref8.currencyType,
                      extCode = _ref8.extCode;
                  return {
                    productSkuId: productSkuId,
                    supplierPrice: supplierPrice,
                    currencyType: currencyType,
                    skuExtCode: extCode
                  };
                }));
              }, []),
              total: result.total,
              pageNo: pageNo
            });

          case 14:
            msg = "\u83B7\u53D6\u5168\u6258\u7BA1\u4F9B\u8D27\u4EF7\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errorMsg);
            log["a" /* default */].setLog(msg);
            return _context3.abrupt("return", {
              msg: msg,
              pageNo: pageNo,
              code: 1
            });

          case 17:
            _context3.next = 29;
            break;

          case 19:
            _context3.prev = 19;
            _context3.t0 = _context3["catch"](2);
            _msg4 = "\u83B7\u53D6\u5168\u6258\u7BA1skuid&\u4F9B\u8D27\u4EF7\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(_msg4); // 重试三次

            if (!(retry < 3)) {
              _context3.next = 28;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context3.next = 27;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 27:
            return _context3.abrupt("return", getSaleVolume_getCbSupplierPrice(task, ++retry));

          case 28:
            return _context3.abrupt("return", {
              msg: _msg4,
              pageNo: 1,
              code: 2
            });

          case 29:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[2, 19]]);
  }));

  return function getCbSupplierPrice(_x5) {
    return _ref5.apply(this, arguments);
  };
}();

var getAllSaleVolume = /*#__PURE__*/function () {
  var _ref9 = getSaleVolume_asyncToGenerator( /*#__PURE__*/getSaleVolume_regeneratorRuntime().mark(function _callee4(task) {
    var _ref10, code, msg, pageNo, info, total, count, batchSkuIds, saleList, i, saleVolumeList;

    return getSaleVolume_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            if (!(task.skuIds && task.skuIds.length)) {
              _context4.next = 6;
              break;
            }

            _context4.next = 3;
            return getSaleVolume_getCbSupplierPrice(task);

          case 3:
            _context4.t0 = _context4.sent;
            _context4.next = 9;
            break;

          case 6:
            _context4.next = 8;
            return requestSkuid(task, task.pageNo || 1);

          case 8:
            _context4.t0 = _context4.sent;

          case 9:
            _ref10 = _context4.t0;
            code = _ref10.code;
            msg = _ref10.msg;
            pageNo = _ref10.pageNo;
            info = _ref10.info;
            total = _ref10.total;
            // 记录当前页数
            task.pageNo = pageNo; // 获取失败，上报状态

            if (!(code !== 0)) {
              _context4.next = 18;
              break;
            }

            return _context4.abrupt("return", {
              code: 2,
              msg: msg,
              data: {
                pageNo: pageNo,
                skuIds: task.skuIds
              }
            });

          case 18:
            count = Math.ceil(info.length / 100);
            batchSkuIds = Array(count).fill(1).map(function (i, key) {
              return info.slice(key * 100, (key + 1) * 100);
            });
            saleList = []; // 批量获取，每次获取100个sku的销量（原因：傻逼temu不能同时获取超过100个sku的销量）

            i = 0;

          case 22:
            if (!(i < batchSkuIds.length)) {
              _context4.next = 35;
              break;
            }

            _context4.next = 25;
            return requestSaleVolumeBySkuId(task, batchSkuIds[i].map(function (_ref11) {
              var productSkuId = _ref11.productSkuId;
              return productSkuId;
            }));

          case 25:
            saleVolumeList = _context4.sent;

            if (!(saleVolumeList.code !== 0)) {
              _context4.next = 31;
              break;
            }

            if (!(saleVolumeList.code !== 5)) {
              _context4.next = 29;
              break;
            }

            return _context4.abrupt("return", {
              code: saleVolumeList.code,
              msg: saleVolumeList.msg + "----sku\u6570\u91CF: ".concat(info.length),
              data: {
                pageNo: pageNo,
                skuIds: task.skuIds
              }
            });

          case 29:
            _context4.next = 32;
            break;

          case 31:
            saleList.push.apply(saleList, getSaleVolume_toConsumableArray(saleVolumeList.result));

          case 32:
            i++;
            _context4.next = 22;
            break;

          case 35:
            if (!(saleList.length === 0)) {
              _context4.next = 37;
              break;
            }

            return _context4.abrupt("return", {
              code: 0,
              result: {
                total: total,
                supplierPriceList: info
              }
            });

          case 37:
            // 记录当前已获取数据，用于显示
            task.currentNum = (task.currentNum || 0) + info.length;
            task.total = total;
            task.curPage = pageNo * $count; // 判断是否获取完毕

            if (!(task.curPage < total)) {
              _context4.next = 45;
              break;
            }

            task.pageNo += 1; // 上报当前状态

            _context4.next = 44;
            return common_newTask["a" /* default */].uploadTask({
              code: 4,
              data: {
                pageNo: task.pageNo
              },
              result: {
                total: total,
                supplierPriceList: info,
                saleVolume: saleList
              }
            }, task);

          case 44:
            return _context4.abrupt("return", getAllSaleVolume(task));

          case 45:
            return _context4.abrupt("return", {
              code: 0,
              result: {
                total: total,
                supplierPriceList: info,
                saleVolume: saleList
              }
            });

          case 46:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function getAllSaleVolume(_x6) {
    return _ref9.apply(this, arguments);
  };
}();

var getSaleVolume = /*#__PURE__*/function () {
  var _ref12 = getSaleVolume_asyncToGenerator( /*#__PURE__*/getSaleVolume_regeneratorRuntime().mark(function _callee5(task) {
    var loginRes, msg, res;
    return getSaleVolume_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            if (!(task.resCache && task.resCache.code === 0)) {
              _context5.next = 2;
              break;
            }

            return _context5.abrupt("return", task.resCache);

          case 2:
            _context5.next = 4;
            return Object(temu["g" /* loginCb */])(task);

          case 4:
            loginRes = _context5.sent;

            if (loginRes) {
              _context5.next = 10;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context5.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 10:
            _context5.next = 12;
            return getAllSaleVolume(task);

          case 12:
            res = _context5.sent;
            task.status = [1, 2].indexOf(res.code) > -1 ? 14 : 15;
            task.msg = res.msg;
            return _context5.abrupt("return", res);

          case 16:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getSaleVolume(_x7) {
    return _ref12.apply(this, arguments);
  };
}();

/* harmony default export */ var temu_getSaleVolume = (getSaleVolume); // window.requestSaleVolumeBySkuId = () => {
//   requestSaleVolumeBySkuId({
//     host: 'https://seller.kuajingmaihuo.com',
//     skuIds: [
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118,
//       3092153307, 3269504539, 1851325013, 4010808419, 4582729262, 1857468159, 6711667118
//     ],
//     store_id: 65016470556
//   })
// }
// window.requestSkuid = () => {
//   requestSkuid({
//     host: 'https://seller.kuajingmaihuo.com',
//     store_id: 65016470556
//   })
// }
// EXTERNAL MODULE: ./node_modules/axios/index.js
var axios = __webpack_require__("bc3a");
var axios_default = /*#__PURE__*/__webpack_require__.n(axios);

// EXTERNAL MODULE: ./node_modules/jszip/dist/jszip.min.js
var jszip_min = __webpack_require__("c4e3");
var jszip_min_default = /*#__PURE__*/__webpack_require__.n(jszip_min);

// CONCATENATED MODULE: ./src/platform/temu/qtReport/getBillDetailsReport.js
function getBillDetailsReport_typeof(obj) { "@babel/helpers - typeof"; return getBillDetailsReport_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; }, getBillDetailsReport_typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getBillDetailsReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getBillDetailsReport_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" == getBillDetailsReport_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 getBillDetailsReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getBillDetailsReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getBillDetailsReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getBillDetailsReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }








var generateReport = /*#__PURE__*/function () {
  var _ref = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee(task) {
    var _yield$nativeRequest, success, errorCode, errorMsg, msg;

    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export"), 'post', {
              beginTime: task.report_custom_datetime_start,
              endTime: task.report_custom_datetime_end,
              fundDetailExport: true,
              taskType: 19
            }, {
              Mallid: task.real_mall_id
            });

          case 3:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorCode = _yield$nativeRequest.errorCode;
            errorMsg = _yield$nativeRequest.errorMsg;

            if (!success) {
              _context.next = 13;
              break;
            }

            log["a" /* default */].setLog('全托管财务明细报表生成成功');
            task.status = 6;
            return _context.abrupt("return", true);

          case 13:
            if (!(errorCode == 2000000)) {
              _context.next = 16;
              break;
            }

            task.status = 6;
            return _context.abrupt("return", true);

          case 16:
            if (!(errorCode == 3000000)) {
              _context.next = 18;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 18:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            task.status = 3;
            log["a" /* default */].setLog(msg);
            task.msg = msg;

          case 22:
            _context.next = 30;
            break;

          case 24:
            _context.prev = 24;
            _context.t0 = _context["catch"](0);
            task.status = 3;
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 30:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 24]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        find,
        _args2 = arguments;
    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/history/page"), 'post', {
              pageNum: 1,
              pageSize: 50,
              taskType: 19
            }, {
              Mallid: task.real_mall_id
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 35;
              break;
            }

            list = res.result.merchantMerchantFileExportHistoryList;
            find = list.find(function (item) {
              return item.fundDetailExport == true && item.searchExportTimeBegin == task.report_custom_datetime_start && item.searchExportTimeEnd == task.report_custom_datetime_end && item.createTime > Date.now() - 24 * 60 * 60 * 1000;
            });

            if (!find) {
              _context2.next = 31;
              break;
            }

            _context2.t0 = find.status;
            _context2.next = _context2.t0 === 2 ? 17 : _context2.t0 === 1 ? 22 : 22;
            break;

          case 17:
            task.status = 2;
            task.agentSellerExportParams = find.agentSellerExportParams;
            task.agentSellerExportSign = find.agentSellerExportSign;
            task.downloadId = find.id;
            return _context2.abrupt("return", true);

          case 22:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 26;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 26:
            _context2.next = 28;
            return awaitReportDownload(task, ++count);

          case 28:
            return _context2.abrupt("return", _context2.sent);

          case 29:
            _context2.next = 33;
            break;

          case 31:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25----not find\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 33:
            _context2.next = 37;
            break;

          case 35:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 37:
            _context2.next = 43;
            break;

          case 39:
            _context2.prev = 39;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 43:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 39]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取下载报表链接


var getCnReportUrl = /*#__PURE__*/function () {
  var _ref3 = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee3(task) {
    var res;
    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/download"), 'post', {
              id: task.downloadId,
              taskType: 19
            }, {
              Mallid: task.real_mall_id
            });

          case 3:
            res = _context3.sent;

            if (!(res.success && res.result)) {
              _context3.next = 9;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context3.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 9:
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(res.errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 12:
            _context3.next = 19;
            break;

          case 14:
            _context3.prev = 14;
            _context3.t0 = _context3["catch"](0);
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 19:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 14]]);
  }));

  return function getCnReportUrl(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 获取英文中心下载报表链接


var getEnReportUrl = /*#__PURE__*/function () {
  var _ref4 = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee4(task, host) {
    var backUp, loginRes, changeStoreId, _yield$nativeRequest2, success, result, errorMsg, msg;

    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            // 需要提前登录一下美区或者欧区
            backUp = _objectSpread(_objectSpread({}, task), {}, {
              host: host
            });
            _context4.next = 3;
            return Object(temu["g" /* loginCb */])(backUp);

          case 3:
            loginRes = _context4.sent;

            if (loginRes) {
              _context4.next = 9;
              break;
            }

            backUp.msg = '切换到美区、欧区或全球站点失败，请检查';
            backUp.status = 11;
            log["a" /* default */].setLog(backUp.msg);
            return _context4.abrupt("return", {
              code: 1,
              msg: backUp.msg
            });

          case 9:
            _context4.prev = 9;
            changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            _context4.next = 13;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export"), 'post', {
              params: task.agentSellerExportParams,
              sign: task.agentSellerExportSign,
              taskType: 31
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: changeStoreId
            });

          case 13:
            _yield$nativeRequest2 = _context4.sent;
            success = _yield$nativeRequest2.success;
            result = _yield$nativeRequest2.result;
            errorMsg = _yield$nativeRequest2.errorMsg;

            if (!(success && result)) {
              _context4.next = 23;
              break;
            }

            _context4.next = 20;
            return getEnReportUrlDownload(task, host, result);

          case 20:
            return _context4.abrupt("return", _context4.sent);

          case 23:
            msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            task.msg = msg;
            task.status = 9;
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              msg: msg,
              code: 1
            });

          case 28:
            _context4.next = 36;
            break;

          case 30:
            _context4.prev = 30;
            _context4.t0 = _context4["catch"](9);
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            task.status = 9;
            log["a" /* default */].setLog(task.msg);
            return _context4.abrupt("return", false);

          case 36:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[9, 30]]);
  }));

  return function getEnReportUrl(_x4, _x5) {
    return _ref4.apply(this, arguments);
  };
}();

var getEnReportUrlDownload = /*#__PURE__*/function () {
  var _ref5 = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee5(task, host, result) {
    var count,
        changeStoreId,
        res,
        _args5 = arguments;
    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            count = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : 0;

            if (!(count >= 5)) {
              _context5.next = 6;
              break;
            }

            task.msg = '获取下载报表链接失败，超过最大重试次数';
            task.status = 9;
            log["a" /* default */].setLog(task.msg);
            return _context5.abrupt("return", false);

          case 6:
            changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            _context5.prev = 7;
            _context5.next = 10;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export/download"), 'post', {
              id: result,
              taskType: 31
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: changeStoreId
            });

          case 10:
            res = _context5.sent;

            if (!(res.success && res.result)) {
              _context5.next = 16;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context5.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 16:
            // 这里失败可能是文件还未生成好（中文中心生成好了但是可能英文中心没生成好。。。）
            task.msg = res.errorMsg;
            task.status = 6;
            log["a" /* default */].setLog(task.msg, "---\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context5.next = 21;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 21:
            _context5.next = 23;
            return getEnReportUrlDownload(task, host, result, ++count);

          case 23:
            return _context5.abrupt("return", _context5.sent);

          case 24:
            _context5.next = 32;
            break;

          case 26:
            _context5.prev = 26;
            _context5.t0 = _context5["catch"](7);
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context5.t0, task));
            task.status = 9;
            log["a" /* default */].setLog(task.msg);
            return _context5.abrupt("return", false);

          case 32:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[7, 26]]);
  }));

  return function getEnReportUrlDownload(_x6, _x7, _x8) {
    return _ref5.apply(this, arguments);
  };
}(); // 下载报表


var downloadReport = /*#__PURE__*/function () {
  var _ref6 = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee6(task) {
    var res, name, oFile, fileRes, zip;
    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;
            _context6.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context6.sent;

            if (!(res && res.data)) {
              _context6.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context6.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context6.abrupt("return", fileRes);

          case 16:
            _context6.next = 23;
            break;

          case 18:
            _context6.prev = 18;
            _context6.t0 = _context6["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context6.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[0, 18]]);
  }));

  return function downloadReport(_x9) {
    return _ref6.apply(this, arguments);
  };
}();

var getBillDetailsReport = /*#__PURE__*/function () {
  var _ref7 = getBillDetailsReport_asyncToGenerator( /*#__PURE__*/getBillDetailsReport_regeneratorRuntime().mark(function _callee7(task) {
    var generateReportRes, host, param, res, uploadRes;
    return getBillDetailsReport_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            _context7.t0 = task.status !== 6;

            if (!_context7.t0) {
              _context7.next = 5;
              break;
            }

            _context7.next = 4;
            return awaitReportDownload(task);

          case 4:
            _context7.t0 = !_context7.sent;

          case 5:
            if (!_context7.t0) {
              _context7.next = 14;
              break;
            }

            _context7.next = 8;
            return generateReport(task);

          case 8:
            generateReportRes = _context7.sent;

            if (generateReportRes) {
              _context7.next = 11;
              break;
            }

            return _context7.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 11:
            if (!(generateReportRes == 'needSplit')) {
              _context7.next = 14;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context7.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 14:
            _context7.t1 = task.status !== 2;

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

            _context7.next = 18;
            return awaitReportDownload(task);

          case 18:
            _context7.t1 = !_context7.sent;

          case 19:
            if (!_context7.t1) {
              _context7.next = 21;
              break;
            }

            return _context7.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 21:
            if (!(task.report_type == 51)) {
              _context7.next = 28;
              break;
            }

            _context7.next = 24;
            return getCnReportUrl(task);

          case 24:
            if (_context7.sent) {
              _context7.next = 26;
              break;
            }

            return _context7.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 26:
            _context7.next = 33;
            break;

          case 28:
            host = {
              5: temu["h" /* temu */].cbGlobalHost,
              502: temu["h" /* temu */].cbEuHost,
              503: temu["h" /* temu */].cbUsHost
            }[task.report_type]; // 监听header头修改cookie
            // await changeLocalMallId(task.platform_store_id, task.siteId, host)

            _context7.next = 31;
            return getEnReportUrl(task, host);

          case 31:
            if (_context7.sent) {
              _context7.next = 33;
              break;
            }

            return _context7.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 33:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context7.next = 36;
            return downloadReport(task);

          case 36:
            res = _context7.sent;

            if (!(res && res.file)) {
              _context7.next = 47;
              break;
            }

            _context7.next = 40;
            return Object(util["L" /* uploadFile */])(res.file);

          case 40:
            uploadRes = _context7.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context7.next = 44;
              break;
            }

            return _context7.abrupt("return", _objectSpread(_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 44:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 47:
            return _context7.abrupt("return", _objectSpread(_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 48:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7);
  }));

  return function getBillDetailsReport(_x10) {
    return _ref7.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getBillDetailsReport = (getBillDetailsReport);
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getDeductionReportExportDetail.js
function getDeductionReportExportDetail_typeof(obj) { "@babel/helpers - typeof"; return getDeductionReportExportDetail_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; }, getDeductionReportExportDetail_typeof(obj); }

function getDeductionReportExportDetail_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getDeductionReportExportDetail_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getDeductionReportExportDetail_ownKeys(Object(source), !0).forEach(function (key) { getDeductionReportExportDetail_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getDeductionReportExportDetail_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getDeductionReportExportDetail_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getDeductionReportExportDetail_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getDeductionReportExportDetail_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" == getDeductionReportExportDetail_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 getDeductionReportExportDetail_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getDeductionReportExportDetail_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getDeductionReportExportDetail_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getDeductionReportExportDetail_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }




var remarkMap = {
  52: '消费者及履约保障-售后问题',
  521: '仓储增值服务-贴标费'
}; // 获取账务明细列表

var getAccountingDetailsList = /*#__PURE__*/function () {
  var _ref = getDeductionReportExportDetail_asyncToGenerator( /*#__PURE__*/getDeductionReportExportDetail_regeneratorRuntime().mark(function _callee(task) {
    var list,
        pageNum,
        res,
        _args = arguments;
    return getDeductionReportExportDetail_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            list = _args.length > 1 && _args[1] !== undefined ? _args[1] : [];
            pageNum = _args.length > 2 && _args[2] !== undefined ? _args[2] : 1;
            _context.prev = 2;
            _context.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/fund/detail/pageSearch"), 'post', {
              beginTime: task.report_custom_datetime_start,
              endTime: task.report_custom_datetime_end,
              pageNum: pageNum,
              pageSize: 100
            }, {
              Mallid: task.real_mall_id
            });

          case 5:
            res = _context.sent;

            if (!(res.success && res.result && res.result.resultList)) {
              _context.next = 15;
              break;
            }

            list = list.concat(res.result.resultList.filter(function (_ref2) {
              var remark = _ref2.remark;
              return remarkMap[task.report_type] === remark;
            })); // 判断是否获取完毕

            if (!(res.result.total > pageNum * 100)) {
              _context.next = 12;
              break;
            }

            _context.next = 11;
            return getAccountingDetailsList(task, list, pageNum++);

          case 11:
            return _context.abrupt("return", _context.sent);

          case 12:
            return _context.abrupt("return", list);

          case 15:
            task.msg = "\u8BF7\u6C42\u5217\u8868\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----code:".concat(res.errorCode, "--msg:").concat(res.errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 17:
            _context.next = 23;
            break;

          case 19:
            _context.prev = 19;
            _context.t0 = _context["catch"](2);
            task.msg = "\u8BF7\u6C42\u5217\u8868\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[2, 19]]);
  }));

  return function getAccountingDetailsList(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 获取账务明细详情，返回值是个数组


var getAccountingDetailsItem = /*#__PURE__*/function () {
  var _ref4 = getDeductionReportExportDetail_asyncToGenerator( /*#__PURE__*/getDeductionReportExportDetail_regeneratorRuntime().mark(function _callee2(task, _ref3) {
    var batchId, createTime, fundType, res;
    return getDeductionReportExportDetail_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            batchId = _ref3.batchId, createTime = _ref3.createTime, fundType = _ref3.fundType;
            _context2.prev = 1;
            _context2.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/fund/detail/item"), 'post', {
              batchId: batchId,
              createdTime: createTime,
              fundType: fundType
            }, {
              Mallid: task.real_mall_id
            });

          case 4:
            res = _context2.sent;

            if (!(res.success && res.result)) {
              _context2.next = 9;
              break;
            }

            return _context2.abrupt("return", res.result.map(function (item) {
              return getDeductionReportExportDetail_objectSpread({
                batchId: batchId,
                createTime: createTime
              }, item);
            }));

          case 9:
            task.msg = "\u8BF7\u6C42\u8BE6\u60C5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----code:".concat(res.errorCode, "--msg:").concat(res.errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 11:
            _context2.next = 17;
            break;

          case 13:
            _context2.prev = 13;
            _context2.t0 = _context2["catch"](1);
            task.msg = "\u8BF7\u6C42\u8BE6\u60C5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(task.msg);

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

  return function getAccountingDetailsItem(_x2, _x3) {
    return _ref4.apply(this, arguments);
  };
}(); // 获取导出链接


var getFileUrl = /*#__PURE__*/function () {
  var _ref5 = getDeductionReportExportDetail_asyncToGenerator( /*#__PURE__*/getDeductionReportExportDetail_regeneratorRuntime().mark(function _callee3(task, item) {
    var res;
    return getDeductionReportExportDetail_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/fund/detail/item/download/detail"), 'post', item, {
              Mallid: task.real_mall_id
            });

          case 3:
            res = _context3.sent;

            if (!(res.success && res.result)) {
              _context3.next = 8;
              break;
            }

            return _context3.abrupt("return", res.result.fileUrl);

          case 8:
            task.msg = "\u8BF7\u6C42\u5BFC\u51FA\u6570\u636E\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----code:".concat(res.errorCode, "--msg:").concat(res.errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 10:
            _context3.next = 16;
            break;

          case 12:
            _context3.prev = 12;
            _context3.t0 = _context3["catch"](0);
            task.msg = "\u8BF7\u6C42\u5BFC\u51FA\u6570\u636E\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 16:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 12]]);
  }));

  return function getFileUrl(_x4, _x5) {
    return _ref5.apply(this, arguments);
  };
}(); // 下载报表


var getDeductionReportExportDetail_downloadReport = /*#__PURE__*/function () {
  var _ref6 = getDeductionReportExportDetail_asyncToGenerator( /*#__PURE__*/getDeductionReportExportDetail_regeneratorRuntime().mark(function _callee4(task, url) {
    var res, name, oFile;
    return getDeductionReportExportDetail_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios_default()({
              method: 'GET',
              url: url,
              responseType: 'blob'
            });

          case 3:
            res = _context4.sent;

            if (!(res && res.data)) {
              _context4.next = 8;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(url);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            return _context4.abrupt("return", {
              oFile: oFile,
              name: name,
              blob: res.data
            });

          case 8:
            _context4.next = 15;
            break;

          case 10:
            _context4.prev = 10;
            _context4.t0 = _context4["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u62A5\u8868\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 15:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 10]]);
  }));

  return function downloadReport(_x6, _x7) {
    return _ref6.apply(this, arguments);
  };
}();

function getDeductionReportExportDetail(_x8) {
  return _getDeductionReportExportDetail.apply(this, arguments);
}

function _getDeductionReportExportDetail() {
  _getDeductionReportExportDetail = getDeductionReportExportDetail_asyncToGenerator( /*#__PURE__*/getDeductionReportExportDetail_regeneratorRuntime().mark(function _callee5(task) {
    var accountingDetailsList, items, fileUrls, files;
    return getDeductionReportExportDetail_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.next = 2;
            return getAccountingDetailsList(task);

          case 2:
            accountingDetailsList = _context5.sent;

            if (accountingDetailsList) {
              _context5.next = 5;
              break;
            }

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

          case 5:
            if (!(accountingDetailsList.length === 0)) {
              _context5.next = 7;
              break;
            }

            return _context5.abrupt("return", 'none');

          case 7:
            _context5.next = 9;
            return Promise.all(accountingDetailsList.map(function (item) {
              return getAccountingDetailsItem(task, item);
            })).catch(function () {
              return false;
            });

          case 9:
            items = _context5.sent;

            if (items) {
              _context5.next = 12;
              break;
            }

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

          case 12:
            _context5.next = 14;
            return Promise.all(items.flat().map(function (item) {
              return getFileUrl(task, item);
            })).catch(function () {
              return false;
            });

          case 14:
            fileUrls = _context5.sent;

            if (fileUrls) {
              _context5.next = 17;
              break;
            }

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

          case 17:
            _context5.next = 19;
            return Promise.all(fileUrls.map(function (url) {
              return getDeductionReportExportDetail_downloadReport(task, url);
            })).catch(function () {
              return false;
            });

          case 19:
            files = _context5.sent;

            if (files) {
              _context5.next = 22;
              break;
            }

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

          case 22:
            return _context5.abrupt("return", files);

          case 23:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));
  return _getDeductionReportExportDetail.apply(this, arguments);
}
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getDeductionReport.js
function getDeductionReport_typeof(obj) { "@babel/helpers - typeof"; return getDeductionReport_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; }, getDeductionReport_typeof(obj); }

function getDeductionReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getDeductionReport_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" == getDeductionReport_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 getDeductionReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getDeductionReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getDeductionReport_ownKeys(Object(source), !0).forEach(function (key) { getDeductionReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getDeductionReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getDeductionReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getDeductionReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getDeductionReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getDeductionReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getDeductionReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }






var deductionType = {
  53: 'SHIP_NOT_ON_TIME',
  54: 'DELIVERY_NOT_ON_TIME',
  55: 'DELIVERY_QUANTITY_NOT_STATIS',
  56: 'JIT_ISSUE',
  57: 'CUSTOMIZED_GOODS_QUALITY_ISSUE'
};
var deductionNameObj = {
  52: '消费者及履约保障-售后问题',
  53: '备货违规 - 发货履约保障-延迟发货',
  54: '备货违规 - 发货履约保障-延迟到货',
  55: '备货违规 - 发货履约保障-缺货',
  56: '备货违规 - 商品品质保障-质量问题(JIT商品)',
  57: '备货违规 - 商品品质保障-质量问题(定制商品)',
  58: '质量事故违规',
  521: '仓储增值服务-贴标费'
};

var getParamsByType = function getParamsByType(type) {
  switch (type) {
    case 52:
      return {
        fundDeductionType: 'AFTER_SALES'
      };

    case 53:
    case 54:
    case 55:
    case 56:
    case 57:
      return {
        fundDeductionType: 'STOCKING_VIOLATION',
        deductionCode: deductionType[type]
      };

    case 58:
      return {
        fundDeductionType: 'QUALITY_ACCIDENT'
      };

    default:
      return {};
  }
};

var getDeductionReport_generateReport = /*#__PURE__*/function () {
  var _ref = getDeductionReport_asyncToGenerator( /*#__PURE__*/getDeductionReport_regeneratorRuntime().mark(function _callee(task) {
    var params, _yield$nativeRequest, success, errorCode, errorMsg, msg;

    return getDeductionReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            // deductionCode: "SHIP_NOT_ON_TIME",
            // fundDeductionType: "STOCKING_VIOLATION", // AFTER_SALES, QUALITY_ACCIDENT
            params = getParamsByType(task.report_type);
            _context.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export"), 'post', getDeductionReport_objectSpread(getDeductionReport_objectSpread({
              beginFundTime: task.report_custom_datetime_start,
              endFundTime: task.report_custom_datetime_end
            }, params), {}, {
              taskType: 17
            }), {
              Mallid: task.real_mall_id
            });

          case 4:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorCode = _yield$nativeRequest.errorCode;
            errorMsg = _yield$nativeRequest.errorMsg;

            if (!success) {
              _context.next = 14;
              break;
            }

            log["a" /* default */].setLog('全托管支出详情报表生成成功');
            task.status = 6;
            return _context.abrupt("return", true);

          case 14:
            if (!(errorCode == 4000004)) {
              _context.next = 19;
              break;
            }

            task.status = 6;
            return _context.abrupt("return", true);

          case 19:
            if (!(errorCode == 3000000)) {
              _context.next = 21;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 21:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            task.status = 3;
            log["a" /* default */].setLog(msg);
            task.msg = msg;

          case 25:
            _context.next = 33;
            break;

          case 27:
            _context.prev = 27;
            _context.t0 = _context["catch"](0);
            task.status = 3;
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 33:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 27]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getDeductionReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getDeductionReport_asyncToGenerator( /*#__PURE__*/getDeductionReport_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        find,
        _args2 = arguments;
    return getDeductionReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/history/page"), 'post', {
              pageNum: 1,
              pageSize: 50,
              taskType: 17
            }, {
              Mallid: task.real_mall_id
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 33;
              break;
            }

            list = res.result.merchantMerchantFileExportHistoryList;
            find = list.find(function (item) {
              return item.deductionName == deductionNameObj[task.report_type] && item.dataBeginDateTime == task.beginTime && item.dataEndDateTime == task.endTime;
            });

            if (!find) {
              _context2.next = 29;
              break;
            }

            _context2.t0 = find.status;
            _context2.next = _context2.t0 === 2 ? 17 : _context2.t0 === 1 ? 20 : 20;
            break;

          case 17:
            task.status = 2;
            task.exportId = find.id;
            return _context2.abrupt("return", true);

          case 20:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 24;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 24:
            _context2.next = 26;
            return getDeductionReport_awaitReportDownload(task, ++count);

          case 26:
            return _context2.abrupt("return", _context2.sent);

          case 27:
            _context2.next = 31;
            break;

          case 29:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 31:
            _context2.next = 35;
            break;

          case 33:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 35:
            _context2.next = 41;
            break;

          case 37:
            _context2.prev = 37;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 41:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 37]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取下载报表链接


var getReportUrl = /*#__PURE__*/function () {
  var _ref3 = getDeductionReport_asyncToGenerator( /*#__PURE__*/getDeductionReport_regeneratorRuntime().mark(function _callee3(task) {
    var res;
    return getDeductionReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/download"), 'post', {
              id: task.exportId,
              taskType: 17
            }, {
              Mallid: task.real_mall_id
            });

          case 3:
            res = _context3.sent;

            if (!(res.success && res.result)) {
              _context3.next = 7;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context3.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 7:
            _context3.next = 14;
            break;

          case 9:
            _context3.prev = 9;
            _context3.t0 = _context3["catch"](0);
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 14:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 9]]);
  }));

  return function getReportUrl(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 下载报表


var getDeductionReport_downloadReport = /*#__PURE__*/function () {
  var _ref4 = getDeductionReport_asyncToGenerator( /*#__PURE__*/getDeductionReport_regeneratorRuntime().mark(function _callee4(task) {
    var res, name, oFile;
    return getDeductionReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context4.sent;

            if (!(res && res.data)) {
              _context4.next = 11;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            log["a" /* default */].setLog('下载成功,源文件大小：', "".concat(oFile.size, "b"));
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context4.abrupt("return", [{
              oFile: oFile,
              name: name,
              blob: res.data
            }]);

          case 11:
            _context4.next = 18;
            break;

          case 13:
            _context4.prev = 13;
            _context4.t0 = _context4["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 18:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 13]]);
  }));

  return function downloadReport(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

var getDeductionReport = /*#__PURE__*/function () {
  var _ref5 = getDeductionReport_asyncToGenerator( /*#__PURE__*/getDeductionReport_regeneratorRuntime().mark(function _callee5(task) {
    var res, generateReportRes, fileRes, detailsRes, file, uploadRes;
    return getDeductionReport_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            res = [];

            if (!task.beginTime) {
              task.beginTime = task.report_custom_date_start + ' 00:00:00';
              task.endTime = task.report_custom_date_end + ' 23:59:59';
            }

            if ([521].includes(task.report_type)) {
              _context5.next = 27;
              break;
            }

            if (!(task.status !== 6)) {
              _context5.next = 12;
              break;
            }

            _context5.next = 6;
            return getDeductionReport_generateReport(task);

          case 6:
            generateReportRes = _context5.sent;

            if (generateReportRes) {
              _context5.next = 9;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 9:
            if (!(generateReportRes == 'needSplit')) {
              _context5.next = 12;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context5.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 12:
            _context5.next = 14;
            return getDeductionReport_awaitReportDownload(task);

          case 14:
            _context5.t0 = !_context5.sent;

            if (_context5.t0) {
              _context5.next = 19;
              break;
            }

            _context5.next = 18;
            return getReportUrl(task);

          case 18:
            _context5.t0 = !_context5.sent;

          case 19:
            if (!_context5.t0) {
              _context5.next = 21;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 21:
            _context5.next = 23;
            return getDeductionReport_downloadReport(task);

          case 23:
            fileRes = _context5.sent;

            if (fileRes) {
              _context5.next = 26;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 26:
            res = fileRes;

          case 27:
            if (![52, 521].includes(task.report_type)) {
              _context5.next = 36;
              break;
            }

            _context5.next = 30;
            return getDeductionReportExportDetail(task);

          case 30:
            detailsRes = _context5.sent;

            if (detailsRes) {
              _context5.next = 33;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 33:
            if (!(detailsRes === 'none' && [521].includes(task.report_type))) {
              _context5.next = 35;
              break;
            }

            return _context5.abrupt("return", {
              code: 0,
              msg: '没有需要导出的数据'
            });

          case 35:
            res = res.concat(detailsRes);

          case 36:
            _context5.next = 38;
            return Object(util["n" /* generateAsync */])(res);

          case 38:
            file = _context5.sent;

            if (file) {
              _context5.next = 41;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: '文件压缩失败，稍后可尝试“重新获取”'
            });

          case 41:
            _context5.next = 43;
            return Object(util["L" /* uploadFile */])(file);

          case 43:
            uploadRes = _context5.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context5.next = 47;
              break;
            }

            return _context5.abrupt("return", {
              code: 0,
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            });

          case 47:
            // 上传失败
            task.status = 7;
            task.msg = uploadRes.msg || '文件上传cos失败';
            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg,
              requestId: uploadRes.requestId
            });

          case 50:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getDeductionReport(_x5) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getDeductionReport = (getDeductionReport); // window.testDeductionReport = (report_type) => {
//   getDeductionReport({
//     report_type,
//     host:'https://seller.kuajingmaihuo.com',
//     report_custom_date_start:'2025-01-01',
//     report_custom_date_end:'2025-01-13',
//     platform_store_id: 65016470556,
//     status: 0,
//   })
// }
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getEPRReport.js
function getEPRReport_typeof(obj) { "@babel/helpers - typeof"; return getEPRReport_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; }, getEPRReport_typeof(obj); }

function getEPRReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getEPRReport_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" == getEPRReport_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 getEPRReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getEPRReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getEPRReport_ownKeys(Object(source), !0).forEach(function (key) { getEPRReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getEPRReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getEPRReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getEPRReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getEPRReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getEPRReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getEPRReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }








var getEPRReport_generateReport = /*#__PURE__*/function () {
  var _ref = getEPRReport_asyncToGenerator( /*#__PURE__*/getEPRReport_regeneratorRuntime().mark(function _callee(task) {
    var params, _yield$nativeRequest, success, errorCode, errorMsg, msg;

    return getEPRReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            params = [16].includes(task.taskType) ? {
              billingCycleList: [],
              taskType: task.taskType,
              financeDateStart: task.report_custom_date_start,
              financeDateEnd: task.report_custom_date_end
            } : getEPRReport_objectSpread({
              financeStartTime: task.report_custom_datetime_start,
              financeEndTime: task.report_custom_datetime_end,
              exportType: task.exportType,
              taskType: task.taskType
            }, task.taskType === 19 ? {
              billingCycle: task.report_date_month
            } : {});
            _context.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export"), 'post', params, {
              Mallid: task.real_mall_id,
              changeStoreId: task.changeStoreId
            });

          case 4:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorCode = _yield$nativeRequest.errorCode;
            errorMsg = _yield$nativeRequest.errorMsg;

            if (!success) {
              _context.next = 14;
              break;
            }

            log["a" /* default */].setLog('欧区ERP费用生成成功');
            task.status = 6;
            return _context.abrupt("return", true);

          case 14:
            if (!(errorCode == 4000004)) {
              _context.next = 19;
              break;
            }

            task.status = 6;
            return _context.abrupt("return", true);

          case 19:
            if (!(errorCode == 3000000)) {
              _context.next = 21;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 21:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            task.status = 3;
            log["a" /* default */].setLog(msg);
            task.msg = msg;

          case 25:
            _context.next = 33;
            break;

          case 27:
            _context.prev = 27;
            _context.t0 = _context["catch"](0);
            task.status = 3;
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 33:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 27]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getEPRReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getEPRReport_asyncToGenerator( /*#__PURE__*/getEPRReport_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        find,
        _args2 = arguments;
    return getEPRReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/history/page"), 'post', {
              pageNum: 1,
              pageSize: 50,
              taskType: task.taskType
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: task.changeStoreId
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 33;
              break;
            }

            list = res.result.merchantMerchantFileExportHistoryList;
            find = list.find(function (item) {
              return [16].includes(task.taskType) ? item.financeDateStart == task.report_custom_date_start && item.financeDateEnd == task.report_custom_date_end : item.exportType == task.exportType && item.financeStartTime == task.report_custom_datetime_start && item.financeEndTime == task.report_custom_datetime_end;
            });

            if (!find) {
              _context2.next = 29;
              break;
            }

            _context2.t0 = find.status;
            _context2.next = _context2.t0 === 2 ? 17 : _context2.t0 === 1 ? 20 : 20;
            break;

          case 17:
            task.status = 2;
            task.exportId = find.id;
            return _context2.abrupt("return", true);

          case 20:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 24;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 24:
            _context2.next = 26;
            return getEPRReport_awaitReportDownload(task, ++count);

          case 26:
            return _context2.abrupt("return", _context2.sent);

          case 27:
            _context2.next = 31;
            break;

          case 29:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 31:
            _context2.next = 35;
            break;

          case 33:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 35:
            _context2.next = 41;
            break;

          case 37:
            _context2.prev = 37;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 41:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 37]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取下载报表链接


var getEPRReport_getReportUrl = /*#__PURE__*/function () {
  var _ref3 = getEPRReport_asyncToGenerator( /*#__PURE__*/getEPRReport_regeneratorRuntime().mark(function _callee3(task) {
    var res;
    return getEPRReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/download"), 'post', {
              id: task.exportId,
              taskType: task.taskType
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: task.changeStoreId
            });

          case 3:
            res = _context3.sent;

            if (!(res.success && res.result)) {
              _context3.next = 7;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context3.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 7:
            _context3.next = 14;
            break;

          case 9:
            _context3.prev = 9;
            _context3.t0 = _context3["catch"](0);
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 14:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 9]]);
  }));

  return function getReportUrl(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 下载报表


var getEPRReport_downloadReport = /*#__PURE__*/function () {
  var _ref4 = getEPRReport_asyncToGenerator( /*#__PURE__*/getEPRReport_regeneratorRuntime().mark(function _callee4(task) {
    var res, name, oFile, fileRes, zip;
    return getEPRReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context4.sent;

            if (!(res && res.data)) {
              _context4.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context4.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context4.abrupt("return", fileRes);

          case 16:
            _context4.next = 23;
            break;

          case 18:
            _context4.prev = 18;
            _context4.t0 = _context4["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 18]]);
  }));

  return function downloadReport(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

var getEPRReport = /*#__PURE__*/function () {
  var _ref5 = getEPRReport_asyncToGenerator( /*#__PURE__*/getEPRReport_regeneratorRuntime().mark(function _callee5(task) {
    var loginRes, msg, generateReportRes, param, res, uploadRes;
    return getEPRReport_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            task.changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            task.host = temu["h" /* temu */].cbEuHost;
            task.taskType = 18; // 商品环保费18, 包装环保费19, 代付服务费16

            task.exportType = 2; // 已扣费2 ，已退费 4

            if (task.report_type == 59) {
              task.taskType = 18;
              task.exportType = 2;
            }

            if (task.report_type == 510) {
              task.taskType = 18;
              task.exportType = 4;
            }

            if (task.report_type == 511) {
              task.taskType = 19;
              task.exportType = 2;
            }

            if (task.report_type == 512) {
              task.taskType = 19;
              task.exportType = 4;
            } // 代付服务费-已扣费，生成接口传参和page查询不一样


            if (task.report_type == 513) {
              task.taskType = 16;
            } // 监听header头修改cookie
            // await changeLocalMallId(task.platform_store_id, task.siteId, task.host)


            _context5.next = 11;
            return Object(temu["g" /* loginCb */])(task);

          case 11:
            loginRes = _context5.sent;

            if (loginRes) {
              _context5.next = 17;
              break;
            }

            msg = '切换到欧区站点失败，请检查';
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context5.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 17:
            _context5.t0 = task.status !== 6;

            if (!_context5.t0) {
              _context5.next = 22;
              break;
            }

            _context5.next = 21;
            return getEPRReport_awaitReportDownload(task);

          case 21:
            _context5.t0 = !_context5.sent;

          case 22:
            if (!_context5.t0) {
              _context5.next = 31;
              break;
            }

            _context5.next = 25;
            return getEPRReport_generateReport(task);

          case 25:
            generateReportRes = _context5.sent;

            if (generateReportRes) {
              _context5.next = 28;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 28:
            if (!(generateReportRes == 'needSplit')) {
              _context5.next = 31;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context5.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 31:
            _context5.t1 = task.status !== 2;

            if (!_context5.t1) {
              _context5.next = 36;
              break;
            }

            _context5.next = 35;
            return getEPRReport_awaitReportDownload(task);

          case 35:
            _context5.t1 = !_context5.sent;

          case 36:
            if (!_context5.t1) {
              _context5.next = 38;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 38:
            _context5.next = 40;
            return getEPRReport_getReportUrl(task);

          case 40:
            if (_context5.sent) {
              _context5.next = 42;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 42:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context5.next = 45;
            return getEPRReport_downloadReport(task);

          case 45:
            res = _context5.sent;

            if (!(res && res.file)) {
              _context5.next = 56;
              break;
            }

            _context5.next = 49;
            return Object(util["L" /* uploadFile */])(res.file);

          case 49:
            uploadRes = _context5.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context5.next = 53;
              break;
            }

            return _context5.abrupt("return", getEPRReport_objectSpread(getEPRReport_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 53:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 56:
            if (![8, 12].includes(task.status)) {
              _context5.next = 59;
              break;
            }

            task.isDelete = true;
            return _context5.abrupt("return", getEPRReport_objectSpread(getEPRReport_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 59:
            return _context5.abrupt("return", getEPRReport_objectSpread(getEPRReport_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 60:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getEPRReport(_x5) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getEPRReport = (getEPRReport); // window.testEPRReport = () => {
//   getEPRReport({
//     report_type: 512,
//     host:'https://agentseller-eu.temu.com',
//     report_custom_date_start:'2025-01-01',
//     report_custom_date_end:'2025-01-13',
//     platform_store_id: 65016470556,
//     status: 0,
//   })
// }
// EXTERNAL MODULE: ./src/config.js
var src_config = __webpack_require__("db49");

// CONCATENATED MODULE: ./src/platform/temu/qtReport/getTemuReport.js
function getTemuReport_typeof(obj) { "@babel/helpers - typeof"; return getTemuReport_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; }, getTemuReport_typeof(obj); }

function getTemuReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getTemuReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getTemuReport_ownKeys(Object(source), !0).forEach(function (key) { getTemuReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getTemuReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getTemuReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getTemuReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getTemuReport_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" == getTemuReport_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 getTemuReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getTemuReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getTemuReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getTemuReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }









var getTemuReport_generateReport = /*#__PURE__*/function () {
  var _ref = getTemuReport_asyncToGenerator( /*#__PURE__*/getTemuReport_regeneratorRuntime().mark(function _callee(task) {
    var _yield$nativeRequest, success, errorMsg, errorCode, errMsg, msg;

    return getTemuReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export"), 'post', {
              beginTime: task.report_custom_datetime_start,
              endTime: task.report_custom_datetime_end,
              fundDetailExport: true,
              taskType: 19
            }, {
              Mallid: task.platform_store_id
            });

          case 3:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            errorCode = _yield$nativeRequest.errorCode;

            if (!success) {
              _context.next = 13;
              break;
            }

            log["a" /* default */].setLog('半托管财务报表生成成功');
            task.status = 6;
            return _context.abrupt("return", true);

          case 13:
            errMsg = JSON.stringify(errorMsg);

            if (!(errorCode === 2000000 || errMsg.includes('请明日再试'))) {
              _context.next = 19;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);
            _context.next = 24;
            break;

          case 19:
            if (!(errorCode == 3000000)) {
              _context.next = 23;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 23:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);

          case 24:
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            task.status = 3;

          case 27:
            _context.next = 35;
            break;

          case 29:
            _context.prev = 29;
            _context.t0 = _context["catch"](0);
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            task.status = 3;
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 35:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 29]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getTemuReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getTemuReport_asyncToGenerator( /*#__PURE__*/getTemuReport_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        find,
        _args2 = arguments;
    return getTemuReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/history/page"), 'post', {
              pageNum: 1,
              pageSize: 50,
              taskType: 19
            }, {
              Mallid: task.platform_store_id
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 35;
              break;
            }

            list = res.result.merchantMerchantFileExportHistoryList;
            find = list.find(function (item) {
              return item.fundDetailExport == true && item.searchExportTimeBegin == task.report_custom_datetime_start && item.searchExportTimeEnd == task.report_custom_datetime_end && item.createTime > Date.now() - 24 * 60 * 60 * 1000;
            });

            if (!find) {
              _context2.next = 31;
              break;
            }

            _context2.t0 = find.status;
            _context2.next = _context2.t0 === 2 ? 17 : _context2.t0 === 1 ? 22 : 22;
            break;

          case 17:
            task.status = 2;
            task.agentSellerExportParams = find.agentSellerExportParams;
            task.agentSellerExportSign = find.agentSellerExportSign;
            task.downloadId = find.id;
            return _context2.abrupt("return", true);

          case 22:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 26;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 26:
            _context2.next = 28;
            return getTemuReport_awaitReportDownload(task, ++count);

          case 28:
            return _context2.abrupt("return", _context2.sent);

          case 29:
            _context2.next = 33;
            break;

          case 31:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 33:
            _context2.next = 37;
            break;

          case 35:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 37:
            _context2.next = 43;
            break;

          case 39:
            _context2.prev = 39;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 43:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 39]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取英文中心下载报表链接


var getTemuReport_getEnReportUrl = /*#__PURE__*/function () {
  var _ref3 = getTemuReport_asyncToGenerator( /*#__PURE__*/getTemuReport_regeneratorRuntime().mark(function _callee3(task, host) {
    var backUp, loginRes, msg, changeStoreId, _yield$nativeRequest2, success, result, errorMsg, res, _msg;

    return getTemuReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            // 需要提前登录一下美区或者欧区
            backUp = getTemuReport_objectSpread(getTemuReport_objectSpread({}, task), {}, {
              host: host
            });
            _context3.next = 3;
            return Object(temu["g" /* loginCb */])(backUp);

          case 3:
            loginRes = _context3.sent;

            if (loginRes) {
              _context3.next = 10;
              break;
            }

            msg = '切换到美区、欧区或全球站点失败，请检查';
            backUp.msg = msg;
            backUp.status = 11;
            log["a" /* default */].setLog(backUp.msg);
            return _context3.abrupt("return", {
              code: 1,
              msg: backUp.msg
            });

          case 10:
            _context3.prev = 10;
            changeStoreId = "".concat(task.platform_store_id, "&").concat(task.siteId);
            _context3.next = 14;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export"), 'post', {
              params: task.agentSellerExportParams,
              sign: task.agentSellerExportSign,
              taskType: 31
            }, {
              Mallid: task.platform_store_id,
              changeStoreId: changeStoreId
            });

          case 14:
            _yield$nativeRequest2 = _context3.sent;
            success = _yield$nativeRequest2.success;
            result = _yield$nativeRequest2.result;
            errorMsg = _yield$nativeRequest2.errorMsg;

            if (!(success && result)) {
              _context3.next = 36;
              break;
            }

            _context3.prev = 19;
            _context3.next = 22;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export/download"), 'post', {
              id: result,
              taskType: 31
            }, {
              Mallid: task.platform_store_id,
              changeStoreId: changeStoreId
            });

          case 22:
            res = _context3.sent;

            if (!(res.success && res.result)) {
              _context3.next = 26;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context3.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 26:
            _context3.next = 34;
            break;

          case 28:
            _context3.prev = 28;
            _context3.t0 = _context3["catch"](19);
            task.msg = "\u4E0B\u8F7D\u62A5\u8868\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            task.status = 9;
            log["a" /* default */].setLog(task.msg);
            return _context3.abrupt("return", false);

          case 34:
            _context3.next = 40;
            break;

          case 36:
            _msg = "\u83B7\u53D6\u62A5\u8868\u4E0B\u8F7D\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            task.msg = _msg;
            task.status = 9;
            log["a" /* default */].setLog(_msg);

          case 40:
            _context3.next = 48;
            break;

          case 42:
            _context3.prev = 42;
            _context3.t1 = _context3["catch"](10);
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t1, task));
            task.status = 9;
            log["a" /* default */].setLog(task.msg);
            return _context3.abrupt("return", false);

          case 48:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[10, 42], [19, 28]]);
  }));

  return function getEnReportUrl(_x3, _x4) {
    return _ref3.apply(this, arguments);
  };
}(); // 获取下载报表链接


var getTemuReport_getCnReportUrl = /*#__PURE__*/function () {
  var _ref4 = getTemuReport_asyncToGenerator( /*#__PURE__*/getTemuReport_regeneratorRuntime().mark(function _callee4(task) {
    var res;
    return getTemuReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/download"), 'post', {
              id: task.downloadId,
              taskType: 19
            }, {
              Mallid: task.platform_store_id
            });

          case 3:
            res = _context4.sent;

            if (!(res.success && res.result)) {
              _context4.next = 9;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context4.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 9:
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(res.errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 12:
            _context4.next = 19;
            break;

          case 14:
            _context4.prev = 14;
            _context4.t0 = _context4["catch"](0);
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 19:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 14]]);
  }));

  return function getCnReportUrl(_x5) {
    return _ref4.apply(this, arguments);
  };
}(); // 下载报表


var getTemuReport_downloadReport = /*#__PURE__*/function () {
  var _ref5 = getTemuReport_asyncToGenerator( /*#__PURE__*/getTemuReport_regeneratorRuntime().mark(function _callee5(task) {
    var res, name, oFile, fileRes, zip;
    return getTemuReport_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.prev = 0;
            _context5.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context5.sent;

            if (!(res && res.data)) {
              _context5.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context5.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context5.abrupt("return", fileRes);

          case 16:
            _context5.next = 23;
            break;

          case 18:
            _context5.prev = 18;
            _context5.t0 = _context5["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context5.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[0, 18]]);
  }));

  return function downloadReport(_x6) {
    return _ref5.apply(this, arguments);
  };
}();

var getTemuReport = /*#__PURE__*/function () {
  var _ref6 = getTemuReport_asyncToGenerator( /*#__PURE__*/getTemuReport_regeneratorRuntime().mark(function _callee6(task) {
    var generateReportRes, host, param, res, uploadRes;
    return getTemuReport_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.t0 = task.status !== 6;

            if (!_context6.t0) {
              _context6.next = 5;
              break;
            }

            _context6.next = 4;
            return getTemuReport_awaitReportDownload(task);

          case 4:
            _context6.t0 = !_context6.sent;

          case 5:
            if (!_context6.t0) {
              _context6.next = 14;
              break;
            }

            _context6.next = 8;
            return getTemuReport_generateReport(task);

          case 8:
            generateReportRes = _context6.sent;

            if (generateReportRes) {
              _context6.next = 11;
              break;
            }

            return _context6.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 11:
            if (!(generateReportRes == 'needSplit')) {
              _context6.next = 14;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context6.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 14:
            _context6.t1 = task.status !== 2;

            if (!_context6.t1) {
              _context6.next = 19;
              break;
            }

            _context6.next = 18;
            return getTemuReport_awaitReportDownload(task);

          case 18:
            _context6.t1 = !_context6.sent;

          case 19:
            if (!_context6.t1) {
              _context6.next = 21;
              break;
            }

            return _context6.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 21:
            if (!(task.report_type == 1)) {
              _context6.next = 28;
              break;
            }

            _context6.next = 24;
            return getTemuReport_getCnReportUrl(task);

          case 24:
            if (_context6.sent) {
              _context6.next = 26;
              break;
            }

            return _context6.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 26:
            _context6.next = 33;
            break;

          case 28:
            host = {
              101: temu["h" /* temu */].cbGlobalHost,
              102: temu["h" /* temu */].cbEuHost,
              103: temu["h" /* temu */].cbUsHost
            }[task.report_type]; // 监听header头修改cookie
            // await changeLocalMallId(task.platform_store_id, task.siteId, host)

            _context6.next = 31;
            return getTemuReport_getEnReportUrl(task, host);

          case 31:
            if (_context6.sent) {
              _context6.next = 33;
              break;
            }

            return _context6.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 33:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context6.next = 36;
            return getTemuReport_downloadReport(task);

          case 36:
            res = _context6.sent;

            if (!(res && res.file)) {
              _context6.next = 47;
              break;
            }

            _context6.next = 40;
            return Object(util["L" /* uploadFile */])(res.file);

          case 40:
            uploadRes = _context6.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context6.next = 44;
              break;
            }

            return _context6.abrupt("return", getTemuReport_objectSpread(getTemuReport_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 44:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 47:
            if (![8, 12].includes(task.status)) {
              _context6.next = 50;
              break;
            }

            task.isDelete = true;
            return _context6.abrupt("return", getTemuReport_objectSpread(getTemuReport_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 50:
            return _context6.abrupt("return", getTemuReport_objectSpread(getTemuReport_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 51:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6);
  }));

  return function getTemuReport(_x7) {
    return _ref6.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getTemuReport = (getTemuReport); // window.testGetTemuReport = () => {
//   getTemuReport({
//     host:'https://seller.kuajingmaihuo.com',
//     report_custom_date_start:'2024-11-01',
//     report_custom_date_end:'2024-11-26',
//     platform_store_id: 634418215364437,
//     beginTime:1730390400000,
//     endTime:1732636799000,
//     area: 'US',
//     status: 6,
//   })
// }
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getStmlReport.js
function getStmlReport_typeof(obj) { "@babel/helpers - typeof"; return getStmlReport_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; }, getStmlReport_typeof(obj); }

function getStmlReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getStmlReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getStmlReport_ownKeys(Object(source), !0).forEach(function (key) { getStmlReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getStmlReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getStmlReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getStmlReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getStmlReport_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" == getStmlReport_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 getStmlReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getStmlReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getStmlReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getStmlReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }









var getStmlReport_generateReport = /*#__PURE__*/function () {
  var _ref = getStmlReport_asyncToGenerator( /*#__PURE__*/getStmlReport_regeneratorRuntime().mark(function _callee(task) {
    var _yield$nativeRequest, success, result, errorMsg, errorCode, errMsg, msg;

    return getStmlReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["z" /* nativeRequest */])(task.isUdp ? "".concat(task.host, "/api/udp/yuanbenchu/seller_central/recon_bill/download/async") : "".concat(task.host, "/portal/selene/seller/portal/recon/download"), 'post', {
              req: {
                deductTimeBegin: task.report_custom_datetime_start,
                deductTimeEnd: task.report_custom_datetime_end,
                settleStatus: 1
              },
              requestStr: JSON.stringify(["\u8D26\u5355\u652F\u51FA/\u9000\u6B3E\u65F6\u95F4: ".concat(task.report_custom_date_start, " ~ ").concat(task.report_custom_date_end)])
            }, {
              changeStoreId: task.platform_store_id,
              Mallid: task.platform_store_id
            });

          case 3:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            result = _yield$nativeRequest.result;
            errorMsg = _yield$nativeRequest.errorMsg;
            errorCode = _yield$nativeRequest.errorCode;

            if (!(success && result && result.taskId)) {
              _context.next = 15;
              break;
            }

            log["a" /* default */].setLog('发货面单费报表生成成功');
            task.taskId = result.taskId;
            task.status = 6;
            return _context.abrupt("return", true);

          case 15:
            errMsg = JSON.stringify(errorMsg);

            if (!(errorCode === 2000000 || errMsg.includes('请明日再试'))) {
              _context.next = 21;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);
            _context.next = 26;
            break;

          case 21:
            if (!(errorCode == 3000000)) {
              _context.next = 25;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 25:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);

          case 26:
            log["a" /* default */].setLog(msg);
            task.msg = msg;

          case 28:
            _context.next = 36;
            break;

          case 30:
            _context.prev = 30;
            _context.t0 = _context["catch"](0);
            task.status = 3;
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 36:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 30]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getStmlReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getStmlReport_asyncToGenerator( /*#__PURE__*/getStmlReport_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        curDate,
        requestDate,
        find,
        _args2 = arguments;
    return getStmlReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])(task.isUdp ? "".concat(task.host, "/api/udp/yuanbenchu/seller_central/recon_bill/task/info") : "".concat(task.host, "/portal/selene/seller/portal/recon/download_list"), 'post', {
              pageNum: 1,
              pageSize: 50,
              settleStatus: 1
            }, {
              changeStoreId: task.platform_store_id,
              Mallid: task.platform_store_id
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 37;
              break;
            }

            list = res.result.excelCommonTaskList;
            _context2.next = 14;
            return Object(util["t" /* getServiceTime */])();

          case 14:
            curDate = _context2.sent;
            requestDate = "".concat(task.report_custom_date_start, " ~ ").concat(task.report_custom_date_end);
            find = list.find(function (item) {
              // 判断列表是否已有要获取报表
              if (item.createTime > curDate - 23 * 60 * 60 * 1000 && !task.taskId) {
                return item.requestStr.indexOf(requestDate) > -1;
              } else return item.taskId == task.taskId;
            });

            if (!find) {
              _context2.next = 33;
              break;
            }

            _context2.t0 = find.isFinished;
            _context2.next = _context2.t0 === true ? 21 : _context2.t0 === false ? 24 : 24;
            break;

          case 21:
            task.status = 2;
            task.downloadUrl = find.downloadUrl;
            return _context2.abrupt("return", true);

          case 24:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 28;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 28:
            _context2.next = 30;
            return getStmlReport_awaitReportDownload(task, ++count);

          case 30:
            return _context2.abrupt("return", _context2.sent);

          case 31:
            _context2.next = 35;
            break;

          case 33:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 35:
            _context2.next = 39;
            break;

          case 37:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 39:
            _context2.next = 45;
            break;

          case 41:
            _context2.prev = 41;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 45:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 41]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 下载报表


var getStmlReport_downloadReport = /*#__PURE__*/function () {
  var _ref3 = getStmlReport_asyncToGenerator( /*#__PURE__*/getStmlReport_regeneratorRuntime().mark(function _callee3(task) {
    var res, name, oFile, fileRes, zip;
    return getStmlReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.downloadUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context3.sent;

            if (!(res && res.data)) {
              _context3.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.downloadUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context3.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('发货面单费压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context3.abrupt("return", fileRes);

          case 16:
            _context3.next = 23;
            break;

          case 18:
            _context3.prev = 18;
            _context3.t0 = _context3["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 18]]);
  }));

  return function downloadReport(_x3) {
    return _ref3.apply(this, arguments);
  };
}();

var getStmlReport = /*#__PURE__*/function () {
  var _ref4 = getStmlReport_asyncToGenerator( /*#__PURE__*/getStmlReport_regeneratorRuntime().mark(function _callee4(task) {
    var loginRes, msg, generateReportRes, param, res, uploadRes;
    return getStmlReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            task.host = task.report_type == 1102 ? temu["h" /* temu */].cbUsHost : temu["h" /* temu */].cbEuHost;
            task.isUdp = task.report_type == 1102; // 监听header头修改cookie
            // await changeLocalMallId(task.platform_store_id, task.siteId, task.host)
            // 需要提前登录一下美区或者欧区

            _context4.next = 4;
            return Object(temu["g" /* loginCb */])(task);

          case 4:
            loginRes = _context4.sent;

            if (loginRes) {
              _context4.next = 10;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 10:
            _context4.t0 = task.status !== 6;

            if (!_context4.t0) {
              _context4.next = 15;
              break;
            }

            _context4.next = 14;
            return getStmlReport_awaitReportDownload(task);

          case 14:
            _context4.t0 = !_context4.sent;

          case 15:
            if (!_context4.t0) {
              _context4.next = 24;
              break;
            }

            _context4.next = 18;
            return getStmlReport_generateReport(task);

          case 18:
            generateReportRes = _context4.sent;

            if (generateReportRes) {
              _context4.next = 21;
              break;
            }

            return _context4.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 21:
            if (!(generateReportRes == 'needSplit')) {
              _context4.next = 24;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context4.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 24:
            _context4.t1 = task.status !== 2;

            if (!_context4.t1) {
              _context4.next = 29;
              break;
            }

            _context4.next = 28;
            return getStmlReport_awaitReportDownload(task);

          case 28:
            _context4.t1 = !_context4.sent;

          case 29:
            if (!_context4.t1) {
              _context4.next = 31;
              break;
            }

            return _context4.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 31:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context4.next = 34;
            return getStmlReport_downloadReport(task);

          case 34:
            res = _context4.sent;

            if (!(res && res.file)) {
              _context4.next = 45;
              break;
            }

            _context4.next = 38;
            return Object(util["L" /* uploadFile */])(res.file);

          case 38:
            uploadRes = _context4.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context4.next = 42;
              break;
            }

            return _context4.abrupt("return", getStmlReport_objectSpread(getStmlReport_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 42:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 45:
            if (![8, 12].includes(task.status)) {
              _context4.next = 48;
              break;
            }

            task.isDelete = true;
            return _context4.abrupt("return", getStmlReport_objectSpread(getStmlReport_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 48:
            return _context4.abrupt("return", getStmlReport_objectSpread(getStmlReport_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 49:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function getStmlReport(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getStmlReport = (getStmlReport); // window.testGetStmlReport = () => {
//   getStmlReport({
//     host:'https://agentseller-eu.temu.com',
//     report_custom_date_start:'2024-11-01',
//     report_custom_date_end:'2024-11-30',
//     platform_store_id: 634418215364437,
//     beginTime:1730390400000,
//     endTime:1732636799000,
//     area: 'EU'
//   })
// }
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getReverseReport.js
function getReverseReport_typeof(obj) { "@babel/helpers - typeof"; return getReverseReport_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; }, getReverseReport_typeof(obj); }

function getReverseReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getReverseReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getReverseReport_ownKeys(Object(source), !0).forEach(function (key) { getReverseReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getReverseReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getReverseReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getReverseReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getReverseReport_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" == getReverseReport_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 getReverseReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getReverseReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getReverseReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getReverseReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }









var getReverseReport_generateReport = /*#__PURE__*/function () {
  var _ref = getReverseReport_asyncToGenerator( /*#__PURE__*/getReverseReport_regeneratorRuntime().mark(function _callee(task) {
    var _yield$nativeRequest, success, result, errorMsg, errorCode, errMsg, msg;

    return getReverseReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/portal/").concat(task.isUdp ? 'udp/' : '').concat(task.serverName, "/seller/center/bill/download/async"), 'post', {
              ext: JSON.stringify({
                deductTimeBegin: task.report_custom_datetime_start,
                deductTimeEnd: task.report_custom_datetime_end,
                rangeTime: "\u5BFC\u51FA\u4EFB\u52A1\u751F\u6210\u65F6\u95F4: ".concat(task.report_custom_date_start, " ~ ").concat(task.report_custom_date_end)
              })
            }, {
              changeStoreId: task.platform_store_id,
              Mallid: task.platform_store_id
            });

          case 3:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            result = _yield$nativeRequest.result;
            errorMsg = _yield$nativeRequest.errorMsg;
            errorCode = _yield$nativeRequest.errorCode;

            if (!(success && result && result.taskId)) {
              _context.next = 15;
              break;
            }

            log["a" /* default */].setLog('退货面单费已创建生成任务');
            task.taskId = result.taskId;
            task.status = 6;
            return _context.abrupt("return", true);

          case 15:
            errMsg = JSON.stringify(errorMsg);

            if (!(errorCode === 2000000 || errMsg.includes('请明日再试'))) {
              _context.next = 21;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);
            _context.next = 26;
            break;

          case 21:
            if (!(errorCode == 3000000)) {
              _context.next = 25;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 25:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);

          case 26:
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            task.status = 3;
            return _context.abrupt("return", false);

          case 30:
            _context.next = 38;
            break;

          case 32:
            _context.prev = 32;
            _context.t0 = _context["catch"](0);
            task.status = 3;
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 38:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 32]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getReverseReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getReverseReport_asyncToGenerator( /*#__PURE__*/getReverseReport_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        curDate,
        find,
        _args2 = arguments;
    return getReverseReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/portal/").concat(task.isUdp ? 'udp/' : '').concat(task.serverName, "/seller/center/bill/task/list"), 'post', {
              pageNum: 1,
              pageSize: 50
            }, {
              changeStoreId: task.platform_store_id,
              Mallid: task.platform_store_id
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 36;
              break;
            }

            list = res.result.excelCommonTaskList;
            _context2.next = 14;
            return Object(util["t" /* getServiceTime */])();

          case 14:
            curDate = _context2.sent;
            find = list.find(function (item) {
              var ext = item.ext && JSON.parse(item.ext);
              var createTime = new Date(item.createdAt).getTime(); // 判断列表是否已有要获取报表

              if (createTime > curDate - 23 * 60 * 60 * 1000 && ext && !task.taskId) {
                return ext.deductTimeBegin == task.report_custom_datetime_start && ext.deductTimeEnd == task.report_custom_datetime_end;
              } else return item.taskId == task.taskId;
            });

            if (!find) {
              _context2.next = 32;
              break;
            }

            _context2.t0 = find.isFinished;
            _context2.next = _context2.t0 === true ? 20 : _context2.t0 === false ? 23 : 23;
            break;

          case 20:
            task.status = 2;
            task.downloadUrl = find.downloadUrl;
            return _context2.abrupt("return", true);

          case 23:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 27;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 27:
            _context2.next = 29;
            return getReverseReport_awaitReportDownload(task, ++count);

          case 29:
            return _context2.abrupt("return", _context2.sent);

          case 30:
            _context2.next = 34;
            break;

          case 32:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 34:
            _context2.next = 38;
            break;

          case 36:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 38:
            _context2.next = 44;
            break;

          case 40:
            _context2.prev = 40;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 44:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 40]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 下载报表


var getReverseReport_downloadReport = /*#__PURE__*/function () {
  var _ref3 = getReverseReport_asyncToGenerator( /*#__PURE__*/getReverseReport_regeneratorRuntime().mark(function _callee3(task) {
    var res, name, oFile, fileRes, zip;
    return getReverseReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.downloadUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context3.sent;

            if (!(res && res.data)) {
              _context3.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.downloadUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context3.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('退货面单费压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context3.abrupt("return", fileRes);

          case 16:
            _context3.next = 23;
            break;

          case 18:
            _context3.prev = 18;
            _context3.t0 = _context3["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 18]]);
  }));

  return function downloadReport(_x3) {
    return _ref3.apply(this, arguments);
  };
}();

var getReverseReport = /*#__PURE__*/function () {
  var _ref4 = getReverseReport_asyncToGenerator( /*#__PURE__*/getReverseReport_regeneratorRuntime().mark(function _callee4(task) {
    var isUs, loginRes, msg, generateReportRes, param, res, uploadRes;
    return getReverseReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            isUs = [1202, 1302].includes(task.report_type);
            task.host = isUs ? temu["h" /* temu */].cbUsHost : temu["h" /* temu */].cbEuHost;
            task.serverName = [1201, 1202].includes(task.report_type) ? 'sunce' : 'sunquan';
            task.isUdp = isUs; // 监听header头修改cookie
            // await changeLocalMallId(task.platform_store_id, task.siteId, task.host)
            // 需要提前登录一下美区或者欧区

            _context4.next = 6;
            return Object(temu["g" /* loginCb */])(task);

          case 6:
            loginRes = _context4.sent;

            if (loginRes) {
              _context4.next = 12;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 12:
            _context4.t0 = task.status !== 6;

            if (!_context4.t0) {
              _context4.next = 17;
              break;
            }

            _context4.next = 16;
            return getReverseReport_awaitReportDownload(task);

          case 16:
            _context4.t0 = !_context4.sent;

          case 17:
            if (!_context4.t0) {
              _context4.next = 26;
              break;
            }

            _context4.next = 20;
            return getReverseReport_generateReport(task);

          case 20:
            generateReportRes = _context4.sent;

            if (generateReportRes) {
              _context4.next = 23;
              break;
            }

            return _context4.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 23:
            if (!(generateReportRes == 'needSplit')) {
              _context4.next = 26;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context4.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 26:
            _context4.t1 = task.status !== 2;

            if (!_context4.t1) {
              _context4.next = 31;
              break;
            }

            _context4.next = 30;
            return getReverseReport_awaitReportDownload(task);

          case 30:
            _context4.t1 = !_context4.sent;

          case 31:
            if (!_context4.t1) {
              _context4.next = 33;
              break;
            }

            return _context4.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 33:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context4.next = 36;
            return getReverseReport_downloadReport(task);

          case 36:
            res = _context4.sent;

            if (!(res && res.file)) {
              _context4.next = 47;
              break;
            }

            _context4.next = 40;
            return Object(util["L" /* uploadFile */])(res.file);

          case 40:
            uploadRes = _context4.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context4.next = 44;
              break;
            }

            return _context4.abrupt("return", getReverseReport_objectSpread(getReverseReport_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 44:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 47:
            if (![8, 12].includes(task.status)) {
              _context4.next = 50;
              break;
            }

            task.isDelete = true;
            return _context4.abrupt("return", getReverseReport_objectSpread(getReverseReport_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 50:
            return _context4.abrupt("return", getReverseReport_objectSpread(getReverseReport_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 51:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function getReverseReport(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getReverseReport = (getReverseReport); // window.testGetReverseReport = () => {
//   getReverseReport({
//     area: 'EU',
//     host:'https://agentseller-eu.temu.com',
//     report_custom_date_start:'2024-11-01',
//     report_custom_date_end:'2024-11-26',
//     platform_store_id: 634418215364437,
//     beginTime:1730390400000,
//     endTime:1732636799000,
//     report_type:12,
//   })
// }
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getPoDetail.js
function getPoDetail_typeof(obj) { "@babel/helpers - typeof"; return getPoDetail_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; }, getPoDetail_typeof(obj); }

function getPoDetail_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getPoDetail_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getPoDetail_ownKeys(Object(source), !0).forEach(function (key) { getPoDetail_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getPoDetail_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getPoDetail_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getPoDetail_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getPoDetail_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" == getPoDetail_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 getPoDetail_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getPoDetail_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getPoDetail_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getPoDetail_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }







 // 生成报告

var getPoDetail_generateReport = /*#__PURE__*/function () {
  var _ref = getPoDetail_asyncToGenerator( /*#__PURE__*/getPoDetail_regeneratorRuntime().mark(function _callee(task) {
    var _yield$nativeRequest, success, errorMsg, result, errorCode, errMsg, msg;

    return getPoDetail_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export"), 'post', {
              accountTimeEnd: task.report_custom_date_end,
              accountTimeStart: task.report_custom_date_start,
              taskType: 36
            }, {
              Mallid: task.platform_store_id
            });

          case 3:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            result = _yield$nativeRequest.result;
            errorCode = _yield$nativeRequest.errorCode;

            if (!success) {
              _context.next = 15;
              break;
            }

            log["a" /* default */].setLog('半托管po明细生成成功');
            task.reportId = result;
            task.status = 6;
            return _context.abrupt("return", true);

          case 15:
            errMsg = JSON.stringify(errorMsg);

            if (!(errorCode === 2000000 || errMsg.includes('请明日再试'))) {
              _context.next = 21;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);
            _context.next = 26;
            break;

          case 21:
            if (!(errorCode == 3000000)) {
              _context.next = 25;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 25:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);

          case 26:
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            task.status = 3;

          case 29:
            _context.next = 37;
            break;

          case 31:
            _context.prev = 31;
            _context.t0 = _context["catch"](0);
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            task.status = 3;
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 37:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 31]]);
  }));

  return function generateReport(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getPoDetail_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getPoDetail_asyncToGenerator( /*#__PURE__*/getPoDetail_regeneratorRuntime().mark(function _callee2(task) {
    var count,
        res,
        list,
        find,
        _args2 = arguments;
    return getPoDetail_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D"; // task.status = 6

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

          case 7:
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/history/page"), 'post', {
              pageNum: 1,
              pageSize: 50,
              taskType: 36
            }, {
              Mallid: task.platform_store_id
            });

          case 9:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 33;
              break;
            }

            list = res.result.merchantMerchantFileExportHistoryList;
            find = list.find(function (item) {
              var accountTimeStart = moment_default()(item.accountTimeStart).format('YYYY-MM-DD');
              var accountTimeEnd = moment_default()(item.accountTimeEnd).format('YYYY-MM-DD');
              return item.expireSeconds > 0 && accountTimeStart == task.report_custom_date_start && accountTimeEnd == task.report_custom_date_end || item.id == task.reportId;
            });

            if (!find) {
              _context2.next = 29;
              break;
            }

            _context2.t0 = find.status;
            _context2.next = _context2.t0 === 2 ? 17 : _context2.t0 === 1 ? 20 : 20;
            break;

          case 17:
            task.status = 2;
            task.reportId = find.id;
            return _context2.abrupt("return", true);

          case 20:
            // task.status = 6
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 24;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 24:
            _context2.next = 26;
            return getPoDetail_awaitReportDownload(task, ++count);

          case 26:
            return _context2.abrupt("return", _context2.sent);

          case 27:
            _context2.next = 31;
            break;

          case 29:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 31:
            _context2.next = 35;
            break;

          case 33:
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 35:
            _context2.next = 41;
            break;

          case 37:
            _context2.prev = 37;
            _context2.t1 = _context2["catch"](1);
            // task.status = 6
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 41:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 37]]);
  }));

  return function awaitReportDownload(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 生成下载报表链接


var getDownloadReportUrl = /*#__PURE__*/function () {
  var _ref3 = getPoDetail_asyncToGenerator( /*#__PURE__*/getPoDetail_regeneratorRuntime().mark(function _callee3(task) {
    var _yield$nativeRequest2, success, result, errorMsg;

    return getPoDetail_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/file/export/download"), 'post', {
              id: task.reportId,
              taskType: 36
            }, {
              Mallid: task.platform_store_id
            });

          case 3:
            _yield$nativeRequest2 = _context3.sent;
            success = _yield$nativeRequest2.success;
            result = _yield$nativeRequest2.result;
            errorMsg = _yield$nativeRequest2.errorMsg;

            if (!(success && result.fileUrl)) {
              _context3.next = 12;
              break;
            }

            task.fileUrl = result.fileUrl;
            return _context3.abrupt("return", {
              fileUrl: result.fileUrl
            });

          case 12:
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 15:
            _context3.next = 22;
            break;

          case 17:
            _context3.prev = 17;
            _context3.t0 = _context3["catch"](0);
            task.status = 9;
            task.msg = "\u751F\u6210\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 22:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 17]]);
  }));

  return function getDownloadReportUrl(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 下载报表


var getPoDetail_downloadReport = /*#__PURE__*/function () {
  var _ref4 = getPoDetail_asyncToGenerator( /*#__PURE__*/getPoDetail_regeneratorRuntime().mark(function _callee4(task) {
    var res, name, oFile, fileRes, zip;
    return getPoDetail_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context4.sent;

            if (!(res && res.data)) {
              _context4.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context4.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context4.abrupt("return", fileRes);

          case 16:
            _context4.next = 23;
            break;

          case 18:
            _context4.prev = 18;
            _context4.t0 = _context4["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 18]]);
  }));

  return function downloadReport(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

var getPoDetail = /*#__PURE__*/function () {
  var _ref5 = getPoDetail_asyncToGenerator( /*#__PURE__*/getPoDetail_regeneratorRuntime().mark(function _callee5(task) {
    var loginRes, msg, generateReportRes, param, res, uploadRes;
    return getPoDetail_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            task.host = {
              201: temu["h" /* temu */].cbGlobalHost,
              202: temu["h" /* temu */].cbEuHost,
              203: temu["h" /* temu */].cbUsHost
            }[task.report_type];
            _context5.next = 3;
            return Object(temu["g" /* loginCb */])(task);

          case 3:
            loginRes = _context5.sent;

            if (loginRes) {
              _context5.next = 10;
              break;
            }

            msg = '切换到美区、欧区或全球站点失败，请检查';
            task.msg = msg;
            task.status = 11;
            log["a" /* default */].setLog(task.msg);
            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 10:
            _context5.t0 = task.status !== 6;

            if (!_context5.t0) {
              _context5.next = 15;
              break;
            }

            _context5.next = 14;
            return getPoDetail_awaitReportDownload(task);

          case 14:
            _context5.t0 = !_context5.sent;

          case 15:
            if (!_context5.t0) {
              _context5.next = 24;
              break;
            }

            _context5.next = 18;
            return getPoDetail_generateReport(task);

          case 18:
            generateReportRes = _context5.sent;

            if (generateReportRes) {
              _context5.next = 21;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 21:
            if (!(generateReportRes == 'needSplit')) {
              _context5.next = 24;
              break;
            }

            log["a" /* default */].setLog('当前时间段报表数据量太多，需要拆分');
            return _context5.abrupt("return", {
              code: 4,
              msg: '当前时间段报表数据量太多，需要拆分'
            });

          case 24:
            _context5.t1 = task.status !== 2;

            if (!_context5.t1) {
              _context5.next = 29;
              break;
            }

            _context5.next = 28;
            return getPoDetail_awaitReportDownload(task);

          case 28:
            _context5.t1 = !_context5.sent;

          case 29:
            if (!_context5.t1) {
              _context5.next = 31;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 31:
            _context5.next = 33;
            return getDownloadReportUrl(task);

          case 33:
            if (_context5.sent) {
              _context5.next = 35;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 35:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context5.next = 38;
            return getPoDetail_downloadReport(task);

          case 38:
            res = _context5.sent;

            if (!(res && res.file)) {
              _context5.next = 49;
              break;
            }

            _context5.next = 42;
            return Object(util["L" /* uploadFile */])(res.file);

          case 42:
            uploadRes = _context5.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context5.next = 46;
              break;
            }

            return _context5.abrupt("return", getPoDetail_objectSpread(getPoDetail_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 46:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 49:
            if (![8, 12].includes(task.status)) {
              _context5.next = 52;
              break;
            }

            task.isDelete = true;
            return _context5.abrupt("return", getPoDetail_objectSpread(getPoDetail_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 52:
            return _context5.abrupt("return", getPoDetail_objectSpread(getPoDetail_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 53:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getPoDetail(_x5) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getPoDetail = (getPoDetail);
// EXTERNAL MODULE: ./node_modules/moment-timezone/index.js
var moment_timezone = __webpack_require__("7f45");

// CONCATENATED MODULE: ./src/platform/temu/qtReport/getLocalTemuReport.js
function getLocalTemuReport_typeof(obj) { "@babel/helpers - typeof"; return getLocalTemuReport_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; }, getLocalTemuReport_typeof(obj); }

function getLocalTemuReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getLocalTemuReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getLocalTemuReport_ownKeys(Object(source), !0).forEach(function (key) { getLocalTemuReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getLocalTemuReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getLocalTemuReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getLocalTemuReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getLocalTemuReport_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" == getLocalTemuReport_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 getLocalTemuReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getLocalTemuReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getLocalTemuReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getLocalTemuReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }







 // 根据区域(US/EU)将日期字符串转换为对应当地时间的时间戳（不覆盖原字段）

var getLocalTemuReport_convertLocalDateRange = function convertLocalDateRange(task) {
  var tz = task.time_zone || (task.area === 'US' ? 'America/Los_Angeles' : 'Europe/Berlin');
  var startLocal = moment_default.a.tz(task.report_custom_date_start, 'YYYY-MM-DD', tz).startOf('day').valueOf();
  var endLocal = moment_default.a.tz(task.report_custom_date_end, 'YYYY-MM-DD', tz).endOf('day').valueOf();
  task.report_custom_datetime_start_local = startLocal;
  task.report_custom_datetime_end_local = endLocal;
};

var toGetReportSelectMaxTime = /*#__PURE__*/function () {
  var _ref = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee(task) {
    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return getReportMaxTime(task);

          case 2:
            return _context.abrupt("return", _context.sent);

          case 3:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function toGetReportSelectMaxTime(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 获取当前报表可导出的最新结束时间（失败最多重试3次）


var getReportMaxTime = /*#__PURE__*/function () {
  var _ref2 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee2(task) {
    var retry,
        res,
        _res$result,
        max_time,
        time_zone,
        _args2 = arguments;

    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            retry = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 0;
            _context2.prev = 1;
            _context2.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/statement/export/task/time"), 'post', {
              exportType: 1
            });

          case 4:
            res = _context2.sent;

            if (!(res && res.success && res.result && res.result.max_time)) {
              _context2.next = 10;
              break;
            }

            _res$result = res.result, max_time = _res$result.max_time, time_zone = _res$result.time_zone;
            task.time_zone = time_zone;
            task.max_time = max_time;
            return _context2.abrupt("return", true);

          case 10:
            task.msg = '获取报表可导出时间失败-----res返回：' + JSON.stringify(res);
            log["a" /* default */].setLog(task.msg);
            task.status = 3;
            return _context2.abrupt("return", false);

          case 16:
            _context2.prev = 16;
            _context2.t0 = _context2["catch"](1);

            if (!(retry < 3)) {
              _context2.next = 25;
              break;
            }

            log["a" /* default */].setLog("\u83B7\u53D6\u62A5\u8868\u53EF\u5BFC\u51FA\u65F6\u95F4\u5931\u8D25\uFF0C\u91CD\u8BD5\u7B2C".concat(retry + 1, "\u6B21"), Object(util["u" /* isError */])(_context2.t0, task));
            _context2.next = 22;
            return Object(util["h" /* delayed */])(1000);

          case 22:
            _context2.next = 24;
            return getReportMaxTime(task, retry + 1);

          case 24:
            return _context2.abrupt("return", _context2.sent);

          case 25:
            task.msg = '获取报表可导出时间失败-----接口报错：' + Object(util["u" /* isError */])(_context2.t0, task);
            log["a" /* default */].setLog(task.msg);
            task.status = 3;
            return _context2.abrupt("return", false);

          case 29:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 16]]);
  }));

  return function getReportMaxTime(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 校验并确定结束时间：开始时间必须 < max_time，结束时间取 min(report_custom_datetime_end, max_time)


var resolveReportEndTime = /*#__PURE__*/function () {
  var _ref3 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee3(task) {
    var _task$report_custom_d, _task$report_custom_d2;

    var maxTime, startTime, endTime;
    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            maxTime = task.max_time;

            if (maxTime) {
              _context3.next = 3;
              break;
            }

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

          case 3:
            startTime = Number((_task$report_custom_d = task.report_custom_datetime_start_local) !== null && _task$report_custom_d !== void 0 ? _task$report_custom_d : task.report_custom_datetime_start);
            endTime = Number((_task$report_custom_d2 = task.report_custom_datetime_end_local) !== null && _task$report_custom_d2 !== void 0 ? _task$report_custom_d2 : task.report_custom_datetime_end);

            if (startTime < maxTime) {
              _context3.next = 10;
              break;
            }

            task.msg = '开始时间大于最近可导出日期，请调整时间范围----startTime: ' + startTime + ' maxTime: ' + maxTime;
            log["a" /* default */].setLog(task.msg);
            task.status = 3;
            return _context3.abrupt("return", null);

          case 10:
            return _context3.abrupt("return", Math.min(endTime, maxTime));

          case 11:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function resolveReportEndTime(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 确保任务上缓存可用的结束时间，保持“生成请求”和“状态查询”用同一结束时间，避免中途再次拉接口导致结束时间变化。


var ensureEndCreateTime = /*#__PURE__*/function () {
  var _ref4 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee4(task) {
    var end;
    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            if (!(typeof task.endCreateTime === 'number')) {
              _context4.next = 2;
              break;
            }

            return _context4.abrupt("return", task.endCreateTime);

          case 2:
            _context4.next = 4;
            return resolveReportEndTime(task);

          case 4:
            end = _context4.sent;

            if (typeof end === 'number') {
              task.endCreateTime = end;
            }

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

          case 7:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function ensureEndCreateTime(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

var getLocalTemuReport_generateReport = /*#__PURE__*/function () {
  var _ref5 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee5(task) {
    var _task$report_custom_d3, endCreateTime, createParams, _yield$nativeRequest, success, error_msg, error_code, errMsg, msg;

    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.prev = 0;
            _context5.next = 3;
            return ensureEndCreateTime(task);

          case 3:
            endCreateTime = _context5.sent;

            if (endCreateTime) {
              _context5.next = 6;
              break;
            }

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

          case 6:
            createParams = {
              beginCreateTime: (_task$report_custom_d3 = task.report_custom_datetime_start_local) !== null && _task$report_custom_d3 !== void 0 ? _task$report_custom_d3 : task.report_custom_datetime_start,
              endCreateTime: endCreateTime,
              exportType: 1,
              fileType: 'excel'
            };
            _context5.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/statement/export/task/create"), 'post', createParams);

          case 9:
            _yield$nativeRequest = _context5.sent;
            success = _yield$nativeRequest.success;
            error_msg = _yield$nativeRequest.error_msg;
            error_code = _yield$nativeRequest.error_code;

            if (!success) {
              _context5.next = 18;
              break;
            }

            log["a" /* default */].setLog('半托管财务报表生成成功');
            return _context5.abrupt("return", true);

          case 18:
            errMsg = JSON.stringify(error_msg);

            // 操作频繁直接不让重试
            if (error_code === 2000000 || errMsg.includes('请明日再试')) {
              task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
              msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);
            } else {
              msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(errMsg);
            }

            log["a" /* default */].setLog(msg);
            task.msg = msg;
            task.status = 3;

          case 23:
            _context5.next = 31;
            break;

          case 25:
            _context5.prev = 25;
            _context5.t0 = _context5["catch"](0);
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context5.t0, task));
            task.status = 3;
            log["a" /* default */].setLog(task.msg);
            return _context5.abrupt("return", false);

          case 31:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[0, 25]]);
  }));

  return function generateReport(_x5) {
    return _ref5.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getLocalTemuReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref6 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee6(task) {
    var count,
        res,
        _task$report_custom_d4,
        list,
        normalizedEnd,
        endCreateTime,
        find,
        _args6 = arguments;

    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            count = _args6.length > 1 && _args6[1] !== undefined ? _args6[1] : 0;
            _context6.prev = 1;

            if (!(count >= 5)) {
              _context6.next = 8;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D";
            task.status = 6;
            return _context6.abrupt("return", false);

          case 8:
            _context6.next = 10;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/statement/export/task/list"), 'post', {
              page: 1,
              size: 50
            });

          case 10:
            res = _context6.sent;

            if (!(res && res.success && res.result)) {
              _context6.next = 41;
              break;
            }

            list = res.result.export_task_list || []; // 为当前查询重新规范化结束时间（拉取一次 time 接口），确保与生成时使用的结束时间一致

            _context6.next = 15;
            return resolveReportEndTime(task);

          case 15:
            normalizedEnd = _context6.sent;
            if (typeof normalizedEnd === 'number') task.endCreateTime = normalizedEnd;
            endCreateTime = typeof task.endCreateTime === 'number' ? task.endCreateTime : normalizedEnd !== null && normalizedEnd !== void 0 ? normalizedEnd : (_task$report_custom_d4 = task.report_custom_datetime_end_local) !== null && _task$report_custom_d4 !== void 0 ? _task$report_custom_d4 : task.report_custom_datetime_end;
            find = list.find(function (item) {
              var _task$report_custom_d5;

              // temu后台报告记录有可能存在时间段非12:00:00-11:59:59的记录，所以需要判断是否是同一天，同一天则不需要重新去生成
              var isStartSameDay = moment_default()(item.start_time_stamp).isSame((_task$report_custom_d5 = task.report_custom_datetime_start_local) !== null && _task$report_custom_d5 !== void 0 ? _task$report_custom_d5 : task.report_custom_datetime_start, 'day');
              var isEndSameDay = moment_default()(item.end_time_stamp).isSame(endCreateTime, 'day');
              return isStartSameDay && isEndSameDay && item.create_time_stamp > Date.now() - 24 * 60 * 60 * 1000;
            });

            if (!find) {
              _context6.next = 36;
              break;
            }

            _context6.t0 = find.status;
            _context6.next = _context6.t0 === 1 ? 23 : 26;
            break;

          case 23:
            task.status = 2;
            task.flow_id = find.flow_id;
            return _context6.abrupt("return", true);

          case 26:
            task.status = 6;
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context6.next = 31;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 31:
            _context6.next = 33;
            return getLocalTemuReport_awaitReportDownload(task, ++count);

          case 33:
            return _context6.abrupt("return", _context6.sent);

          case 34:
            _context6.next = 39;
            break;

          case 36:
            task.status = 6;
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D----not find";
            log["a" /* default */].setLog(task.msg);

          case 39:
            _context6.next = 44;
            break;

          case 41:
            task.status = 6;
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D";
            log["a" /* default */].setLog(task.msg);

          case 44:
            _context6.next = 51;
            break;

          case 46:
            _context6.prev = 46;
            _context6.t1 = _context6["catch"](1);
            task.status = 6;
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context6.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 51:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[1, 46]]);
  }));

  return function awaitReportDownload(_x6) {
    return _ref6.apply(this, arguments);
  };
}(); // 获取下载报表链接


var getLocalTemuReport_getReportUrl = /*#__PURE__*/function () {
  var _ref7 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee7(task) {
    var res;
    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            _context7.prev = 0;
            _context7.next = 3;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/statement/export/task/result"), 'post', {
              flowId: task.flow_id
            });

          case 3:
            res = _context7.sent;

            if (!(res.success && res.result)) {
              _context7.next = 9;
              break;
            }

            task.fileUrl = res.result.file_url;
            return _context7.abrupt("return", {
              fileUrl: res.result.file_url
            });

          case 9:
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(res.error_msg);
            log["a" /* default */].setLog(task.msg);

          case 12:
            _context7.next = 19;
            break;

          case 14:
            _context7.prev = 14;
            _context7.t0 = _context7["catch"](0);
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context7.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 19:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7, null, [[0, 14]]);
  }));

  return function getReportUrl(_x7) {
    return _ref7.apply(this, arguments);
  };
}(); // 下载报表


var getLocalTemuReport_downloadReport = /*#__PURE__*/function () {
  var _ref8 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee8(task) {
    var res, name, oFile, fileRes, zip;
    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            _context8.prev = 0;
            _context8.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context8.sent;

            if (!(res && res.data)) {
              _context8.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context8.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context8.abrupt("return", fileRes);

          case 16:
            _context8.next = 23;
            break;

          case 18:
            _context8.prev = 18;
            _context8.t0 = _context8["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\u201C\u91CD\u65B0\u83B7\u53D6\u201D\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context8.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee8, null, [[0, 18]]);
  }));

  return function downloadReport(_x8) {
    return _ref8.apply(this, arguments);
  };
}();

var getLocalTemuReport = /*#__PURE__*/function () {
  var _ref9 = getLocalTemuReport_asyncToGenerator( /*#__PURE__*/getLocalTemuReport_regeneratorRuntime().mark(function _callee9(task) {
    var timeRes, param, res, uploadRes;
    return getLocalTemuReport_regeneratorRuntime().wrap(function _callee9$(_context9) {
      while (1) {
        switch (_context9.prev = _context9.next) {
          case 0:
            _context9.next = 2;
            return toGetReportSelectMaxTime(task);

          case 2:
            timeRes = _context9.sent;

            if (timeRes) {
              _context9.next = 5;
              break;
            }

            return _context9.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 5:
            // 先根据区域转换时间为当地时间戳（起始00:00:00，结束23:59:59）
            getLocalTemuReport_convertLocalDateRange(task); // 如果还未生成过，并且找历史导出列表也没有，那就生成一次

            _context9.t0 = task.status !== 6;

            if (!_context9.t0) {
              _context9.next = 11;
              break;
            }

            _context9.next = 10;
            return getLocalTemuReport_awaitReportDownload(task);

          case 10:
            _context9.t0 = !_context9.sent;

          case 11:
            if (!_context9.t0) {
              _context9.next = 16;
              break;
            }

            _context9.next = 14;
            return getLocalTemuReport_generateReport(task);

          case 14:
            if (_context9.sent) {
              _context9.next = 16;
              break;
            }

            return _context9.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 16:
            _context9.t1 = task.status !== 2;

            if (!_context9.t1) {
              _context9.next = 21;
              break;
            }

            _context9.next = 20;
            return getLocalTemuReport_awaitReportDownload(task);

          case 20:
            _context9.t1 = !_context9.sent;

          case 21:
            if (!_context9.t1) {
              _context9.next = 23;
              break;
            }

            return _context9.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 23:
            _context9.next = 25;
            return getLocalTemuReport_getReportUrl(task);

          case 25:
            if (_context9.sent) {
              _context9.next = 27;
              break;
            }

            return _context9.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 27:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context9.next = 30;
            return getLocalTemuReport_downloadReport(task);

          case 30:
            res = _context9.sent;

            if (!(res && res.file)) {
              _context9.next = 41;
              break;
            }

            _context9.next = 34;
            return Object(util["L" /* uploadFile */])(res.file);

          case 34:
            uploadRes = _context9.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context9.next = 38;
              break;
            }

            return _context9.abrupt("return", getLocalTemuReport_objectSpread(getLocalTemuReport_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 38:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 41:
            if (![8, 12].includes(task.status)) {
              _context9.next = 44;
              break;
            }

            task.isDelete = true;
            return _context9.abrupt("return", getLocalTemuReport_objectSpread(getLocalTemuReport_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 44:
            return _context9.abrupt("return", getLocalTemuReport_objectSpread(getLocalTemuReport_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 45:
          case "end":
            return _context9.stop();
        }
      }
    }, _callee9);
  }));

  return function getLocalTemuReport(_x9) {
    return _ref9.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getLocalTemuReport = (getLocalTemuReport);
// CONCATENATED MODULE: ./src/platform/temu/qtReport/getSettlementData.js
function getSettlementData_typeof(obj) { "@babel/helpers - typeof"; return getSettlementData_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; }, getSettlementData_typeof(obj); }

function getSettlementData_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getSettlementData_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getSettlementData_ownKeys(Object(source), !0).forEach(function (key) { getSettlementData_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getSettlementData_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getSettlementData_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getSettlementData_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getSettlementData_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" == getSettlementData_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 getSettlementData_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getSettlementData_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getSettlementData_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getSettlementData_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }






 // 根据report_type获取settleDataType
// 504, 505, 506 → 待处理款项 settleDataType: 1
// 507, 508, 509 → 结算中款项 settleDataType: 2

var getSettleDataType = function getSettleDataType(reportType) {
  if ([504, 505, 506].includes(reportType)) return 1;
  if ([507, 508, 509].includes(reportType)) return 2;
  return 1;
}; // 根据report_type获取英文中心host


var getSettlementData_getHost = function getHost(reportType) {
  return {
    504: temu["h" /* temu */].cbGlobalHost,
    505: temu["h" /* temu */].cbUsHost,
    506: temu["h" /* temu */].cbEuHost,
    507: temu["h" /* temu */].cbGlobalHost,
    508: temu["h" /* temu */].cbUsHost,
    509: temu["h" /* temu */].cbEuHost
  }[reportType];
};

var getSettlementData_generateReport = /*#__PURE__*/function () {
  var _ref = getSettlementData_asyncToGenerator( /*#__PURE__*/getSettlementData_regeneratorRuntime().mark(function _callee(task, host) {
    var settleDataType, changeStoreId, _yield$nativeRequest, success, errorCode, errorMsg, msg;

    return getSettlementData_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            settleDataType = getSettleDataType(task.report_type);
            changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            _context.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export"), 'post', {
              settleDataType: settleDataType,
              taskType: 12
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: changeStoreId
            });

          case 5:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorCode = _yield$nativeRequest.errorCode;
            errorMsg = _yield$nativeRequest.errorMsg;

            if (!success) {
              _context.next = 15;
              break;
            }

            log["a" /* default */].setLog('结算数据报表生成成功');
            task.status = 6;
            return _context.abrupt("return", true);

          case 15:
            if (!(errorCode == 2000000)) {
              _context.next = 18;
              break;
            }

            task.status = 6;
            return _context.abrupt("return", true);

          case 18:
            if (!(errorCode == 3000000)) {
              _context.next = 20;
              break;
            }

            return _context.abrupt("return", 'needSplit');

          case 20:
            msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            task.status = 3;
            log["a" /* default */].setLog(msg);
            task.msg = msg;

          case 24:
            _context.next = 32;
            break;

          case 26:
            _context.prev = 26;
            _context.t0 = _context["catch"](0);
            task.status = 3;
            task.msg = "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 32:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 26]]);
  }));

  return function generateReport(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}(); // 查询报表生成状态


var getSettlementData_awaitReportDownload = /*#__PURE__*/function () {
  var _ref2 = getSettlementData_asyncToGenerator( /*#__PURE__*/getSettlementData_regeneratorRuntime().mark(function _callee2(task, host) {
    var count,
        changeStoreId,
        res,
        list,
        settleDataType,
        find,
        _args2 = arguments;
    return getSettlementData_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : 0;
            _context2.prev = 1;

            if (!(count >= 5)) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D";
            return _context2.abrupt("return", false);

          case 7:
            changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            _context2.next = 10;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export/history/page"), 'post', {
              pageNum: 1,
              pageSize: 50,
              taskType: 12
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: changeStoreId
            });

          case 10:
            res = _context2.sent;

            if (!(res && res.result)) {
              _context2.next = 35;
              break;
            }

            list = res.result.merchantMerchantFileExportHistoryList;
            settleDataType = getSettleDataType(task.report_type);
            find = list.find(function (item) {
              // 只获取一小时内生成的报表
              var taskFinishedTime = new Date(item.taskFinishedTime).getTime();
              return item.settleDataType == settleDataType && taskFinishedTime > Date.now() - 1 * 60 * 60 * 1000;
            });

            if (!find) {
              _context2.next = 31;
              break;
            }

            _context2.t0 = find.status;
            _context2.next = _context2.t0 === 2 ? 19 : _context2.t0 === 1 ? 22 : 22;
            break;

          case 19:
            task.status = 2;
            task.downloadId = find.id;
            return _context2.abrupt("return", true);

          case 22:
            task.msg = '文件正在生成中';
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context2.next = 26;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 26:
            _context2.next = 28;
            return getSettlementData_awaitReportDownload(task, host, ++count);

          case 28:
            return _context2.abrupt("return", _context2.sent);

          case 29:
            _context2.next = 33;
            break;

          case 31:
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25----not find\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"";
            log["a" /* default */].setLog(task.msg);

          case 33:
            _context2.next = 37;
            break;

          case 35:
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CTemu\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"";
            log["a" /* default */].setLog(task.msg);

          case 37:
            _context2.next = 43;
            break;

          case 39:
            _context2.prev = 39;
            _context2.t1 = _context2["catch"](1);
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t1, task));
            log["a" /* default */].setLog(task.msg);

          case 43:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 39]]);
  }));

  return function awaitReportDownload(_x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取下载报表链接


var getSettlementData_getReportUrl = /*#__PURE__*/function () {
  var _ref3 = getSettlementData_asyncToGenerator( /*#__PURE__*/getSettlementData_regeneratorRuntime().mark(function _callee3(task, host) {
    var changeStoreId, res;
    return getSettlementData_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            changeStoreId = "".concat(task.real_mall_id, "&").concat(task.siteId);
            _context3.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(host, "/api/merchant/file/export/download"), 'post', {
              id: task.downloadId,
              taskType: 12
            }, {
              Mallid: task.real_mall_id,
              changeStoreId: changeStoreId
            });

          case 4:
            res = _context3.sent;

            if (!(res.success && res.result)) {
              _context3.next = 10;
              break;
            }

            task.fileUrl = res.result.fileUrl;
            return _context3.abrupt("return", {
              fileUrl: res.result.fileUrl
            });

          case 10:
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(res.errorMsg);
            log["a" /* default */].setLog(task.msg);

          case 13:
            _context3.next = 20;
            break;

          case 15:
            _context3.prev = 15;
            _context3.t0 = _context3["catch"](0);
            task.status = 9;
            task.msg = "\u83B7\u53D6\u4E0B\u8F7D\u62A5\u8868\u94FE\u63A5\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 20:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 15]]);
  }));

  return function getReportUrl(_x5, _x6) {
    return _ref3.apply(this, arguments);
  };
}(); // 下载报表


var getSettlementData_downloadReport = /*#__PURE__*/function () {
  var _ref4 = getSettlementData_asyncToGenerator( /*#__PURE__*/getSettlementData_regeneratorRuntime().mark(function _callee4(task) {
    var res, name, oFile, fileRes, zip;
    return getSettlementData_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.fileUrl,
              responseType: 'blob'
            });

          case 3:
            res = _context4.sent;

            if (!(res && res.data)) {
              _context4.next = 16;
              break;
            }

            name = Object(util["q" /* getNameByUrl */])(task.fileUrl);
            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context4.next = 12;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              compressionOptions: {
                level: 9
              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 12:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context4.abrupt("return", fileRes);

          case 16:
            _context4.next = 23;
            break;

          case 18:
            _context4.prev = 18;
            _context4.t0 = _context4["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u539F\u59CB\u9875\u9762\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);

          case 23:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 18]]);
  }));

  return function downloadReport(_x7) {
    return _ref4.apply(this, arguments);
  };
}();

var getSettlementData = /*#__PURE__*/function () {
  var _ref5 = getSettlementData_asyncToGenerator( /*#__PURE__*/getSettlementData_regeneratorRuntime().mark(function _callee5(task) {
    var host, backUp, loginRes, generateReportRes, param, res, uploadRes;
    return getSettlementData_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            host = getSettlementData_getHost(task.report_type); // 登录英文中心

            backUp = getSettlementData_objectSpread(getSettlementData_objectSpread({}, task), {}, {
              host: host
            });
            _context5.next = 4;
            return Object(temu["g" /* loginCb */])(backUp);

          case 4:
            loginRes = _context5.sent;

            if (loginRes) {
              _context5.next = 10;
              break;
            }

            task.msg = '切换到对应站点失败，请检查';
            task.status = 11;
            log["a" /* default */].setLog(task.msg);
            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 10:
            _context5.next = 12;
            return getSettlementData_awaitReportDownload(task, host);

          case 12:
            if (_context5.sent) {
              _context5.next = 21;
              break;
            }

            _context5.next = 15;
            return getSettlementData_generateReport(task, host);

          case 15:
            generateReportRes = _context5.sent;

            if (generateReportRes) {
              _context5.next = 18;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 18:
            if (!(generateReportRes == 'needSplit')) {
              _context5.next = 21;
              break;
            }

            log["a" /* default */].setLog('当前报表数据量太多，需要拆分');
            return _context5.abrupt("return", {
              code: 4,
              msg: '当前报表数据量太多，需要拆分'
            });

          case 21:
            _context5.t0 = task.status !== 2;

            if (!_context5.t0) {
              _context5.next = 26;
              break;
            }

            _context5.next = 25;
            return getSettlementData_awaitReportDownload(task, host);

          case 25:
            _context5.t0 = !_context5.sent;

          case 26:
            if (!_context5.t0) {
              _context5.next = 28;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 28:
            _context5.next = 30;
            return getSettlementData_getReportUrl(task, host);

          case 30:
            if (_context5.sent) {
              _context5.next = 32;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 32:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context5.next = 35;
            return getSettlementData_downloadReport(task);

          case 35:
            res = _context5.sent;

            if (!(res && res.file)) {
              _context5.next = 46;
              break;
            }

            _context5.next = 39;
            return Object(util["L" /* uploadFile */])(res.file);

          case 39:
            uploadRes = _context5.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context5.next = 43;
              break;
            }

            return _context5.abrupt("return", getSettlementData_objectSpread(getSettlementData_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 43:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 46:
            return _context5.abrupt("return", getSettlementData_objectSpread(getSettlementData_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 47:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getSettlementData(_x8) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport_getSettlementData = (getSettlementData);
// CONCATENATED MODULE: ./src/platform/temu/qtReport/index.js
function qtReport_typeof(obj) { "@babel/helpers - typeof"; return qtReport_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; }, qtReport_typeof(obj); }

function qtReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ qtReport_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" == qtReport_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 qtReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function qtReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? qtReport_ownKeys(Object(source), !0).forEach(function (key) { qtReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : qtReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function qtReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = qtReport_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function qtReport_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return qtReport_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 qtReport_arrayLikeToArray(o, minLen); }

function qtReport_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; }

function qtReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function qtReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { qtReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { qtReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

//     Temu_SETTLEMENT_REPORT(5, "Temu全托管结算报告"),
//     Temu_BILLDETAILS_REPORT(51, "Temu全托管账务明细"),
//     Temu_DEDUCTION_1(52, "Temu全托管支出详情1"),
//     Temu_DEDUCTION_2(53, "Temu全托管支出详情2"),
//     Temu_DEDUCTION_3(54, "Temu全托管支出详情3"),
//     Temu_DEDUCTION_4(55, "Temu全托管支出详情4"),
//     Temu_DEDUCTION_5(56, "Temu全托管支出详情5"),
//     Temu_DEDUCTION_6(57, "Temu全托管支出详情6"),
//     Temu_DEDUCTION_7(58, "Temu全托管支出详情7"),
//     Temu_ERPFEE_1(59, "Temu全托管ERP费用1"),
//     Temu_ERPFEE_2(510, "Temu全托管ERP费用2"),
//     Temu_ERPFEE_3(511, "Temu全托管ERP费用3"),
//     Temu_ERPFEE_4(512, "Temu全托管ERP费用4"),











var BillDetailsReportType = [5, // 全球
51, // 跨境中文中心
502, // 欧区
503, // 美区
504, // 全球 - 待处理款项
505, // 美区 - 待处理款项
506, // 欧区 - 待处理款项
507, // 全球 - 结算中款项
508, // 美区 - 结算中款项
509 // 欧区 - 结算中款项
];
var DeductionReportType = [52, // 消费者及履约保障-售后问题
53, // 备货违规 - 发货履约保障-延迟发货
54, // 备货违规 - 发货履约保障-延迟到货
55, // 备货违规 - 发货履约保障-缺货
56, // 备货违规 - 商品品质保障-质量问题(JIT商品)
57, // 备货违规 - 商品品质保障-质量问题(定制商品)
58, // 质量事故违规
521 // 仓储增值服务-贴标费
];
var EPRReportType = [59, // Temu全托管ERP费用1
510, // Temu全托管ERP费用2
511, // Temu全托管ERP费用3
512, // Temu全托管ERP费用4
513 // Temu全托管ERP费用5
];
var SemiBillDetailsReportType = [1, // 跨境中文中心
101, // 全球
102, // 欧区
103 // 美区
];
var StmlReportType = [1101, // 欧区
1102 // 美区
];
var ReverseReportType = [1201, // 欧区商家仓
1202, // 美区商家仓
1301, // 欧区Temu仓
1302 // 美区Temu仓
];
var PoDetailType = [201, // 全球
202, // 欧区
203 // 美区
];
var LocalTemuReportType = [6 // Temu本土交易报告
];
var reportIntroMap = {
  5: '全球',
  51: '商家中心',
  502: '欧区',
  503: '美区',
  52: '消费者及履约保障-售后问题',
  53: '备货违规 - 发货履约保障-延迟发货',
  54: '备货违规 - 发货履约保障-延迟到货',
  55: '备货违规 - 发货履约保障-缺货',
  56: '备货违规 - 商品品质保障-质量问题(JIT商品)',
  57: '备货违规 - 商品品质保障-质量问题(定制商品)',
  58: '质量事故违规',
  521: '仓储增值服务-贴标费',
  59: 'Temu全托管ERP费用1',
  510: 'Temu全托管ERP费用2',
  511: 'Temu全托管ERP费用3',
  512: 'Temu全托管ERP费用4',
  513: 'Temu全托管ERP费用5',
  1: '商家中心',
  101: '全球',
  102: '欧区',
  103: '美区',
  1101: '欧区',
  1102: '美区',
  1201: '欧区商家仓',
  1202: '美区商家仓',
  1301: '欧区Temu仓',
  1302: '美区Temu仓',
  201: '全球',
  202: '欧区',
  203: '美区'
};

var qtReport_splitTimeRange = function splitTimeRange(start, end) {
  var startTime = Number(start);
  var endTime = Number(end);
  var midTime = Math.floor((startTime + endTime) / 2);
  return [{
    start: startTime,
    end: midTime,
    // 用moment将时间戳转换成北京时间YYYY-MM-DD格式输出
    formatStart: moment_default.a.tz(startTime, 'x', 'Asia/Shanghai').format('YYYY-MM-DD'),
    formatEnd: moment_default.a.tz(midTime, 'x', 'Asia/Shanghai').format('YYYY-MM-DD')
  }, {
    start: midTime + 1,
    end: endTime,
    formatStart: moment_default.a.tz(midTime + 1, 'x', 'Asia/Shanghai').format('YYYY-MM-DD'),
    formatEnd: moment_default.a.tz(endTime, 'x', 'Asia/Shanghai').format('YYYY-MM-DD')
  }];
};

var executeWithSplit = /*#__PURE__*/function () {
  var _ref = qtReport_asyncToGenerator( /*#__PURE__*/qtReport_regeneratorRuntime().mark(function _callee(task, handleFunc, depth) {
    var res, _mergedList$map, ranges, subResults, _iterator, _step, range, subTask, subRes, failedResult, mergedList;

    return qtReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return handleFunc(task);

          case 2:
            res = _context.sent;

            if (!(res.code === 4 && depth < 2)) {
              _context.next = 32;
              break;
            }

            ranges = qtReport_splitTimeRange(task.report_custom_datetime_start, task.report_custom_datetime_end);
            subResults = [];
            _iterator = _createForOfIteratorHelper(ranges);
            _context.prev = 7;

            _iterator.s();

          case 9:
            if ((_step = _iterator.n()).done) {
              _context.next = 19;
              break;
            }

            range = _step.value;
            log["a" /* default */].setLog('拆分时间范围', "\u5F00\u59CB\u65F6\u95F4\uFF1A".concat(range.formatStart, "\uFF0C\u7ED3\u675F\u65F6\u95F4\uFF1A").concat(range.formatEnd));
            subTask = qtReport_objectSpread(qtReport_objectSpread({}, task), {}, {
              report_custom_datetime_start: range.start,
              report_custom_datetime_end: range.end,
              report_custom_date_start: range.formatStart,
              report_custom_date_end: range.formatEnd,
              reportId: null
            });
            _context.next = 15;
            return executeWithSplit(subTask, handleFunc, depth + 1);

          case 15:
            subRes = _context.sent;
            subResults.push(subRes);

          case 17:
            _context.next = 9;
            break;

          case 19:
            _context.next = 24;
            break;

          case 21:
            _context.prev = 21;
            _context.t0 = _context["catch"](7);

            _iterator.e(_context.t0);

          case 24:
            _context.prev = 24;

            _iterator.f();

            return _context.finish(24);

          case 27:
            failedResult = subResults.find(function (r) {
              return r.code !== 0;
            });

            if (!failedResult) {
              _context.next = 30;
              break;
            }

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

          case 30:
            mergedList = subResults.flatMap(function (r) {
              return r.result || [];
            });
            return _context.abrupt("return", {
              code: 0,
              msg: '',
              result: {
                coskey: (_mergedList$map = mergedList.map(function (_ref2) {
                  var cosKey = _ref2.cosKey;
                  return cosKey;
                })) === null || _mergedList$map === void 0 ? void 0 : _mergedList$map.join(',')
              }
            });

          case 32:
            return _context.abrupt("return", res);

          case 33:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[7, 21, 24, 27]]);
  }));

  return function executeWithSplit(_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}();

var SettlementDataTypes = [504, 505, 506, 507, 508, 509]; // 获取财务任务公共方法

var commonGetReport = /*#__PURE__*/function () {
  var _ref3 = qtReport_asyncToGenerator( /*#__PURE__*/qtReport_regeneratorRuntime().mark(function _callee2(task, type) {
    var handleFunc, res, reportIntro;
    return qtReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            handleFunc = type === 'billDetails' && SettlementDataTypes.includes(task.report_type) ? qtReport_getSettlementData : {
              billDetails: qtReport_getBillDetailsReport,
              deduction: qtReport_getDeductionReport,
              epr: qtReport_getEPRReport,
              semiBillDetails: qtReport_getTemuReport,
              stmlReport: qtReport_getStmlReport,
              reverseReport: qtReport_getReverseReport,
              poDetail: qtReport_getPoDetail,
              localTemuReport: qtReport_getLocalTemuReport
            }[type];
            _context2.next = 3;
            return executeWithSplit(task, handleFunc, 0);

          case 3:
            res = _context2.sent;
            reportIntro = reportIntroMap[task.report_type];
            return _context2.abrupt("return", qtReport_objectSpread({
              reportType: task.report_type,
              msg: (reportIntro ? "[".concat(reportIntro, "]") : '') + (res.msg || ''),
              code: res.code
            }, res.result || {}));

          case 6:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));

  return function commonGetReport(_x4, _x5) {
    return _ref3.apply(this, arguments);
  };
}(); // 公共处理方法


var commonHandleReport = /*#__PURE__*/function () {
  var _ref4 = qtReport_asyncToGenerator( /*#__PURE__*/qtReport_regeneratorRuntime().mark(function _callee3(task, type) {
    var res, taskCache, typeList, _iterator2, _step2, _loop, _ret, index, errTask, errRes;

    return qtReport_regeneratorRuntime().wrap(function _callee3$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            res = task.resCache ? task.resCache : {
              code: 0,
              msg: '',
              result: []
            };
            taskCache = [];
            typeList = {
              billDetails: BillDetailsReportType,
              deduction: DeductionReportType,
              epr: EPRReportType,
              semiBillDetails: SemiBillDetailsReportType,
              stmlReport: StmlReportType,
              reverseReport: ReverseReportType,
              poDetail: PoDetailType,
              localTemuReport: LocalTemuReportType
            }[type];
            _iterator2 = _createForOfIteratorHelper(typeList);
            _context4.prev = 4;
            _loop = /*#__PURE__*/qtReport_regeneratorRuntime().mark(function _loop() {
              var reportType, findIndex, newTask, _res;

              return qtReport_regeneratorRuntime().wrap(function _loop$(_context3) {
                while (1) {
                  switch (_context3.prev = _context3.next) {
                    case 0:
                      reportType = _step2.value;
                      findIndex = res.result.findIndex(function (res) {
                        return res.reportType === reportType;
                      });

                      if (!(findIndex !== -1 && res.result[findIndex].code === 0)) {
                        _context3.next = 6;
                        break;
                      }

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

                    case 6:
                      newTask = qtReport_objectSpread(qtReport_objectSpread({}, task), {}, {
                        report_type: reportType
                      });
                      taskCache.push(newTask);
                      _context3.next = 10;
                      return commonGetReport(newTask, type);

                    case 10:
                      _res = _context3.sent;

                      if (findIndex !== -1) {
                        res.result[findIndex] = _res;
                      } else {
                        res.result.push(_res);
                      }

                    case 12:
                    case "end":
                      return _context3.stop();
                  }
                }
              }, _loop);
            });

            _iterator2.s();

          case 7:
            if ((_step2 = _iterator2.n()).done) {
              _context4.next = 14;
              break;
            }

            return _context4.delegateYield(_loop(), "t0", 9);

          case 9:
            _ret = _context4.t0;

            if (!(_ret === "continue")) {
              _context4.next = 12;
              break;
            }

            return _context4.abrupt("continue", 12);

          case 12:
            _context4.next = 7;
            break;

          case 14:
            _context4.next = 19;
            break;

          case 16:
            _context4.prev = 16;
            _context4.t1 = _context4["catch"](4);

            _iterator2.e(_context4.t1);

          case 19:
            _context4.prev = 19;

            _iterator2.f();

            return _context4.finish(19);

          case 22:
            // 找出第一个获取失败的报表
            index = res.result.findIndex(function (_ref5) {
              var code = _ref5.code;
              return code !== 0;
            });

            if (index !== -1) {
              errTask = taskCache[index];
              errRes = res.result[index];
              res.msg = errRes.msg;
              res.code = errRes.code;
              task.status = errTask.status;
              task.msg = errRes.msg;
              task.error_time = errTask.error_time; // 缓存获取成功的报表

              task.resCache = res;
            } else {
              // 全部获取成功
              res.code = 0;
              res.msg = '';
            }

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

          case 25:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee3, null, [[4, 16, 19, 22]]);
  }));

  return function commonHandleReport(_x6, _x7) {
    return _ref4.apply(this, arguments);
  };
}();

var getQtReport = /*#__PURE__*/function () {
  var _ref6 = qtReport_asyncToGenerator( /*#__PURE__*/qtReport_regeneratorRuntime().mark(function _callee4(task) {
    return qtReport_regeneratorRuntime().wrap(function _callee4$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.t0 = +task.type_id;
            _context5.next = _context5.t0 === 22006 ? 3 : _context5.t0 === 22015 ? 4 : _context5.t0 === 22009 ? 5 : _context5.t0 === 22003 ? 6 : _context5.t0 === 22005 ? 7 : _context5.t0 === 22004 ? 8 : _context5.t0 === 22018 ? 9 : _context5.t0 === 22019 ? 10 : 11;
            break;

          case 3:
            return _context5.abrupt("return", commonHandleReport(task, 'billDetails'));

          case 4:
            return _context5.abrupt("return", commonHandleReport(task, 'deduction'));

          case 5:
            return _context5.abrupt("return", commonHandleReport(task, 'epr'));

          case 6:
            return _context5.abrupt("return", commonHandleReport(task, 'semiBillDetails'));

          case 7:
            return _context5.abrupt("return", commonHandleReport(task, 'stmlReport'));

          case 8:
            return _context5.abrupt("return", commonHandleReport(task, 'reverseReport'));

          case 9:
            return _context5.abrupt("return", commonHandleReport(task, 'poDetail'));

          case 10:
            return _context5.abrupt("return", commonHandleReport(task, 'localTemuReport'));

          case 11:
            return _context5.abrupt("break", 12);

          case 12:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee4);
  }));

  return function getQtReport(_x8) {
    return _ref6.apply(this, arguments);
  };
}();

/* harmony default export */ var qtReport = (getQtReport);
// CONCATENATED MODULE: ./src/platform/temu/getTodaySaleVolume.js
function getTodaySaleVolume_typeof(obj) { "@babel/helpers - typeof"; return getTodaySaleVolume_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; }, getTodaySaleVolume_typeof(obj); }

function getTodaySaleVolume_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getTodaySaleVolume_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" == getTodaySaleVolume_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 getTodaySaleVolume_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getTodaySaleVolume_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getTodaySaleVolume_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getTodaySaleVolume_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





 // 获取销量列表的页数

var getTodaySaleVolume_$count = 40;
/**
 * @description 获取今日销量列表
 * @param {*} task 任务对象
 * @param {number} pageNo 页码
 * @param {number} retry 重试次数
 * @returns {Promise<{
 *   code: number,
 *   msg?: string,
 *   result?: {
 *     total: number,
 *     list: Array<{
 *       todaySaleVolume: number,
 *       supplierPrice: number,
 *       skuExtCode: string,
 *       productSkuId: number,
 *       currencyType: string
 *     }>,
 *     getDate: string
 *   },
 *   data?: {
 *     pageNo: number
 *   }
 * }>}
 */

var requestTodaySaleVolume = /*#__PURE__*/function () {
  var _ref = getTodaySaleVolume_asyncToGenerator( /*#__PURE__*/getTodaySaleVolume_regeneratorRuntime().mark(function _callee(task) {
    var pageNo,
        retry,
        _yield$nativeRequest,
        success,
        errorMsg,
        result,
        total,
        subOrderList,
        list,
        msg,
        _msg,
        _args = arguments;

    return getTodaySaleVolume_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            pageNo = _args.length > 1 && _args[1] !== undefined ? _args[1] : 1;
            retry = _args.length > 2 && _args[2] !== undefined ? _args[2] : 0;
            _context.prev = 2;
            _context.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/mms/venom/api/supplier/sales/management/listWarehouse"), // host需要改为 cbGLOBALhost
            'post', {
              pageNo: pageNo,
              pageSize: getTodaySaleVolume_$count,
              isLack: 0,
              priceAdjustRecentDays: 7,
              todaySaleVolumMin: 1,
              // sevenDaysSaleVolumMin: 1,
              advancedSort: {
                firstOrderByDesc: 1,
                firstOrderByParam: 'todaySaleVolume',
                secondOrderByDesc: 1,
                secondOrderByParam: 'todaySaleVolume'
              }
            }, {
              Mallid: task.platform_store_id
            });

          case 5:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            result = _yield$nativeRequest.result;

            if (!(success && result && result.subOrderList)) {
              _context.next = 18;
              break;
            }

            total = result.total, subOrderList = result.subOrderList;

            if (!(!subOrderList || !subOrderList.length)) {
              _context.next = 13;
              break;
            }

            return _context.abrupt("return", {
              code: 0,
              msg: '获取完毕'
            });

          case 13:
            list = []; // 数据收集

            subOrderList.forEach(function (_ref2) {
              var skuQuantityDetailList = _ref2.skuQuantityDetailList;

              if (skuQuantityDetailList.length) {
                skuQuantityDetailList.forEach(function (_ref3) {
                  var productSkuId = _ref3.productSkuId,
                      supplierPrice = _ref3.supplierPrice,
                      currencyType = _ref3.currencyType,
                      todaySaleVolume = _ref3.todaySaleVolume,
                      skuExtCode = _ref3.skuExtCode;
                  // if (todaySaleVolume > 0) {
                  list.push({
                    productSkuId: productSkuId,
                    supplierPrice: supplierPrice,
                    currencyType: currencyType,
                    todaySaleVolume: todaySaleVolume,
                    skuExtCode: skuExtCode
                  }); // }
                });
              }
            });
            return _context.abrupt("return", {
              code: 0,
              total: total,
              list: list
            });

          case 18:
            msg = "\u83B7\u53D6\u4ECA\u65E5\u9500\u91CF\u5217\u8868\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].report(msg, 'error', task.task_id);
            return _context.abrupt("return", {
              msg: msg,
              code: 1
            });

          case 21:
            _context.next = 33;
            break;

          case 23:
            _context.prev = 23;
            _context.t0 = _context["catch"](2);
            _msg = "\u83B7\u53D6\u4ECA\u65E5\u9500\u91CF\u5217\u8868\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(_msg); // 重试三次

            if (!(retry < 3)) {
              _context.next = 32;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context.next = 31;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 31:
            return _context.abrupt("return", requestTodaySaleVolume(task, pageNo, ++retry));

          case 32:
            return _context.abrupt("return", {
              msg: _msg,
              code: 2
            });

          case 33:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[2, 23]]);
  }));

  return function requestTodaySaleVolume(_x) {
    return _ref.apply(this, arguments);
  };
}();
/**
 * @description 获取所有今日销量数据
 * @param {*} task 任务对象
 * @param {number} pageNo 页码
 * @returns {Promise<{
 *   code: number,
 *   msg?: string,
 *   result?: {
 *     total: number,
 *     list: Array<{
 *       todaySaleVolume: number,
 *       supplierPrice: number,
 *       skuExtCode: string,
 *       productSkuId: number,
 *       currencyType: string
 *     }>,
 *     getDate: string
 *   }
 * }>}
 */


var getAllTodaySaleVolume = /*#__PURE__*/function () {
  var _ref4 = getTodaySaleVolume_asyncToGenerator( /*#__PURE__*/getTodaySaleVolume_regeneratorRuntime().mark(function _callee2(task) {
    var pageNo,
        _yield$requestTodaySa,
        code,
        msg,
        list,
        total,
        res,
        getDate,
        _args2 = arguments;

    return getTodaySaleVolume_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            pageNo = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : 1;
            _context2.next = 3;
            return requestTodaySaleVolume(task, pageNo);

          case 3:
            _yield$requestTodaySa = _context2.sent;
            code = _yield$requestTodaySa.code;
            msg = _yield$requestTodaySa.msg;
            list = _yield$requestTodaySa.list;
            total = _yield$requestTodaySa.total;

            if (!(code !== 0)) {
              _context2.next = 10;
              break;
            }

            return _context2.abrupt("return", {
              code: 4,
              // 重复任务上报4保证下次还能下发
              msg: msg
            });

          case 10:
            // 商品页总页数
            task.total = total; // 已获取页数

            task.curPage = pageNo * getTodaySaleVolume_$count; // 已获取销量的sku数

            task.currentNum = (task.currentNum || 0) + ((list === null || list === void 0 ? void 0 : list.length) || 0); // 获取当前北京时间

            _context2.next = 15;
            return Object(util["l" /* gateGet */])('api/v1/baseInfos', {}, 'task').catch(function () {});

          case 15:
            res = _context2.sent;
            getDate = res && res.data && res.data.time_format; // 判断是否获取完毕

            if (!(task.curPage < total)) {
              _context2.next = 23;
              break;
            }

            _context2.next = 20;
            return common_newTask["a" /* default */].uploadTask({
              code: 4,
              result: {
                currentNum: task.currentNum,
                curPage: task.curPage,
                total: total,
                list: list,
                getDate: getDate
              }
            }, task);

          case 20:
            _context2.next = 22;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 22:
            return _context2.abrupt("return", getAllTodaySaleVolume(task, ++pageNo));

          case 23:
            return _context2.abrupt("return", {
              code: 0,
              msg: msg,
              result: (list === null || list === void 0 ? void 0 : list.length) > 0 ? {
                list: list,
                getDate: getDate,
                currentNum: task.currentNum,
                curPage: task.curPage,
                total: total
              } : {
                list: [],
                getDate: getDate,
                currentNum: task.currentNum,
                curPage: task.curPage,
                total: total
              }
            });

          case 24:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));

  return function getAllTodaySaleVolume(_x2) {
    return _ref4.apply(this, arguments);
  };
}();
/**
 * @description 获取今日销量入口函数
 * @param {*} task 任务对象
 * @returns {Promise<{
 *   code: number,
 *   msg?: string,
 *   result?: {
 *     total: number,
 *     list: Array<{
 *       todaySaleVolume: number,
 *       supplierPrice: number,
 *       skuExtCode: string,
 *       productSkuId: number,
 *       currencyType: string
 *     }>,
 *     getDate: string
 *   }
 * }>}
 */


var getTodaySaleVolume = /*#__PURE__*/function () {
  var _ref5 = getTodaySaleVolume_asyncToGenerator( /*#__PURE__*/getTodaySaleVolume_regeneratorRuntime().mark(function _callee3(task) {
    var loginRes, msg, res;
    return getTodaySaleVolume_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            if (!(task.resCache && task.resCache.code === 0)) {
              _context3.next = 2;
              break;
            }

            return _context3.abrupt("return", task.resCache);

          case 2:
            _context3.next = 4;
            return Object(temu["g" /* loginCb */])(task);

          case 4:
            loginRes = _context3.sent;

            if (loginRes) {
              _context3.next = 10;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context3.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 10:
            _context3.next = 12;
            return getAllTodaySaleVolume(task);

          case 12:
            res = _context3.sent;
            task.status = [1, 2].indexOf(res.code) > -1 ? 14 : 15;
            task.msg = res.msg;
            return _context3.abrupt("return", res);

          case 16:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function getTodaySaleVolume(_x3) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var temu_getTodaySaleVolume = (getTodaySaleVolume);
// CONCATENATED MODULE: ./src/platform/temu/getActivityPrice.js
function getActivityPrice_typeof(obj) { "@babel/helpers - typeof"; return getActivityPrice_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; }, getActivityPrice_typeof(obj); }

function getActivityPrice_toConsumableArray(arr) { return getActivityPrice_arrayWithoutHoles(arr) || getActivityPrice_iterableToArray(arr) || getActivityPrice_unsupportedIterableToArray(arr) || getActivityPrice_nonIterableSpread(); }

function getActivityPrice_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getActivityPrice_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getActivityPrice_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getActivityPrice_arrayLikeToArray(arr); }

function getActivityPrice_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = getActivityPrice_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function getActivityPrice_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getActivityPrice_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 getActivityPrice_arrayLikeToArray(o, minLen); }

function getActivityPrice_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; }

function getActivityPrice_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getActivityPrice_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" == getActivityPrice_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 getActivityPrice_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getActivityPrice_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getActivityPrice_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getActivityPrice_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }



 // 获取活动列表的页数

var getActivityPrice_$count = 50;
/**
 * @description 获取报名记录列表-获取活动价
 * @param {*} task 任务对象
 * @param {number[]} ids skuId列表
 * @param {number} pageNo 页码
 * @param {number} retry 重试次数
 * @param {number} frequencyRetry 频率限制重试次数
 * @returns {Promise<{}>}
 */

var requestActivityPrice = /*#__PURE__*/function () {
  var _ref = getActivityPrice_asyncToGenerator( /*#__PURE__*/getActivityPrice_regeneratorRuntime().mark(function _callee(task, ids) {
    var pageNo,
        retry,
        frequencyRetry,
        _yield$nativeRequest,
        success,
        errorMsg,
        result,
        errorCode,
        total,
        list,
        _formatActivityData,
        res,
        isIn30Days,
        delaySeconds,
        msg,
        _msg,
        _msg2,
        _args = arguments;

    return getActivityPrice_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            pageNo = _args.length > 2 && _args[2] !== undefined ? _args[2] : 1;
            retry = _args.length > 3 && _args[3] !== undefined ? _args[3] : 0;
            frequencyRetry = _args.length > 4 && _args[4] !== undefined ? _args[4] : 0;
            _context.prev = 3;
            _context.next = 6;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/kiana/gamblers/marketing/enroll/list"), 'post', {
              pageNo: pageNo,
              pageSize: getActivityPrice_$count,
              productSkuIds: ids || []
            }, {
              Mallid: task.real_mall_id
            });

          case 6:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            result = _yield$nativeRequest.result;
            errorCode = _yield$nativeRequest.errorCode;

            if (!(success && result)) {
              _context.next = 19;
              break;
            }

            total = result.total, list = result.list;

            if (!(!list || !list.length)) {
              _context.next = 15;
              break;
            }

            return _context.abrupt("return", {
              code: 0,
              msg: '获取完毕'
            });

          case 15:
            _formatActivityData = getActivityPrice_formatActivityData(list, task), res = _formatActivityData.res, isIn30Days = _formatActivityData.isIn30Days;
            return _context.abrupt("return", {
              code: 0,
              total: total,
              list: res,
              isIn30Days: isIn30Days // 最后一项的报名时间是否在近30天内

            });

          case 19:
            if (!(errorCode === 2000000 && errorMsg.includes('Operation too frequent'))) {
              _context.next = 33;
              break;
            }

            if (!(frequencyRetry < 3)) {
              _context.next = 28;
              break;
            }

            delaySeconds = (frequencyRetry + 1) * 3; // 3秒、6秒、9秒

            log["a" /* default */].setLog("\u83B7\u53D6\u6D3B\u52A8\u4EF7---\u9891\u7387\u9650\u5236\u91CD\u8BD5\u7B2C".concat(frequencyRetry + 1, "\u6B21\uFF0C").concat(delaySeconds, "\u79D2\u540E\u91CD\u8BD5..."));
            _context.next = 25;
            return Object(util["h" /* delayed */])(delaySeconds * 1000);

          case 25:
            return _context.abrupt("return", requestActivityPrice(task, ids, pageNo, retry, ++frequencyRetry));

          case 28:
            // 频率限制重试次数用完，返回失败
            msg = "\u83B7\u53D6\u62A5\u540D\u8BB0\u5F55\u5217\u8868\u5931\u8D25-----\u7FFB\u9875\u8FC7\u4E8E\u9891\u7E41\uFF0C\u5DF2\u91CD\u8BD53\u6B21\u4ECD\u5931\u8D25";
            log["a" /* default */].setLog(msg);
            return _context.abrupt("return", {
              msg: msg,
              code: 1
            });

          case 31:
            _context.next = 36;
            break;

          case 33:
            _msg = "\u83B7\u53D6\u62A5\u540D\u8BB0\u5F55\u5217\u8868\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].report(_msg, 'error', task.task_id);
            return _context.abrupt("return", {
              msg: _msg,
              code: 1
            });

          case 36:
            _context.next = 48;
            break;

          case 38:
            _context.prev = 38;
            _context.t0 = _context["catch"](3);
            _msg2 = "\u83B7\u53D6\u62A5\u540D\u8BB0\u5F55\u5217\u8868\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(_msg2); // 重试三次

            if (!(retry < 3)) {
              _context.next = 47;
              break;
            }

            log["a" /* default */].setLog('获取活动价---正在重试........................');
            _context.next = 46;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 46:
            return _context.abrupt("return", requestActivityPrice(task, ids, pageNo, ++retry, frequencyRetry));

          case 47:
            return _context.abrupt("return", {
              msg: _msg2,
              code: 2
            });

          case 48:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[3, 38]]);
  }));

  return function requestActivityPrice(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}(); // 抽取上报数据结构


var getActivityPrice_formatActivityData = function formatActivityData(data, task) {
  var skuIds = task.skuIds || [];

  if (!Array.isArray(data)) {
    return {
      res: [],
      isIn30Days: false
    };
  }

  var isHalf = String(task.platform_code) !== '10022'; // 是否半托店铺（10022为全托，其他为半托）

  var now = Date.now();
  var THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;
  var res = [];
  var isIn30Days = true; // 映射报名结果 session 对象

  var mapSession = function mapSession(session) {
    if (!session) return null;
    return {
      sessionName: session.sessionName,
      sessionStatus: session.sessionStatus,
      sessionId: session.sessionId,
      siteName: session.siteName,
      siteId: session.siteId,
      startTime: session.startTime,
      endTime: session.endTime,
      startDateStr: session.startDateStr,
      endDateStr: session.endDateStr
    };
  };

  var _iterator = getActivityPrice_createForOfIteratorHelper(data),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _item$activityThemati, _item$activityTypeNam, _item$activityThemati2;

      var item = _step.value;

      // 判断是否在近30天内
      if (!item.enrollTime || now - item.enrollTime > THIRTY_DAYS) {
        // 由于数据是按时间倒序排列，后面的都更旧，直接停止循环
        log["a" /* default */].setLog("\u83B7\u53D6\u6D3B\u52A8\u4EF7---\u9047\u5230\u8D85\u8FC730\u5929\u7684\u6D3B\u52A8\u6570\u636E\uFF0C\u505C\u6B62\u83B7\u53D6\u540E\u7EED\u6570\u636E");
        isIn30Days = false;
        break;
      } // 处理 assignSessionList：半托店铺 map 所有项，全托店铺只取第一项


      var assignSessionList = item.assignSessionList || [];
      var processedAssignSessionList = void 0;

      if (isHalf) {
        // 半托店铺：map 所有项
        processedAssignSessionList = assignSessionList.map(mapSession).filter(function (session) {
          return session !== null;
        });
      } else {
        // 全托店铺：只取第一项
        var firstSession = assignSessionList[0] ? mapSession(assignSessionList[0]) : null;
        processedAssignSessionList = firstSession ? [firstSession] : [];
      }

      res.push({
        productId: item.productId,
        activityThematicName: (_item$activityThemati = item.activityThematicName) !== null && _item$activityThemati !== void 0 ? _item$activityThemati : '',
        activityTypeName: (_item$activityTypeNam = item.activityTypeName) !== null && _item$activityTypeNam !== void 0 ? _item$activityTypeNam : '',
        activityThematicId: (_item$activityThemati2 = item.activityThematicId) !== null && _item$activityThemati2 !== void 0 ? _item$activityThemati2 : null,
        enrollId: item.enrollId,
        assignSessionList: processedAssignSessionList,
        skcList: (item.skcList || []).map(function (skc) {
          return {
            skcId: skc.skcId,
            skuList: (skc.skuList || []).filter(function (sku) {
              return skuIds.map(String).includes(String(sku.skuId));
            }).flatMap(function (sku) {
              var _sku$activityDiscount;

              if (isHalf) {
                var siteList = Array.isArray(sku.sitePriceList) ? sku.sitePriceList : [];
                return siteList.map(function (siteItem) {
                  var _siteItem$activityDis, _siteItem$siteId, _siteItem$siteName;

                  return {
                    skuId: sku.skuId,
                    currency: sku.currency,
                    dailyPrice: siteItem === null || siteItem === void 0 ? void 0 : siteItem.dailyPrice,
                    activityPrice: siteItem === null || siteItem === void 0 ? void 0 : siteItem.activityPrice,
                    activityDiscount: (_siteItem$activityDis = siteItem === null || siteItem === void 0 ? void 0 : siteItem.activityDiscount) !== null && _siteItem$activityDis !== void 0 ? _siteItem$activityDis : null,
                    siteId: (_siteItem$siteId = siteItem === null || siteItem === void 0 ? void 0 : siteItem.siteId) !== null && _siteItem$siteId !== void 0 ? _siteItem$siteId : null,
                    siteName: (_siteItem$siteName = siteItem === null || siteItem === void 0 ? void 0 : siteItem.siteName) !== null && _siteItem$siteName !== void 0 ? _siteItem$siteName : null
                  };
                });
              }

              return [{
                skuId: sku.skuId,
                currency: sku.currency,
                dailyPrice: sku.dailyPrice,
                activityPrice: sku.activityPrice,
                activityDiscount: (_sku$activityDiscount = sku.activityDiscount) !== null && _sku$activityDiscount !== void 0 ? _sku$activityDiscount : null,
                siteId: null,
                siteName: null
              }];
            })
          };
        })
      });
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  return {
    res: res,
    isIn30Days: isIn30Days
  };
};
/**
 * @description 获取所有活动价数据
 * @param {*} task 任务对象
 * @param {number} pageNo 页码
 * @returns {Promise<{
 *   code: number,
 *   msg?: string,
 *   result?: {
 *     total: number,
 *     currentNum: number,
 *     curPage: number,
 *     list: Array<{
 *       activityThematicId: number,
 *       activityThematicName: string | null,
 *       activityTypeName: string,
 *       enrollStatus: number,
 *       enrollSessionIdList: Array<string>,
 *       sessionStatus: number,
 *       skuId: number,
 *       activityDiscount: number,
 *       activityPrice: number,
 *       currency: string,
 *     }>,
 *     getDate: string
 *   }
 * }>}
 */


var getAllActivityPrice = /*#__PURE__*/function () {
  var _ref2 = getActivityPrice_asyncToGenerator( /*#__PURE__*/getActivityPrice_regeneratorRuntime().mark(function _callee2(task) {
    var skuIds, succList, message, count, batchSkuIds, i, ids, _yield$getOneBatchAct, code, msg, result, timeRes, getDate;

    return getActivityPrice_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            skuIds = task.skuIds || []; // const failSkuIds = []

            succList = [];
            message = '';
            count = Math.ceil(skuIds.length / 50); // temu一次最多只能查50个skuid

            batchSkuIds = Array(count).fill(1).map(function (i, key) {
              return skuIds.slice(key * 50, (key + 1) * 50);
            });
            i = 0;

          case 6:
            if (!(i < batchSkuIds.length)) {
              _context2.next = 20;
              break;
            }

            ids = batchSkuIds[i]; // 等待5s

            _context2.next = 10;
            return Object(util["h" /* delayed */])(5 * 1000);

          case 10:
            _context2.next = 12;
            return getOneBatchActivityPrice(task, ids);

          case 12:
            _yield$getOneBatchAct = _context2.sent;
            code = _yield$getOneBatchAct.code;
            msg = _yield$getOneBatchAct.msg;
            result = _yield$getOneBatchAct.result;

            if (code === 0) {
              succList.push.apply(succList, getActivityPrice_toConsumableArray(result.list || []));
            } else {
              // failSkuIds.push(...ids)
              log["a" /* default */].setLog("\u83B7\u53D6\u7B2C".concat(i + 1, "\u6279\u6D3B\u52A8\u4EF7---\u83B7\u53D6\u5931\u8D25:").concat(msg));
            }

          case 17:
            i++;
            _context2.next = 6;
            break;

          case 20:
            message = succList.length > 0 ? '获取完毕' : "\u83B7\u53D6\u6240\u6709\u6D3B\u52A8\u4EF7---\u672A\u83B7\u53D6\u5230\u4EFB\u4F55\u6570\u636E,\u9700\u8981\u83B7\u53D6\u7684skuId:".concat(skuIds.join(','));
            log["a" /* default */].setLog(message);
            _context2.next = 24;
            return Object(util["l" /* gateGet */])('api/v1/baseInfos', {}, 'task').catch(function () {});

          case 24:
            timeRes = _context2.sent;
            getDate = timeRes && timeRes.data && timeRes.data.time_format;
            return _context2.abrupt("return", {
              code: 0,
              msg: message,
              result: {
                list: succList,
                total: succList.length || 0,
                // 用于保持结构，服务端不读取
                currentNum: succList.length || 0,
                // 用于保持结构，服务端不读取
                curPage: 1,
                // 用于保持结构，服务端不读取
                getDate: getDate || ''
              }
            });

          case 27:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));

  return function getAllActivityPrice(_x3) {
    return _ref2.apply(this, arguments);
  };
}();

var getOneBatchActivityPrice = /*#__PURE__*/function () {
  var _ref3 = getActivityPrice_asyncToGenerator( /*#__PURE__*/getActivityPrice_regeneratorRuntime().mark(function _callee3(task, ids) {
    var allResults, currentPage, total, isIn30Days, _yield$requestActivit, code, msg, list, pageTotal, pageIsIn30Days, curPage;

    return getActivityPrice_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            allResults = [];
            currentPage = 1;
            total = 0;
            isIn30Days = true;

          case 4:
            if (!isIn30Days) {
              _context3.next = 27;
              break;
            }

            _context3.next = 7;
            return requestActivityPrice(task, ids, currentPage);

          case 7:
            _yield$requestActivit = _context3.sent;
            code = _yield$requestActivit.code;
            msg = _yield$requestActivit.msg;
            list = _yield$requestActivit.list;
            pageTotal = _yield$requestActivit.total;
            pageIsIn30Days = _yield$requestActivit.isIn30Days;
            task.msg = msg;

            if (!(code !== 0)) {
              _context3.next = 16;
              break;
            }

            return _context3.abrupt("return", {
              code: code,
              msg: msg
            });

          case 16:
            // 更新总页数和30天标志
            total = pageTotal || 0;
            isIn30Days = pageIsIn30Days;

            if (list && list.length > 0) {
              allResults.push.apply(allResults, getActivityPrice_toConsumableArray(list));
            } // 判断是否还有下一页


            curPage = currentPage * getActivityPrice_$count;

            if (!(!isIn30Days || curPage >= total)) {
              _context3.next = 22;
              break;
            }

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

          case 22:
            _context3.next = 24;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 24:
            currentPage++;
            _context3.next = 4;
            break;

          case 27:
            // 更新任务状态
            task.total = total;
            task.curPage = currentPage * getActivityPrice_$count;
            task.currentNum = allResults.length || 0;
            return _context3.abrupt("return", {
              code: 0,
              msg: task.msg,
              result: {
                list: allResults
              }
            });

          case 31:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function getOneBatchActivityPrice(_x4, _x5) {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * @description 获取活动价入口函数
 * @param {*} task 任务对象
 * @returns {Promise<{
 *   code: number,
 *   msg?: string,
 *   result?: {
 *     total: number,
 *     currentNum: number,
 *     curPage: number,
 *     list: Array<{
 *       activityThematicId: number,
 *       activityThematicName: string | null,
 *       activityTypeName: string,
 *       sessionName: string | null,
 *       sessionStatus: number,
 *       skuId: number,
 *       activityDiscount: unknown,
 *       activityPrice: number,
 *       currency: string,
 *     }>,
 *     getDate: string
 *   }
 * }>}
 */


var getActivityPrice = /*#__PURE__*/function () {
  var _ref4 = getActivityPrice_asyncToGenerator( /*#__PURE__*/getActivityPrice_regeneratorRuntime().mark(function _callee4(task) {
    var loginRes, msg, res;
    return getActivityPrice_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            if (!(task.resCache && task.resCache.code === 0)) {
              _context4.next = 2;
              break;
            }

            return _context4.abrupt("return", task.resCache);

          case 2:
            _context4.next = 4;
            return Object(temu["g" /* loginCb */])(task);

          case 4:
            loginRes = _context4.sent;

            if (loginRes) {
              _context4.next = 10;
              break;
            }

            msg = '获取活动价---切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 10:
            _context4.next = 12;
            return getAllActivityPrice(task);

          case 12:
            res = _context4.sent;
            task.status = [1, 2].indexOf(res.code) > -1 ? 14 : 15;
            task.errorMsg = res.msg;
            return _context4.abrupt("return", res);

          case 16:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function getActivityPrice(_x6) {
    return _ref4.apply(this, arguments);
  };
}();

/* harmony default export */ var temu_getActivityPrice = (getActivityPrice);
// CONCATENATED MODULE: ./src/platform/temu/getGoodsTraffic.js
function getGoodsTraffic_toConsumableArray(arr) { return getGoodsTraffic_arrayWithoutHoles(arr) || getGoodsTraffic_iterableToArray(arr) || getGoodsTraffic_unsupportedIterableToArray(arr) || getGoodsTraffic_nonIterableSpread(); }

function getGoodsTraffic_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getGoodsTraffic_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getGoodsTraffic_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 getGoodsTraffic_arrayLikeToArray(o, minLen); }

function getGoodsTraffic_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getGoodsTraffic_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getGoodsTraffic_arrayLikeToArray(arr); }

function getGoodsTraffic_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; }

function getGoodsTraffic_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getGoodsTraffic_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getGoodsTraffic_ownKeys(Object(source), !0).forEach(function (key) { getGoodsTraffic_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getGoodsTraffic_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getGoodsTraffic_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getGoodsTraffic_typeof(obj) { "@babel/helpers - typeof"; return getGoodsTraffic_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; }, getGoodsTraffic_typeof(obj); }

function getGoodsTraffic_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getGoodsTraffic_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" == getGoodsTraffic_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 getGoodsTraffic_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getGoodsTraffic_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getGoodsTraffic_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getGoodsTraffic_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }






var getGoodsTraffic_$count = 20; // 50、80、100, 通常在第24个左右的请求就会被temu接口限流, 所以这里设置为20

var cooldownSteps = [10000, 15000, 20000]; // 连续多次429的额外冷却：10/15/20s

var RATE_LIMIT_BREAKER_THRESHOLD = 30; // detail接口连续命中限流的熔断阈值（一页数据的第一轮获取以及第一轮重试前10个共计30次，耗时大约12分钟）

var randDelay = function randDelay(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}; // 主体逻辑


var getGoodsTrafficList = /*#__PURE__*/function () {
  var _ref = getGoodsTraffic_asyncToGenerator( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee3(task) {
    var loginRes, _msg, _yield$requestGoodsTr, code, msg, pageNo, info, total, goodsTrafficList, failedSpuIds, successStreak, rateLimitStreak, i, currentItem, result, cooldown, _msg2, retryCount, currentFailedItems, _i, failedItem, retryItem, _result, _cooldown, _msg3, retryBackoff;

    return getGoodsTraffic_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            if (!task.isDelete) {
              _context3.next = 2;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: '任务已停止'
            });

          case 2:
            _context3.next = 4;
            return Object(temu["g" /* loginCb */])(task);

          case 4:
            loginRes = _context3.sent;

            if (loginRes) {
              _context3.next = 10;
              break;
            }

            _msg = '切换到美区或欧区站点失败，请检查';
            task.msg = _msg;
            log["a" /* default */].setLog(_msg);
            return _context3.abrupt("return", {
              code: 1,
              msg: _msg
            });

          case 10:
            _context3.next = 12;
            return requestGoodsTrafficList(task, task.pageNo || 1);

          case 12:
            _yield$requestGoodsTr = _context3.sent;
            code = _yield$requestGoodsTr.code;
            msg = _yield$requestGoodsTr.msg;
            pageNo = _yield$requestGoodsTr.pageNo;
            info = _yield$requestGoodsTr.info;
            total = _yield$requestGoodsTr.total;
            // 记录当前页数
            task.pageNo = pageNo; // 获取失败，上报状态

            if (!(code !== 0)) {
              _context3.next = 21;
              break;
            }

            return _context3.abrupt("return", {
              code: 2,
              msg: msg,
              data: {
                pageNo: pageNo
              }
            });

          case 21:
            goodsTrafficList = [];
            failedSpuIds = []; // 记录失败的spu项，用于失败重试

            successStreak = 0;
            rateLimitStreak = 0;
            i = 0;

          case 26:
            if (!(i < info.length)) {
              _context3.next = 73;
              break;
            }

            if (!task.isDelete) {
              _context3.next = 29;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: '任务已停止'
            });

          case 29:
            if (!(i > 0)) {
              _context3.next = 31;
              break;
            }

            return _context3.delegateYield( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee() {
              var delay;
              return getGoodsTraffic_regeneratorRuntime().wrap(function _callee$(_context) {
                while (1) {
                  switch (_context.prev = _context.next) {
                    case 0:
                      delay = void 0;

                      if (rateLimitStreak >= 2) {
                        delay = randDelay(5000, 8000); // 限流多次时加大间隔
                      } else if (rateLimitStreak === 1) {
                        delay = randDelay(4000, 6000);
                      } else if (successStreak >= 3) {
                        delay = randDelay(1500, 2500); // 连续成功时缩短间隔
                      } else {
                        delay = randDelay(2000, 3000);
                      }

                      _context.next = 4;
                      return new Promise(function (resolve) {
                        return setTimeout(resolve, delay);
                      });

                    case 4:
                    case "end":
                      return _context.stop();
                  }
                }
              }, _callee);
            })(), "t0", 31);

          case 31:
            // 获取当前项
            currentItem = info[i];
            _context3.prev = 32;
            _context3.next = 35;
            return requestGoodsDetail(task, currentItem);

          case 35:
            result = _context3.sent;

            if (!(result.code === 429)) {
              _context3.next = 50;
              break;
            }

            rateLimitStreak++;
            successStreak = 0;

            if (!result.rateLimitBreaker) {
              _context3.next = 41;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: result.msg,
              rateLimitBreaker: true
            });

          case 41:
            cooldown = rateLimitStreak >= 3 ? cooldownSteps[Math.min(rateLimitStreak - 3, cooldownSteps.length - 1)] : 0;

            if (!(cooldown > 0)) {
              _context3.next = 46;
              break;
            }

            log["a" /* default */].setLog("\u8FDE\u7EED".concat(rateLimitStreak, "\u6B21\u8FD4\u56DE429\uFF0C\u989D\u5916\u51B7\u5374").concat(cooldown / 1000, "s\uFF0C\u518D\u7EE7\u7EED\u5F53\u524D\u9875"));
            _context3.next = 46;
            return Object(util["h" /* delayed */])(cooldown);

          case 46:
            log["a" /* default */].setLog("\u7B2C ".concat(i + 1, " \u4E2A\u8BF7\u6C42\u9650\u6D41(429)\uFF0CspuId: ").concat((currentItem === null || currentItem === void 0 ? void 0 : currentItem.productId) || 'unknown')); // 计入失败列表，等待重试逻辑处理

            failedSpuIds.push({
              spuId: currentItem.productId,
              productName: currentItem.productName,
              siteId: currentItem.siteId,
              siteName: currentItem.siteName,
              category: currentItem.category || null,
              errorMsg: result.msg,
              retryCount: 0
            });
            _context3.next = 63;
            break;

          case 50:
            if (!(result.code !== 0)) {
              _context3.next = 59;
              break;
            }

            rateLimitStreak = 0;
            successStreak = 0;

            if (!result.rateLimitBreaker) {
              _context3.next = 55;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: result.msg,
              rateLimitBreaker: true
            });

          case 55:
            // 记录失败的spuid，保存完整信息用于重试
            if (currentItem && currentItem.productId) {
              failedSpuIds.push({
                spuId: currentItem.productId,
                productName: currentItem.productName,
                siteId: currentItem.siteId,
                siteName: currentItem.siteName,
                category: currentItem.category || null,
                errorMsg: result.msg,
                retryCount: 0
              });
            }

            log["a" /* default */].setLog("\u7B2C ".concat(i + 1, " \u4E2A\u8BF7\u6C42\u5931\u8D25: ").concat(result.msg, ", spuId: ").concat((currentItem === null || currentItem === void 0 ? void 0 : currentItem.productId) || 'unknown'));
            _context3.next = 63;
            break;

          case 59:
            rateLimitStreak = 0;
            successStreak++; // 收集成功的结果

            goodsTrafficList.push({
              productId: currentItem.productId,
              productName: currentItem.productName,
              siteId: currentItem.siteId,
              siteName: currentItem.siteName,
              category: currentItem.category || null,
              details: result.result || []
            });
            log["a" /* default */].setLog("\u7B2C ".concat(i + 1, " \u4E2A\u8BF7\u6C42\u6210\u529F: spuId: ").concat((currentItem === null || currentItem === void 0 ? void 0 : currentItem.productId) || 'unknown'));

          case 63:
            _context3.next = 70;
            break;

          case 65:
            _context3.prev = 65;
            _context3.t1 = _context3["catch"](32);
            _msg2 = "\u83B7\u53D6\u5546\u54C1\u8BE6\u60C5\u5931\u8D25---\u7B2C ".concat(i + 1, " \u4E2A\u8BF7\u6C42\u53D1\u751F\u5F02\u5E38: ").concat(Object(util["u" /* isError */])(_context3.t1, task));
            log["a" /* default */].setLog(_msg2);
            return _context3.abrupt("return", {
              code: 2,
              msg: _msg2
            });

          case 70:
            i++;
            _context3.next = 26;
            break;

          case 73:
            if (!(failedSpuIds.length > 0)) {
              _context3.next = 140;
              break;
            }

            log["a" /* default */].setLog("\u5F00\u59CB\u91CD\u8BD5\u5931\u8D25\u9879\uFF0C\u5171 ".concat(failedSpuIds.length, " \u4E2A\u5931\u8D25\u9879"));
            _context3.next = 77;
            return Object(util["h" /* delayed */])(5 * 1000);

          case 77:
            retryCount = 1;

          case 78:
            if (!(retryCount <= 3)) {
              _context3.next = 139;
              break;
            }

            if (!(failedSpuIds.length === 0)) {
              _context3.next = 81;
              break;
            }

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

          case 81:
            // 没有失败项了，退出重试
            log["a" /* default */].setLog("\u7B2C ".concat(retryCount, " \u6B21\u91CD\u8BD5\uFF0C\u5269\u4F59 ").concat(failedSpuIds.length, " \u4E2A\u5931\u8D25\u9879"));
            currentFailedItems = [].concat(failedSpuIds); // 复制当前失败项列表

            failedSpuIds.length = 0; // 清空失败项列表，准备重新收集

            _i = 0;

          case 85:
            if (!(_i < currentFailedItems.length)) {
              _context3.next = 131;
              break;
            }

            if (!task.isDelete) {
              _context3.next = 88;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: '任务已停止'
            });

          case 88:
            failedItem = currentFailedItems[_i]; // 重试前自适应节流（使用当前循环的 rateLimitStreak）

            if (!(_i > 0)) {
              _context3.next = 91;
              break;
            }

            return _context3.delegateYield( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee2() {
              var delay;
              return getGoodsTraffic_regeneratorRuntime().wrap(function _callee2$(_context2) {
                while (1) {
                  switch (_context2.prev = _context2.next) {
                    case 0:
                      delay = void 0;

                      if (rateLimitStreak >= 2) {
                        delay = randDelay(5000, 8000);
                      } else if (rateLimitStreak === 1) {
                        delay = randDelay(4000, 6000);
                      } else {
                        delay = randDelay(2000, 3000);
                      }

                      _context2.next = 4;
                      return new Promise(function (resolve) {
                        return setTimeout(resolve, delay);
                      });

                    case 4:
                    case "end":
                      return _context2.stop();
                  }
                }
              }, _callee2);
            })(), "t2", 91);

          case 91:
            _context3.prev = 91;
            retryItem = {
              productId: failedItem.spuId,
              siteId: failedItem.siteId || null
            };
            _context3.next = 95;
            return requestGoodsDetail(task, retryItem);

          case 95:
            _result = _context3.sent;

            if (!(_result.code !== 0)) {
              _context3.next = 115;
              break;
            }

            if (!_result.rateLimitBreaker) {
              _context3.next = 99;
              break;
            }

            return _context3.abrupt("return", {
              code: 1,
              msg: _result.msg,
              rateLimitBreaker: true
            });

          case 99:
            if (!(_result.code === 429)) {
              _context3.next = 109;
              break;
            }

            rateLimitStreak++;
            successStreak = 0;
            _cooldown = rateLimitStreak >= 3 ? cooldownSteps[Math.min(rateLimitStreak - 3, cooldownSteps.length - 1)] : 0;

            if (!(_cooldown > 0)) {
              _context3.next = 107;
              break;
            }

            log["a" /* default */].setLog("\u91CD\u8BD5\u65F6\u8FDE\u7EED".concat(rateLimitStreak, "\u6B21\u8FD4\u56DE429\uFF0C\u989D\u5916\u51B7\u5374").concat(_cooldown / 1000, "s\uFF0C\u518D\u7EE7\u7EED\u5F53\u524D\u9879"));
            _context3.next = 107;
            return Object(util["h" /* delayed */])(_cooldown);

          case 107:
            _context3.next = 111;
            break;

          case 109:
            rateLimitStreak = 0;
            successStreak = 0;

          case 111:
            // 重试仍然失败，重新加入失败列表
            failedSpuIds.push({
              spuId: failedItem.spuId,
              productName: failedItem.productName,
              siteId: failedItem.siteId,
              siteName: failedItem.siteName,
              category: failedItem.category,
              errorMsg: _result.msg,
              retryCount: retryCount
            });
            log["a" /* default */].setLog("\u91CD\u8BD5\u7B2C ".concat(retryCount, " \u6B21\u5931\u8D25: ").concat(_result.msg, ", spuId: ").concat(failedItem.spuId));
            _context3.next = 119;
            break;

          case 115:
            rateLimitStreak = 0;
            successStreak++; // 重试成功，添加到成功列表

            goodsTrafficList.push({
              productId: failedItem.spuId,
              productName: failedItem.productName || '未知商品',
              siteId: failedItem.siteId,
              siteName: failedItem.siteName || '未知站点',
              category: failedItem.category || null,
              details: _result.result || []
            });
            log["a" /* default */].setLog("\u91CD\u8BD5\u7B2C ".concat(retryCount, " \u6B21\u6210\u529F: spuId: ").concat(failedItem.spuId));

          case 119:
            _context3.next = 128;
            break;

          case 121:
            _context3.prev = 121;
            _context3.t3 = _context3["catch"](91);
            rateLimitStreak = 0;
            successStreak = 0;
            _msg3 = "\u91CD\u8BD5\u7B2C ".concat(retryCount, " \u6B21\u53D1\u751F\u5F02\u5E38: ").concat(Object(util["u" /* isError */])(_context3.t3, task), ", spuId: ").concat(failedItem.spuId);
            log["a" /* default */].setLog(_msg3); // 异常情况也重新加入失败列表

            failedSpuIds.push({
              spuId: failedItem.spuId,
              productName: failedItem.productName,
              siteId: failedItem.siteId,
              siteName: failedItem.siteName,
              category: failedItem.category,
              errorMsg: _msg3,
              retryCount: retryCount
            });

          case 128:
            _i++;
            _context3.next = 85;
            break;

          case 131:
            if (!(failedSpuIds.length > 0 && retryCount < 3)) {
              _context3.next = 136;
              break;
            }

            retryBackoff = [8000, 10000][retryCount - 1] || 10000;
            log["a" /* default */].setLog("\u7B2C ".concat(retryCount, " \u6B21\u91CD\u8BD5\u5B8C\u6210\uFF0C\u8FD8\u6709 ").concat(failedSpuIds.length, " \u4E2A\u5931\u8D25\u9879\uFF0C\u7B49\u5F85").concat(retryBackoff / 1000, "\u79D2\u540E\u8FDB\u884C\u4E0B\u6B21\u91CD\u8BD5"));
            _context3.next = 136;
            return Object(util["h" /* delayed */])(retryBackoff);

          case 136:
            retryCount++;
            _context3.next = 78;
            break;

          case 139:
            log["a" /* default */].setLog("\u91CD\u8BD5\u5B8C\u6210\uFF0C\u6700\u7EC8\u8FD8\u6709 ".concat(failedSpuIds.length, " \u4E2A\u5931\u8D25\u9879"));

          case 140:
            // 记录当前已获取数据，用于显示
            task.currentNum = (task.currentNum || 0) + goodsTrafficList.length;
            task.total = total;
            task.curPage = pageNo * getGoodsTraffic_$count; // 判断是否获取完毕

            if (!(task.curPage < total)) {
              _context3.next = 150;
              break;
            }

            task.pageNo += 1; // 上报当前状态

            _context3.next = 147;
            return common_newTask["a" /* default */].uploadTask({
              code: 4,
              data: {
                pageNo: task.pageNo
              },
              result: {
                currentNum: task.currentNum,
                curPage: task.curPage,
                total: total,
                list: goodsTrafficList,
                failedList: failedSpuIds,
                site_name: task.site_name
              }
            }, task);

          case 147:
            _context3.next = 149;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 149:
            return _context3.abrupt("return", getGoodsTrafficList(task));

          case 150:
            return _context3.abrupt("return", {
              code: 0,
              msg: '全部抓取完成',
              result: {
                currentNum: task.currentNum,
                curPage: task.curPage,
                total: total,
                list: goodsTrafficList,
                failedList: failedSpuIds
              }
            });

          case 151:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[32, 65], [91, 121]]);
  }));

  return function getGoodsTrafficList(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 获取商品流量列表


var requestGoodsTrafficList = /*#__PURE__*/function () {
  var _ref2 = getGoodsTraffic_asyncToGenerator( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee4(task) {
    var pageNo,
        retry,
        _yield$nativeRequest,
        success,
        errorMsg,
        result,
        msg,
        _msg4,
        _msg5,
        _args4 = arguments;

    return getGoodsTraffic_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            pageNo = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : 1;
            retry = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : 0;
            _context4.prev = 2;
            _context4.next = 5;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/flow/analysis/list"), // host需要改为 cbGlobalHost
            'post', {
              pageSize: getGoodsTraffic_$count,
              pageNumber: pageNo,
              timeDimension: 5
            }, {
              Mallid: task.platform_store_id
            });

          case 5:
            _yield$nativeRequest = _context4.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            result = _yield$nativeRequest.result;

            if (!(success && result)) {
              _context4.next = 19;
              break;
            }

            if (!result.pageItems) {
              _context4.next = 14;
              break;
            }

            return _context4.abrupt("return", {
              code: 0,
              total: result.total,
              info: result.pageItems,
              pageNo: pageNo
            });

          case 14:
            msg = '获取商品流量列表数据失败，可能规则已改变';
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              code: 2,
              msg: msg,
              pageNo: pageNo
            });

          case 17:
            _context4.next = 22;
            break;

          case 19:
            _msg4 = "\u83B7\u53D6\u5546\u54C1\u6D41\u91CF\u5217\u8868\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].setLog(_msg4);
            return _context4.abrupt("return", {
              msg: _msg4,
              pageNo: pageNo,
              code: 1
            });

          case 22:
            _context4.next = 34;
            break;

          case 24:
            _context4.prev = 24;
            _context4.t0 = _context4["catch"](2);
            _msg5 = "\u83B7\u53D6\u5546\u54C1\u6D41\u91CF\u5217\u8868\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(_msg5); // 重试三次

            if (!(retry < 3)) {
              _context4.next = 33;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context4.next = 32;
            return Object(util["h" /* delayed */])(5 * 1000);

          case 32:
            return _context4.abrupt("return", requestGoodsTrafficList(task, pageNo, ++retry));

          case 33:
            return _context4.abrupt("return", {
              code: 2,
              msg: _msg5,
              pageNo: pageNo
            });

          case 34:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[2, 24]]);
  }));

  return function requestGoodsTrafficList(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取商品流量详情


var requestGoodsDetail = /*#__PURE__*/function () {
  var _ref3 = getGoodsTraffic_asyncToGenerator( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee5(task, item) {
    var retry,
        productId,
        siteId,
        _yield$nativeRequest2,
        success,
        errorMsg,
        result,
        error_code,
        msg,
        _msg6,
        _msg7,
        _msg8,
        breakerMsg,
        _args5 = arguments;

    return getGoodsTraffic_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            retry = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : 0;

            if (!task.isDelete) {
              _context5.next = 3;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: '任务已停止'
            });

          case 3:
            if (typeof task.detailRateLimitCount !== 'number') task.detailRateLimitCount = 0;
            productId = item.productId, siteId = item.siteId;
            _context5.prev = 5;
            _context5.next = 8;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/flow/analysis/goods/detail"), // host需要改为 cbGlobalHost
            'post', {
              prodId: productId,
              siteId: siteId,
              timeType: 10
            }, {
              Mallid: task.platform_store_id
            });

          case 8:
            _yield$nativeRequest2 = _context5.sent;
            success = _yield$nativeRequest2.success;
            errorMsg = _yield$nativeRequest2.errorMsg;
            result = _yield$nativeRequest2.result;
            error_code = _yield$nativeRequest2.error_code;

            if (!(success && result)) {
              _context5.next = 24;
              break;
            }

            task.detailRateLimitCount = 0; // 成功重置计数器

            if (!(result.list && Array.isArray(result.list))) {
              _context5.next = 19;
              break;
            }

            return _context5.abrupt("return", {
              code: 0,
              result: result.list.slice(0, 31) // 只抓取最近31项

            });

          case 19:
            msg = "".concat(productId, "\u65E0list\u6D41\u91CF\u8BE6\u60C5\u6570\u636E\uFF0C\u53EF\u80FD\u89C4\u5219\u5DF2\u6539\u53D8");
            log["a" /* default */].setLog(msg);
            return _context5.abrupt("return", {
              msg: msg,
              code: 2
            });

          case 22:
            _context5.next = 40;
            break;

          case 24:
            if (!(error_code === 40002)) {
              _context5.next = 36;
              break;
            }

            task.detailRateLimitCount += 1;

            if (!(task.detailRateLimitCount >= RATE_LIMIT_BREAKER_THRESHOLD)) {
              _context5.next = 32;
              break;
            }

            _msg6 = 'Temu后台detail接口限流，请稍后重试';
            log["a" /* default */].setLog("\u89E6\u53D1\u7194\u65AD\uFF1Adetail\u63A5\u53E3\u8FDE\u7EED".concat(task.detailRateLimitCount, "\u6B21\u8FD4\u56DE429"));
            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            task.isDelete = true;
            return _context5.abrupt("return", {
              code: 429,
              msg: _msg6,
              rateLimitBreaker: true
            });

          case 32:
            log["a" /* default */].setLog('获取商品流量详情失败---被限流(429)');
            return _context5.abrupt("return", {
              code: 429,
              msg: '接口限流(429)'
            });

          case 36:
            task.detailRateLimitCount = 0; // 其他错误也重置，保证是连续429

            _msg7 = "\u83B7\u53D6\u5546\u54C1\u6D41\u91CF\u8BE6\u60C5\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].setLog(_msg7);
            return _context5.abrupt("return", {
              msg: _msg7,
              code: 1
            });

          case 40:
            _context5.next = 74;
            break;

          case 42:
            _context5.prev = 42;
            _context5.t0 = _context5["catch"](5);

            if (!(_context5.t0.message && _context5.t0.message.includes('40002'))) {
              _context5.next = 57;
              break;
            }

            task.detailRateLimitCount += 1;

            if (!(task.detailRateLimitCount >= RATE_LIMIT_BREAKER_THRESHOLD)) {
              _context5.next = 52;
              break;
            }

            breakerMsg = 'Temu后台detail接口限流，请稍后重试';
            log["a" /* default */].setLog("\u89E6\u53D1\u7194\u65AD\uFF1Adetail\u63A5\u53E3\u8FDE\u7EED".concat(task.detailRateLimitCount, "\u6B21\u8FD4\u56DE429"));
            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            task.isDelete = true;
            return _context5.abrupt("return", {
              code: 429,
              msg: breakerMsg,
              rateLimitBreaker: true
            });

          case 52:
            _msg8 = '获取商品流量详情被限流(429)';
            log["a" /* default */].setLog(_msg8);
            return _context5.abrupt("return", {
              code: 429,
              msg: _msg8
            });

          case 57:
            if (!(_context5.t0.message && _context5.t0.message.includes('"error_code":40001'))) {
              _context5.next = 65;
              break;
            }

            task.detailRateLimitCount = 0; // 重置

            log["a" /* default */].setLog('检测到登录过期，开始重新登陆........................');
            _context5.next = 62;
            return reLogin(task);

          case 62:
            log["a" /* default */].setLog('重新登陆完成，准备重新请求........................');
            _context5.next = 68;
            break;

          case 65:
            task.detailRateLimitCount = 0; // 重置

            _msg8 = "\u83B7\u53D6\u5546\u54C1\u6D41\u91CF\u8BE6\u60C5\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context5.t0, task));
            log["a" /* default */].setLog(_msg8);

          case 68:
            if (!(retry < 3)) {
              _context5.next = 73;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context5.next = 72;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 72:
            return _context5.abrupt("return", requestGoodsDetail(task, item, ++retry));

          case 73:
            return _context5.abrupt("return", {
              code: 2,
              msg: _msg8 || '获取商品流量详情失败'
            });

          case 74:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[5, 42]]);
  }));

  return function requestGoodsDetail(_x3, _x4) {
    return _ref3.apply(this, arguments);
  };
}(); // 店铺重新登陆


var reLogin = /*#__PURE__*/function () {
  var _ref4 = getGoodsTraffic_asyncToGenerator( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee6(task) {
    var loginRes, msg;
    return getGoodsTraffic_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.next = 2;
            return Object(temu["g" /* loginCb */])(task);

          case 2:
            loginRes = _context6.sent;

            if (loginRes) {
              _context6.next = 8;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context6.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 8:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6);
  }));

  return function reLogin(_x5) {
    return _ref4.apply(this, arguments);
  };
}(); // 入口函数


var getGoodsTraffic = /*#__PURE__*/function () {
  var _ref5 = getGoodsTraffic_asyncToGenerator( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee7(task) {
    var loginRes, msg, res, subTask;
    return getGoodsTraffic_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            if (!(task.resCache && task.resCache.code === 0)) {
              _context7.next = 2;
              break;
            }

            return _context7.abrupt("return", task.resCache);

          case 2:
            if (!(task.platform_code === 10022 || task.store_type === 'GLOBAL')) {
              _context7.next = 11;
              break;
            }

            _context7.next = 5;
            return Object(temu["g" /* loginCb */])(task);

          case 5:
            loginRes = _context7.sent;

            if (loginRes) {
              _context7.next = 11;
              break;
            }

            msg = '切换到美区或欧区站点失败，请检查';
            task.msg = msg;
            log["a" /* default */].setLog(msg);
            return _context7.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 11:
            if (!(task.store_type === 'GLOBAL' && task.area === 'US_GLOBAL_MIX')) {
              _context7.next = 17;
              break;
            }

            _context7.next = 14;
            return handleDoubleSiteTraffic(task);

          case 14:
            res = _context7.sent;
            _context7.next = 37;
            break;

          case 17:
            if (!(task.store_type === 'GLOBAL')) {
              _context7.next = 34;
              break;
            }

            // 跨境店铺
            // 使用克隆对象避免污染原 task
            subTask = Object(util["g" /* deepClone */])(task);
            _context7.t0 = task.area;
            _context7.next = _context7.t0 === 'US' ? 22 : _context7.t0 === 'EU' ? 24 : _context7.t0 === 'GLOBAL' ? 26 : 28;
            break;

          case 22:
            subTask.host = temu["h" /* temu */].cbUsHost;
            return _context7.abrupt("break", 29);

          case 24:
            subTask.host = temu["h" /* temu */].cbEuHost;
            return _context7.abrupt("break", 29);

          case 26:
            subTask.host = temu["h" /* temu */].cbGlobalHost;
            return _context7.abrupt("break", 29);

          case 28:
            return _context7.abrupt("return", {
              code: 1,
              msg: '不支持的站点task.area: ' + subTask.area
            });

          case 29:
            _context7.next = 31;
            return getGoodsTrafficList(subTask);

          case 31:
            res = _context7.sent;
            _context7.next = 37;
            break;

          case 34:
            _context7.next = 36;
            return getGoodsTrafficList(task);

          case 36:
            res = _context7.sent;

          case 37:
            task.status = [1, 2, 429].indexOf(res.code) > -1 ? 14 : 15; // code: 0 - 成功, 1 - 失败,2 - 异常, 4 - 执行中（进度上报）

            task.msg = res.msg;
            return _context7.abrupt("return", res);

          case 40:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7);
  }));

  return function getGoodsTraffic(_x6) {
    return _ref5.apply(this, arguments);
  };
}(); // 处理双站点流量分析（Global + US）


var handleDoubleSiteTraffic = /*#__PURE__*/function () {
  var _ref6 = getGoodsTraffic_asyncToGenerator( /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _callee8(task) {
    var combinedResult, finalCode, finalMsg, sites, _loop, _i2, _sites, _ret;

    return getGoodsTraffic_regeneratorRuntime().wrap(function _callee8$(_context9) {
      while (1) {
        switch (_context9.prev = _context9.next) {
          case 0:
            // 初始化汇总结果
            combinedResult = {
              currentNum: 0,
              curPage: 0,
              total: 0,
              list: [],
              failedList: [],
              site_global: {},
              site_us: {}
            };
            finalCode = 0;
            finalMsg = '全部抓取完成'; // 定义需要抓取的站点

            sites = [{
              host: temu["h" /* temu */].cbGlobalHost,
              name: 'GLOBAL'
            }, {
              host: temu["h" /* temu */].cbUsHost,
              name: 'US'
            }];
            _loop = /*#__PURE__*/getGoodsTraffic_regeneratorRuntime().mark(function _loop() {
              var site, subTask, subRes, _combinedResult$list, _combinedResult$faile, listWithSite, failedListWithSite;

              return getGoodsTraffic_regeneratorRuntime().wrap(function _loop$(_context8) {
                while (1) {
                  switch (_context8.prev = _context8.next) {
                    case 0:
                      site = _sites[_i2];

                      if (!task.isDelete) {
                        _context8.next = 3;
                        break;
                      }

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

                    case 3:
                      // 克隆任务对象，避免相互影响
                      subTask = Object(util["g" /* deepClone */])(task);
                      subTask.host = site.host; // 重置分页信息，确保每个站点都从第一页开始

                      subTask.pageNo = 1;
                      subTask.currentNum = 0;
                      subTask.curPage = 0;
                      subTask.site_name = site.name;
                      log["a" /* default */].setLog("\u5F00\u59CB\u6293\u53D6 ".concat(site.name, " \u7AD9\u70B9\u6D41\u91CF\u6570\u636E...")); // 执行抓取

                      _context8.next = 12;
                      return getGoodsTrafficList(subTask);

                    case 12:
                      subRes = _context8.sent;
                      console.log("[".concat(site.name, "\u5B50\u7ED3\u679C]"), subRes); // 记录状态（如果有失败，覆盖成功状态）

                      if (subRes.code !== 0) {
                        finalCode = subRes.code;
                        finalMsg = subRes.msg;
                      } // 如果触发了熔断，同步给原任务并立即终止后续站点执行


                      if (!subRes.rateLimitBreaker) {
                        _context8.next = 20;
                        break;
                      }

                      task.error_time = subTask.error_time;
                      task.isDelete = subTask.isDelete;
                      task.detailRateLimitCount = subTask.detailRateLimitCount;
                      return _context8.abrupt("return", {
                        v: {
                          code: finalCode,
                          msg: finalMsg,
                          result: combinedResult,
                          rateLimitBreaker: true
                        }
                      });

                    case 20:
                      // 合并数据
                      if (subRes.result) {
                        // 给每条数据增加站点标识
                        listWithSite = (subRes.result.list || []).map(function (item) {
                          return getGoodsTraffic_objectSpread(getGoodsTraffic_objectSpread({}, item), {}, {
                            site: site.name
                          });
                        });
                        failedListWithSite = (subRes.result.failedList || []).map(function (item) {
                          return getGoodsTraffic_objectSpread(getGoodsTraffic_objectSpread({}, item), {}, {
                            site: site.name
                          });
                        });

                        (_combinedResult$list = combinedResult.list).push.apply(_combinedResult$list, getGoodsTraffic_toConsumableArray(listWithSite));

                        (_combinedResult$faile = combinedResult.failedList).push.apply(_combinedResult$faile, getGoodsTraffic_toConsumableArray(failedListWithSite));

                        combinedResult.total += subRes.result.total || 0;
                        combinedResult.currentNum += subRes.result.currentNum || 0;
                        combinedResult.curPage += subRes.result.curPage || 0;

                        if (site.name === 'US' && subRes.result.total > 0) {
                          combinedResult.site_us = {
                            siteName: 'US',
                            currentNum: subRes.result.currentNum,
                            curPage: subRes.result.curPage,
                            total: subRes.result.total,
                            failedList: subRes.result.failedList
                          };
                        } else if (site.name === 'GLOBAL' && subRes.result.total > 0) {
                          combinedResult.site_global = {
                            siteName: 'GLOBAL',
                            currentNum: subRes.result.currentNum,
                            curPage: subRes.result.curPage,
                            total: subRes.result.total,
                            failedList: subRes.result.failedList
                          };
                        }
                      }

                    case 21:
                    case "end":
                      return _context8.stop();
                  }
                }
              }, _loop);
            });
            _i2 = 0, _sites = sites;

          case 6:
            if (!(_i2 < _sites.length)) {
              _context9.next = 16;
              break;
            }

            return _context9.delegateYield(_loop(), "t0", 8);

          case 8:
            _ret = _context9.t0;

            if (!(_ret === "break")) {
              _context9.next = 11;
              break;
            }

            return _context9.abrupt("break", 16);

          case 11:
            if (!(getGoodsTraffic_typeof(_ret) === "object")) {
              _context9.next = 13;
              break;
            }

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

          case 13:
            _i2++;
            _context9.next = 6;
            break;

          case 16:
            return _context9.abrupt("return", {
              code: finalCode,
              msg: finalMsg,
              result: combinedResult
            });

          case 17:
          case "end":
            return _context9.stop();
        }
      }
    }, _callee8);
  }));

  return function handleDoubleSiteTraffic(_x7) {
    return _ref6.apply(this, arguments);
  };
}();

/* harmony default export */ var temu_getGoodsTraffic = (getGoodsTraffic);
// CONCATENATED MODULE: ./src/platform/temu/getStorageServiceFee.js
function getStorageServiceFee_typeof(obj) { "@babel/helpers - typeof"; return getStorageServiceFee_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; }, getStorageServiceFee_typeof(obj); }

function getStorageServiceFee_toConsumableArray(arr) { return getStorageServiceFee_arrayWithoutHoles(arr) || getStorageServiceFee_iterableToArray(arr) || getStorageServiceFee_unsupportedIterableToArray(arr) || getStorageServiceFee_nonIterableSpread(); }

function getStorageServiceFee_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getStorageServiceFee_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getStorageServiceFee_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 getStorageServiceFee_arrayLikeToArray(o, minLen); }

function getStorageServiceFee_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getStorageServiceFee_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getStorageServiceFee_arrayLikeToArray(arr); }

function getStorageServiceFee_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; }

function getStorageServiceFee_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getStorageServiceFee_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" == getStorageServiceFee_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 getStorageServiceFee_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getStorageServiceFee_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getStorageServiceFee_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getStorageServiceFee_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }



 // 仅针对 temu 全托店铺，域名为 kuajingmaihuo
// 外层资金明细单页最多 100 条，详情单页最多 100 条

var OUTER_PAGE_SIZE = 100;
var DETAIL_PAGE_SIZE = 100; // 仓储综合服务费标识（bizType 最稳，remark 兜底）

var STORAGE_FEE_BIZ_TYPE = 'deduct_storage_service_fee';
var STORAGE_FEE_REMARK = '仓储综合服务费'; // 防止异常死循环

var MAX_PAGE = 200; // 判断外层 item 是否为仓储综合服务费

var isStorageFeeItem = function isStorageFeeItem(item) {
  return item && (item.bizType === STORAGE_FEE_BIZ_TYPE || item.remark === STORAGE_FEE_REMARK);
}; // 计算任务时间范围（毫秒），优先取自定义时间段，否则按月份


var getStorageServiceFee_getTimeRange = function getTimeRange(task) {
  var startDate = task.report_custom_date_start || moment_default()(task.report_date_month, 'YYYYMM').startOf('month').format('YYYY-MM-DD');
  var endDate = task.report_custom_date_end || moment_default()(task.report_date_month, 'YYYYMM').endOf('month').format('YYYY-MM-DD');
  return {
    beginTime: moment_default()("".concat(startDate, " 00:00:00")).valueOf(),
    endTime: moment_default()("".concat(endDate, " 23:59:59")).valueOf()
  };
};
/**
 * 获取外层资金明细单页
 * @returns {Promise<{code:number, list?:Array, total?:number, msg?:string}>}
 */


var requestFundDetailPage = /*#__PURE__*/function () {
  var _ref = getStorageServiceFee_asyncToGenerator( /*#__PURE__*/getStorageServiceFee_regeneratorRuntime().mark(function _callee(task, pageNum, beginTime, endTime) {
    var retry,
        _yield$nativeRequest,
        success,
        errorMsg,
        result,
        msg,
        _msg,
        _args = arguments;

    return getStorageServiceFee_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            retry = _args.length > 4 && _args[4] !== undefined ? _args[4] : 0;
            _context.prev = 1;
            _context.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/fund/detail/pageSearch"), 'post', {
              moneyChangeTypeList: [2],
              beginTime: beginTime,
              endTime: endTime,
              pageSize: OUTER_PAGE_SIZE,
              pageNum: pageNum
            }, {
              Mallid: task.real_mall_id
            });

          case 4:
            _yield$nativeRequest = _context.sent;
            success = _yield$nativeRequest.success;
            errorMsg = _yield$nativeRequest.errorMsg;
            result = _yield$nativeRequest.result;

            if (!(success && result)) {
              _context.next = 10;
              break;
            }

            return _context.abrupt("return", {
              code: 0,
              list: result.resultList || [],
              total: result.total || 0
            });

          case 10:
            msg = "\u83B7\u53D6\u8D44\u91D1\u660E\u7EC6\u5217\u8868\u5931\u8D25\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(JSON.stringify(errorMsg));
            log["a" /* default */].setLog(msg);
            return _context.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 15:
            _context.prev = 15;
            _context.t0 = _context["catch"](1);
            _msg = "\u83B7\u53D6\u8D44\u91D1\u660E\u7EC6\u5217\u8868\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(_msg);

            if (!(retry < 3)) {
              _context.next = 24;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context.next = 23;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 23:
            return _context.abrupt("return", requestFundDetailPage(task, pageNum, beginTime, endTime, ++retry));

          case 24:
            return _context.abrupt("return", {
              code: 2,
              msg: _msg
            });

          case 25:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[1, 15]]);
  }));

  return function requestFundDetailPage(_x, _x2, _x3, _x4) {
    return _ref.apply(this, arguments);
  };
}();
/**
 * 获取单个仓储综合服务费的详情单页
 * @returns {Promise<{code:number, list?:Array, total?:number, msg?:string}>}
 */


var requestBillDetailPage = /*#__PURE__*/function () {
  var _ref2 = getStorageServiceFee_asyncToGenerator( /*#__PURE__*/getStorageServiceFee_regeneratorRuntime().mark(function _callee2(task, item, pageNum) {
    var retry,
        _yield$nativeRequest2,
        success,
        errorMsg,
        result,
        msg,
        _msg2,
        _args2 = arguments;

    return getStorageServiceFee_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            retry = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : 0;
            _context2.prev = 1;
            _context2.next = 4;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/api/merchant/warehouse/express/bill/detail/list"), 'post', {
              pageNum: pageNum,
              pageSize: DETAIL_PAGE_SIZE,
              billStatus: 2,
              mallId: Number(task.real_mall_id),
              transId: item.transSn // billBizTimeStart: item.transactionTime,
              // billBizTimeEnd: item.transactionTime

            }, {
              Mallid: task.real_mall_id // 'express-entity-type': '0',
              // 'express-mall-type': '1',
              // 'express-source-type': '0'

            });

          case 4:
            _yield$nativeRequest2 = _context2.sent;
            success = _yield$nativeRequest2.success;
            errorMsg = _yield$nativeRequest2.errorMsg;
            result = _yield$nativeRequest2.result;

            if (!(success && result)) {
              _context2.next = 10;
              break;
            }

            return _context2.abrupt("return", {
              code: 0,
              list: result.list || [],
              total: result.total || 0
            });

          case 10:
            msg = "\u83B7\u53D6\u4ED3\u50A8\u7EFC\u5408\u670D\u52A1\u8D39\u8BE6\u60C5\u5931\u8D25(".concat(item.transSn, ")\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A").concat(JSON.stringify(errorMsg));
            log["a" /* default */].setLog(msg);
            return _context2.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 15:
            _context2.prev = 15;
            _context2.t0 = _context2["catch"](1);
            _msg2 = "\u83B7\u53D6\u4ED3\u50A8\u7EFC\u5408\u670D\u52A1\u8D39\u8BE6\u60C5\u5931\u8D25(".concat(item.transSn, ")-----").concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(_msg2);

            if (!(retry < 3)) {
              _context2.next = 24;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context2.next = 23;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 23:
            return _context2.abrupt("return", requestBillDetailPage(task, item, pageNum, ++retry));

          case 24:
            return _context2.abrupt("return", {
              code: 2,
              msg: _msg2
            });

          case 25:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 15]]);
  }));

  return function requestBillDetailPage(_x5, _x6, _x7) {
    return _ref2.apply(this, arguments);
  };
}(); // 获取单个仓储综合服务费的全部详情（翻页直到取完）


var getAllBillDetail = /*#__PURE__*/function () {
  var _ref3 = getStorageServiceFee_asyncToGenerator( /*#__PURE__*/getStorageServiceFee_regeneratorRuntime().mark(function _callee3(task, item) {
    var detailList, pageNum, _yield$requestBillDet, code, list, total, msg;

    return getStorageServiceFee_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            detailList = [];
            pageNum = 1;

          case 2:
            if (!(pageNum <= MAX_PAGE)) {
              _context3.next = 20;
              break;
            }

            _context3.next = 5;
            return requestBillDetailPage(task, item, pageNum);

          case 5:
            _yield$requestBillDet = _context3.sent;
            code = _yield$requestBillDet.code;
            list = _yield$requestBillDet.list;
            total = _yield$requestBillDet.total;
            msg = _yield$requestBillDet.msg;

            if (!(code !== 0)) {
              _context3.next = 12;
              break;
            }

            return _context3.abrupt("return", {
              code: code,
              msg: msg
            });

          case 12:
            detailList.push.apply(detailList, getStorageServiceFee_toConsumableArray(list));

            if (!(detailList.length >= total || !list.length)) {
              _context3.next = 15;
              break;
            }

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

          case 15:
            _context3.next = 17;
            return Object(util["h" /* delayed */])(500);

          case 17:
            pageNum++;
            _context3.next = 2;
            break;

          case 20:
            return _context3.abrupt("return", {
              code: 0,
              detailList: detailList
            });

          case 21:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function getAllBillDetail(_x8, _x9) {
    return _ref3.apply(this, arguments);
  };
}(); // 获取外层全部仓储综合服务费 item（翻页直到取完）


var getAllStorageFeeItems = /*#__PURE__*/function () {
  var _ref4 = getStorageServiceFee_asyncToGenerator( /*#__PURE__*/getStorageServiceFee_regeneratorRuntime().mark(function _callee4(task, beginTime, endTime) {
    var items, pageNum, collected, _yield$requestFundDet, code, list, total, msg;

    return getStorageServiceFee_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            items = [];
            pageNum = 1;
            collected = 0;

          case 3:
            if (!(pageNum <= MAX_PAGE)) {
              _context4.next = 22;
              break;
            }

            _context4.next = 6;
            return requestFundDetailPage(task, pageNum, beginTime, endTime);

          case 6:
            _yield$requestFundDet = _context4.sent;
            code = _yield$requestFundDet.code;
            list = _yield$requestFundDet.list;
            total = _yield$requestFundDet.total;
            msg = _yield$requestFundDet.msg;

            if (!(code !== 0)) {
              _context4.next = 13;
              break;
            }

            return _context4.abrupt("return", {
              code: code,
              msg: msg
            });

          case 13:
            collected += list.length;
            list.filter(isStorageFeeItem).forEach(function (item) {
              items.push({
                transSn: item.transSn,
                transactionTime: item.transactionTime,
                amount: item.amount,
                currencyType: item.currencyType
              });
            });

            if (!(collected >= total || !list.length)) {
              _context4.next = 17;
              break;
            }

            return _context4.abrupt("break", 22);

          case 17:
            _context4.next = 19;
            return Object(util["h" /* delayed */])(500);

          case 19:
            pageNum++;
            _context4.next = 3;
            break;

          case 22:
            return _context4.abrupt("return", {
              code: 0,
              items: items
            });

          case 23:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function getAllStorageFeeItems(_x10, _x11, _x12) {
    return _ref4.apply(this, arguments);
  };
}();

var getStorageServiceFee = /*#__PURE__*/function () {
  var _ref5 = getStorageServiceFee_asyncToGenerator( /*#__PURE__*/getStorageServiceFee_regeneratorRuntime().mark(function _callee5(task) {
    var _getTimeRange, beginTime, endTime, outerRes, items, list, i, item, detailRes;

    return getStorageServiceFee_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            if (!(task.resCache && task.resCache.code === 0)) {
              _context5.next = 2;
              break;
            }

            return _context5.abrupt("return", task.resCache);

          case 2:
            _getTimeRange = getStorageServiceFee_getTimeRange(task), beginTime = _getTimeRange.beginTime, endTime = _getTimeRange.endTime; // 第一步：拿到时间段内所有仓储综合服务费 item（transactionTime + transSn）

            _context5.next = 5;
            return getAllStorageFeeItems(task, beginTime, endTime);

          case 5:
            outerRes = _context5.sent;

            if (!(outerRes.code !== 0)) {
              _context5.next = 10;
              break;
            }

            task.status = 14;
            task.msg = outerRes.msg;
            return _context5.abrupt("return", {
              code: 2,
              msg: outerRes.msg
            });

          case 10:
            items = outerRes.items;

            if (items.length) {
              _context5.next = 15;
              break;
            }

            task.status = 15;
            task.msg = '该时间段无仓储综合服务费数据';
            return _context5.abrupt("return", {
              code: 0,
              msg: task.msg,
              result: {
                list: []
              }
            });

          case 15:
            // 第二步：逐个 transSn 拉取详情 list 并整合
            list = [];
            i = 0;

          case 17:
            if (!(i < items.length)) {
              _context5.next = 32;
              break;
            }

            item = items[i];
            _context5.next = 21;
            return getAllBillDetail(task, item);

          case 21:
            detailRes = _context5.sent;

            if (!(detailRes.code !== 0)) {
              _context5.next = 26;
              break;
            }

            task.status = 14;
            task.msg = detailRes.msg;
            return _context5.abrupt("return", {
              code: 2,
              msg: detailRes.msg
            });

          case 26:
            list.push({
              transSn: item.transSn,
              transactionTime: item.transactionTime,
              amount: item.amount,
              currencyType: item.currencyType,
              detailList: detailRes.detailList
            });
            _context5.next = 29;
            return Object(util["h" /* delayed */])(500);

          case 29:
            i++;
            _context5.next = 17;
            break;

          case 32:
            task.status = 15;
            task.msg = '获取完毕';
            return _context5.abrupt("return", {
              code: 0,
              msg: '获取完毕',
              result: {
                list: list
              }
            });

          case 35:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getStorageServiceFee(_x13) {
    return _ref5.apply(this, arguments);
  };
}();

var handleGetStorageServiceFee = /*#__PURE__*/function () {
  var _ref6 = getStorageServiceFee_asyncToGenerator( /*#__PURE__*/getStorageServiceFee_regeneratorRuntime().mark(function _callee6(task) {
    var res, msg;
    return getStorageServiceFee_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;
            _context6.next = 3;
            return getStorageServiceFee(task);

          case 3:
            res = _context6.sent;
            task.status = [1, 2].includes(res.code) ? 14 : 15;
            task.msg = res.msg;
            return _context6.abrupt("return", res);

          case 9:
            _context6.prev = 9;
            _context6.t0 = _context6["catch"](0);
            msg = "\u83B7\u53D6\u4ED3\u50A8\u7EFC\u5408\u670D\u52A1\u8D39\u5931\u8D25\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A".concat(Object(util["u" /* isError */])(_context6.t0, task));
            log["a" /* default */].setLog(msg);
            task.status = 14;
            task.msg = msg;
            return _context6.abrupt("return", {
              code: 2,
              msg: msg
            });

          case 16:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[0, 9]]);
  }));

  return function handleGetStorageServiceFee(_x14) {
    return _ref6.apply(this, arguments);
  };
}();

/* harmony default export */ var temu_getStorageServiceFee = (handleGetStorageServiceFee);
// EXTERNAL MODULE: ./src/platform/tiktok/utils/index.js
var utils = __webpack_require__("ba27");

// CONCATENATED MODULE: ./src/platform/tiktok/core/getTargetInvitation.js
function getTargetInvitation_typeof(obj) { "@babel/helpers - typeof"; return getTargetInvitation_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; }, getTargetInvitation_typeof(obj); }

function getTargetInvitation_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = getTargetInvitation_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function getTargetInvitation_toConsumableArray(arr) { return getTargetInvitation_arrayWithoutHoles(arr) || getTargetInvitation_iterableToArray(arr) || getTargetInvitation_unsupportedIterableToArray(arr) || getTargetInvitation_nonIterableSpread(); }

function getTargetInvitation_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getTargetInvitation_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getTargetInvitation_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 getTargetInvitation_arrayLikeToArray(o, minLen); }

function getTargetInvitation_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getTargetInvitation_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getTargetInvitation_arrayLikeToArray(arr); }

function getTargetInvitation_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; }

function getTargetInvitation_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getTargetInvitation_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getTargetInvitation_ownKeys(Object(source), !0).forEach(function (key) { getTargetInvitation_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getTargetInvitation_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getTargetInvitation_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getTargetInvitation_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getTargetInvitation_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" == getTargetInvitation_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 getTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getTargetInvitation_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }






var statusMap = {
  1: '进行中',
  2: '即将到期',
  3: '取消中',
  4: '已完成'
};

var getTargetInvitationTotal = /*#__PURE__*/function () {
  var _ref = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee(task) {
    var query, _yield$tkPost, code, data, message;

    return getTargetInvitation_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context.sent;

            if (query) {
              _context.next = 6;
              break;
            }

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

          case 6:
            _context.next = 8;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/count"), query, {
              search_params: {
                query_items: [],
                filter_accept_status: 3
              },
              invitation_status: [1, 2, 3, 4]
            });

          case 8:
            _yield$tkPost = _context.sent;
            code = _yield$tkPost.code;
            data = _yield$tkPost.data;
            message = _yield$tkPost.message;

            if (!(code === 0)) {
              _context.next = 16;
              break;
            }

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

          case 16:
            log["a" /* default */].setLog("\u83B7\u53D6\u5B9A\u5411\u9080\u7EA6\u5217\u8868\u5404\u72B6\u6001\u6570\u636E\u603B\u6570\u5931\u8D25-----".concat(message));
            return _context.abrupt("return", false);

          case 18:
            _context.next = 23;
            break;

          case 20:
            _context.prev = 20;
            _context.t0 = _context["catch"](0);
            log["a" /* default */].setLog("\u83B7\u53D6\u5B9A\u5411\u9080\u7EA6\u5217\u8868\u5404\u72B6\u6001\u6570\u636E\u603B\u6570\u5931\u8D25-----".concat(Object(util["u" /* isError */])(_context.t0)));

          case 23:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 20]]);
  }));

  return function getTargetInvitationTotal(_x) {
    return _ref.apply(this, arguments);
  };
}();

var getTargetInvitationList = /*#__PURE__*/function () {
  var _ref3 = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee2(_ref2, task) {
    var curPage,
        status,
        retry,
        query,
        _yield$tkPost2,
        code,
        message,
        data,
        msg,
        _msg,
        _args2 = arguments;

    return getTargetInvitation_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            curPage = _ref2.curPage, status = _ref2.status;
            retry = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : 0;
            _context2.prev = 2;
            _context2.next = 5;
            return Object(utils["a" /* getQueryString */])(task);

          case 5:
            query = _context2.sent;

            if (query) {
              _context2.next = 8;
              break;
            }

            return _context2.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 8:
            _context2.next = 10;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/search"), query, {
              search_params: {
                query_items: [],
                filter_accept_status: 3
              },
              invitation_group_status: status,
              page_size: 50,
              cur_page: curPage
            }, {
              origin: task.host + "/connection/target-invitation?shop_region=US&tab=".concat(status)
            });

          case 10:
            _yield$tkPost2 = _context2.sent;
            code = _yield$tkPost2.code;
            message = _yield$tkPost2.message;
            data = _yield$tkPost2.data;

            if (!(code === 0)) {
              _context2.next = 18;
              break;
            }

            return _context2.abrupt("return", {
              code: 0,
              data: data
            });

          case 18:
            msg = "\u83B7\u53D6".concat(statusMap[status], "\u7684\u5B9A\u5411\u9080\u7EA6\u5217\u8868\u5931\u8D25-----").concat(message);
            log["a" /* default */].setLog(msg);
            return _context2.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 21:
            _context2.next = 33;
            break;

          case 23:
            _context2.prev = 23;
            _context2.t0 = _context2["catch"](2);
            _msg = "\u83B7\u53D6".concat(statusMap[status], "\u7684\u5B9A\u5411\u9080\u7EA6\u5217\u8868\u5931\u8D25-----").concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(_msg); // 重试三次

            if (!(retry < 3)) {
              _context2.next = 32;
              break;
            }

            log["a" /* default */].setLog("\u83B7\u53D6".concat(statusMap[status], "\u7684\u5B9A\u5411\u9080\u7EA6\u5217\u8868---\u6B63\u5728\u91CD\u8BD5\u7B2C").concat(retry + 1, "\u6B21........................"));
            _context2.next = 31;
            return Object(util["h" /* delayed */])((retry + 1) * 1 * 1000);

          case 31:
            return _context2.abrupt("return", getTargetInvitationList({
              curPage: curPage,
              status: status
            }, task, retry + 1));

          case 32:
            return _context2.abrupt("return", {
              code: 1,
              msg: _msg
            });

          case 33:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[2, 23]]);
  }));

  return function getTargetInvitationList(_x2, _x3) {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * 分批获取定向邀约详情
 * @param {Array} invitationList - 邀约列表（只需要 invitation_group_id 字段）
 * @param {Object} task - 任务对象
 * @returns {Set} 失败的 invitation_group_id 集合（使用Set自动去重）
 */


var fetchInvitationDetails = /*#__PURE__*/function () {
  var _ref4 = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee4(invitationList, task) {
    var DETAIL_BATCH_SIZE, UPLOAD_BATCH_SIZE, failDetailsSet, allDetails, i, batch, batchDetails, uploadBatch, succAmount, uploadRes, _succAmount, _uploadRes;

    return getTargetInvitation_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            DETAIL_BATCH_SIZE = 1; // 每批获取10条

            UPLOAD_BATCH_SIZE = 1000; // 每1000条上报一次

            failDetailsSet = new Set(); // 使用Set自动去重，只存储 invitation_group_id

            allDetails = [];
            log["a" /* default */].setLog("\u5F00\u59CB\u83B7\u53D6\u5B9A\u5411\u9080\u7EA6\u8BE6\u60C5\uFF0C\u5171".concat(invitationList.length, "\u6761")); // 分批处理

            i = 0;

          case 6:
            if (!(i < invitationList.length)) {
              _context4.next = 24;
              break;
            }

            batch = invitationList.slice(i, i + DETAIL_BATCH_SIZE);
            log["a" /* default */].setLog("\u83B7\u53D6\u8BE6\u60C5\u8FDB\u5EA6\uFF1A".concat(i + batch.length, "/").concat(invitationList.length)); // 并发获取当前批次的详情

            _context4.next = 11;
            return Promise.all(batch.map( /*#__PURE__*/function () {
              var _ref5 = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee3(invitationId) {
                var detailRes, errMsg;
                return getTargetInvitation_regeneratorRuntime().wrap(function _callee3$(_context3) {
                  while (1) {
                    switch (_context3.prev = _context3.next) {
                      case 0:
                        _context3.prev = 0;
                        _context3.next = 3;
                        return getInvitationDetail({
                          invitation_group_id: invitationId
                        }, task);

                      case 3:
                        detailRes = _context3.sent;

                        if (!(detailRes.code === 0)) {
                          _context3.next = 8;
                          break;
                        }

                        return _context3.abrupt("return", getTargetInvitation_objectSpread(getTargetInvitation_objectSpread({
                          invitation_group_id: invitationId
                        }, detailRes.detail), {}, {
                          code: 0
                        }));

                      case 8:
                        // 获取失败：记录 ID 到 failDetailsSet
                        failDetailsSet.add(invitationId);
                        return _context3.abrupt("return", {
                          invitation_group_id: invitationId,
                          code: 1,
                          msg: detailRes.msg
                        });

                      case 10:
                        _context3.next = 18;
                        break;

                      case 12:
                        _context3.prev = 12;
                        _context3.t0 = _context3["catch"](0);
                        errMsg = "\u83B7\u53D6\u9080\u7EA6\u8BE6\u60C5\u5F02\u5E38[ID:".concat(invitationId, "]-----").concat(Object(util["u" /* isError */])(_context3.t0)); // 获取异常：记录 ID 到 failDetailsSet

                        failDetailsSet.add(invitationId);
                        log["a" /* default */].setLog(errMsg);
                        return _context3.abrupt("return", {
                          invitation_group_id: invitationId,
                          code: 1,
                          msg: errMsg
                        });

                      case 18:
                      case "end":
                        return _context3.stop();
                    }
                  }
                }, _callee3, null, [[0, 12]]);
              }));

              return function (_x6) {
                return _ref5.apply(this, arguments);
              };
            }()));

          case 11:
            batchDetails = _context4.sent;
            allDetails.push.apply(allDetails, getTargetInvitation_toConsumableArray(batchDetails)); // 每1000条详情上报一次

            if (!(allDetails.length >= UPLOAD_BATCH_SIZE)) {
              _context4.next = 21;
              break;
            }

            uploadBatch = allDetails.splice(0, UPLOAD_BATCH_SIZE);
            succAmount = uploadBatch.filter(function (item) {
              return item.code === 0;
            }).length;
            log["a" /* default */].setLog("\u5206\u6279\u4E0A\u62A5\u5B9A\u5411\u9080\u7EA6\u8BE6\u60C5\uFF0C\u6210\u529F\uFF1A".concat(succAmount, "\u6761\uFF0C\u5931\u8D25\uFF1A").concat(uploadBatch.length - succAmount, "\u6761"));
            _context4.next = 19;
            return common_newTask["a" /* default */].uploadTask({
              code: 4,
              result: {
                details: uploadBatch
              }
            }, task);

          case 19:
            uploadRes = _context4.sent;

            // 如果上报失败，将整批的 invitation_group_id 记录到 failDetailsSet（Set会自动去重）
            if (!uploadRes) {
              log["a" /* default */].setLog("\u4E0A\u62A5\u8BE6\u60C5\u5931\u8D25\uFF0C\u5C06".concat(uploadBatch.length, "\u6761\u6570\u636E\u7684ID\u8BB0\u5F55\u5230failDetails"));
              uploadBatch.forEach(function (item) {
                failDetailsSet.add(item.invitation_group_id);
              });
            }

          case 21:
            i += DETAIL_BATCH_SIZE;
            _context4.next = 6;
            break;

          case 24:
            if (!(allDetails.length > 0)) {
              _context4.next = 31;
              break;
            }

            _succAmount = allDetails.filter(function (item) {
              return item.code === 0;
            }).length;
            log["a" /* default */].setLog("\u51C6\u5907\u4E0A\u4F20\u5269\u4F59\u5B9A\u5411\u9080\u7EA6\u8BE6\u60C5\uFF0C\u6210\u529F\uFF1A".concat(_succAmount, "\u6761\uFF0C\u5931\u8D25\uFF1A").concat(allDetails.length - _succAmount, "\u6761"));
            _context4.next = 29;
            return common_newTask["a" /* default */].uploadTask({
              code: 4,
              result: {
                details: allDetails
              }
            }, task);

          case 29:
            _uploadRes = _context4.sent;

            // 如果上报失败，将剩余的 invitation_group_id 记录到 failDetailsSet（Set会自动去重）
            if (!_uploadRes) {
              log["a" /* default */].setLog("\u4E0A\u62A5\u5269\u4F59\u8BE6\u60C5\u5931\u8D25\uFF0C\u5C06".concat(allDetails.length, "\u6761\u6570\u636E\u7684ID\u8BB0\u5F55\u5230failDetails"));
              allDetails.forEach(function (item) {
                failDetailsSet.add(item.invitation_group_id);
              });
            }

          case 31:
            return _context4.abrupt("return", failDetailsSet);

          case 32:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));

  return function fetchInvitationDetails(_x4, _x5) {
    return _ref4.apply(this, arguments);
  };
}();
/**
 * 获取单个定向邀约详情
 * @param {Object} params - { invitation_group_id: string }
 * @param {Object} task - 任务对象
 * @param {number} retry - 重试次数
 * @returns {Object} { code: 0/1, detail: {}, msg: '' }
 */


var getInvitationDetail = /*#__PURE__*/function () {
  var _ref6 = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee5(params, task) {
    var retry,
        query,
        _yield$tkPost3,
        code,
        data,
        message,
        msg,
        _args5 = arguments;

    return getTargetInvitation_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            retry = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : 0;
            _context5.prev = 1;
            _context5.next = 4;
            return Object(utils["a" /* getQueryString */])(task);

          case 4:
            query = _context5.sent;

            if (query) {
              _context5.next = 7;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 7:
            _context5.next = 9;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/detail"), query, {
              invitation_group_id: params.invitation_group_id
            });

          case 9:
            _yield$tkPost3 = _context5.sent;
            code = _yield$tkPost3.code;
            data = _yield$tkPost3.data;
            message = _yield$tkPost3.message;

            if (!(code === 0)) {
              _context5.next = 17;
              break;
            }

            return _context5.abrupt("return", {
              code: 0,
              detail: data.invitation
            });

          case 17:
            log["a" /* default */].setLog("\u83B7\u53D6\u9080\u7EA6\u8BE6\u60C5\u5931\u8D25[ID:".concat(params.invitation_group_id, "]-----").concat(message));
            return _context5.abrupt("return", {
              code: 1,
              msg: message
            });

          case 19:
            _context5.next = 31;
            break;

          case 21:
            _context5.prev = 21;
            _context5.t0 = _context5["catch"](1);
            msg = "\u83B7\u53D6\u9080\u7EA6\u8BE6\u60C5\u5931\u8D25[ID:".concat(params.invitation_group_id, "]-----").concat(Object(util["u" /* isError */])(_context5.t0, task));
            log["a" /* default */].setLog(msg); // 重试3次

            if (!(retry < 3)) {
              _context5.next = 30;
              break;
            }

            log["a" /* default */].setLog("\u83B7\u53D6\u9080\u7EA6\u8BE6\u60C5\u91CD\u8BD5\u7B2C".concat(retry + 1, "\u6B21[ID:").concat(params.invitation_group_id, "]"));
            _context5.next = 29;
            return Object(util["h" /* delayed */])((retry + 1) * 1000);

          case 29:
            return _context5.abrupt("return", getInvitationDetail(params, task, retry + 1));

          case 30:
            return _context5.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 31:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[1, 21]]);
  }));

  return function getInvitationDetail(_x7, _x8) {
    return _ref6.apply(this, arguments);
  };
}();

function getTargetInvitation(_x9) {
  return _getTargetInvitation.apply(this, arguments);
}

function _getTargetInvitation() {
  _getTargetInvitation = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee7(task) {
    var _task$resCache, _task$resCache$data;

    var failDetailsSet, errorCache, list, allInvitations, NINETYDaysAgo, _iterator, _step, _loop, _failDetailsSet, totalData, findErr, code, msg;

    return getTargetInvitation_regeneratorRuntime().wrap(function _callee7$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            if (!(task.failDetails && task.failDetails.length > 0)) {
              _context8.next = 6;
              break;
            }

            log["a" /* default */].setLog("\u68C0\u6D4B\u5230".concat(task.failDetails.length, "\u6761\u5931\u8D25\u8BE6\u60C5\uFF0C\u4F18\u5148\u91CD\u8BD5"));
            _context8.next = 4;
            return fetchInvitationDetails(task.failDetails, task);

          case 4:
            failDetailsSet = _context8.sent;

            if (failDetailsSet.size === 0) {
              task.failDetails = [];
              log["a" /* default */].setLog('失败详情重试完成，全部成功');
            } else {
              task.failDetails = Array.from(failDetailsSet);
              log["a" /* default */].setLog("\u4ECD\u6709".concat(failDetailsSet.size, "\u6761\u8BE6\u60C5\u83B7\u53D6/\u4E0A\u62A5\u5931\u8D25"));
            }

          case 6:
            errorCache = [];
            list = [];
            allInvitations = []; // 收集所有邀约用于获取详情

            NINETYDaysAgo = Date.now() - 90 * 24 * 60 * 60 * 1000;
            _iterator = getTargetInvitation_createForOfIteratorHelper(((_task$resCache = task.resCache) === null || _task$resCache === void 0 ? void 0 : (_task$resCache$data = _task$resCache.data) === null || _task$resCache$data === void 0 ? void 0 : _task$resCache$data.errorCache) || [1, 2, 3, 4].map(function (item) {
              return {
                status: item,
                curPage: 1
              };
            }));
            _context8.prev = 11;
            _loop = /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _loop() {
              var _step$value, status, curPage, has_more, errMsg, resCode, _yield$getTargetInvit, _code, data, _msg2, rawList, stopDueToTime, filtered, _iterator2, _step2, item;

              return getTargetInvitation_regeneratorRuntime().wrap(function _loop$(_context7) {
                while (1) {
                  switch (_context7.prev = _context7.next) {
                    case 0:
                      _step$value = _step.value, status = _step$value.status, curPage = _step$value.curPage;
                      has_more = true;
                      errMsg = '';
                      resCode = 0;

                    case 4:
                      if (!has_more) {
                        _context7.next = 54;
                        break;
                      }

                      _context7.next = 7;
                      return Object(util["h" /* delayed */])(Math.random() * 2000 + 1000);

                    case 7:
                      _context7.next = 9;
                      return getTargetInvitationList({
                        curPage: curPage,
                        status: status
                      }, task);

                    case 9:
                      _yield$getTargetInvit = _context7.sent;
                      _code = _yield$getTargetInvit.code;
                      data = _yield$getTargetInvit.data;
                      _msg2 = _yield$getTargetInvit.msg;

                      if (!(_code === 0)) {
                        _context7.next = 46;
                        break;
                      }

                      rawList = data.invitation_list || [];
                      stopDueToTime = false; // 停止标识：由于结束时间超出90天的

                      if (!(status === 4)) {
                        _context7.next = 40;
                        break;
                      }

                      filtered = [];
                      _iterator2 = getTargetInvitation_createForOfIteratorHelper(rawList);
                      _context7.prev = 19;

                      _iterator2.s();

                    case 21:
                      if ((_step2 = _iterator2.n()).done) {
                        _context7.next = 31;
                        break;
                      }

                      item = _step2.value;

                      if (!(Number(item.end_time) + 24 * 60 * 60 * 1000 >= NINETYDaysAgo)) {
                        _context7.next = 27;
                        break;
                      }

                      filtered.push(item);
                      _context7.next = 29;
                      break;

                    case 27:
                      stopDueToTime = true;
                      return _context7.abrupt("break", 31);

                    case 29:
                      _context7.next = 21;
                      break;

                    case 31:
                      _context7.next = 36;
                      break;

                    case 33:
                      _context7.prev = 33;
                      _context7.t0 = _context7["catch"](19);

                      _iterator2.e(_context7.t0);

                    case 36:
                      _context7.prev = 36;

                      _iterator2.f();

                      return _context7.finish(36);

                    case 39:
                      rawList = filtered;

                    case 40:
                      // 收集邀约用于后续获取详情
                      allInvitations.push.apply(allInvitations, getTargetInvitation_toConsumableArray(rawList));
                      list.push.apply(list, getTargetInvitation_toConsumableArray(rawList.map(function (item) {
                        return getTargetInvitation_objectSpread(getTargetInvitation_objectSpread({}, item), {}, {
                          invitation_group_status: status
                        });
                      })));

                      if (stopDueToTime) {
                        has_more = false;
                      } else {
                        has_more = data.has_more;
                      }

                      curPage++;
                      _context7.next = 49;
                      break;

                    case 46:
                      has_more = false;
                      errMsg = _msg2;
                      resCode = 1;

                    case 49:
                      if (!(list.length > 0 && (list.length >= 500 || !has_more))) {
                        _context7.next = 52;
                        break;
                      }

                      _context7.next = 52;
                      return common_newTask["a" /* default */].uploadTask({
                        code: 4,
                        result: {
                          list: list.splice(0, list.length),
                          totalData: null
                        }
                      }, task);

                    case 52:
                      _context7.next = 4;
                      break;

                    case 54:
                      // 获取失败的推入缓存，等重试再跑
                      if (resCode !== 0) errorCache.push({
                        status: status,
                        errMsg: errMsg,
                        curPage: curPage,
                        code: resCode
                      });

                    case 55:
                    case "end":
                      return _context7.stop();
                  }
                }
              }, _loop, null, [[19, 33, 36, 39]]);
            });

            _iterator.s();

          case 14:
            if ((_step = _iterator.n()).done) {
              _context8.next = 18;
              break;
            }

            return _context8.delegateYield(_loop(), "t0", 16);

          case 16:
            _context8.next = 14;
            break;

          case 18:
            _context8.next = 23;
            break;

          case 20:
            _context8.prev = 20;
            _context8.t1 = _context8["catch"](11);

            _iterator.e(_context8.t1);

          case 23:
            _context8.prev = 23;

            _iterator.f();

            return _context8.finish(23);

          case 26:
            if (!(allInvitations.length > 0)) {
              _context8.next = 32;
              break;
            }

            log["a" /* default */].setLog("\u5217\u8868\u83B7\u53D6\u5B8C\u6210\uFF0C\u5F00\u59CB\u83B7\u53D6".concat(allInvitations.length, "\u6761\u9080\u7EA6\u8BE6\u60C5"));
            _context8.next = 30;
            return fetchInvitationDetails(allInvitations.map(function (_ref8) {
              var id = _ref8.id;
              return id;
            }), task);

          case 30:
            _failDetailsSet = _context8.sent;

            // 如果有详情获取/上报失败，将 Set 转为数组保存到缓存
            if (_failDetailsSet.size > 0) {
              log["a" /* default */].setLog("\u6709".concat(_failDetailsSet.size, "\u6761\u9080\u7EA6\u8BE6\u60C5\u83B7\u53D6/\u4E0A\u62A5\u5931\u8D25\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8BD5"));
              task.failDetails = Array.from(_failDetailsSet);
            }

          case 32:
            _context8.next = 34;
            return getTargetInvitationTotal(task);

          case 34:
            totalData = _context8.sent;
            findErr = errorCache[0];
            code = findErr ? 1 : 0;
            msg = findErr && findErr.errMsg;
            task.msg = msg;
            task.resCache = {
              data: {
                errorCache: errorCache,
                failDetails: task.failDetails
              }
            };
            return _context8.abrupt("return", {
              code: code,
              msg: msg,
              data: {
                errorCache: errorCache,
                failDetails: task.failDetails
              },
              result: {
                totalData: totalData || null
              }
            });

          case 41:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee7, null, [[11, 20, 23, 26]]);
  }));
  return _getTargetInvitation.apply(this, arguments);
}

var getTargetInvitationDetail = /*#__PURE__*/function () {
  var _ref7 = getTargetInvitation_asyncToGenerator( /*#__PURE__*/getTargetInvitation_regeneratorRuntime().mark(function _callee6(task) {
    var failDetailsSet;
    return getTargetInvitation_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            task.invitationIds = ['7593229570195965751'];

            if (!(!task.invitationIds || task.invitationIds.length === 0)) {
              _context6.next = 4;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            return _context6.abrupt("return", {
              code: 1,
              msg: '没有invitationIds'
            });

          case 4:
            _context6.next = 6;
            return fetchInvitationDetails(task.invitationIds, task);

          case 6:
            failDetailsSet = _context6.sent;

            // 如果有详情获取/上报失败，将 Set 转为数组保存到缓存
            if (failDetailsSet.size > 0) {
              log["a" /* default */].setLog("\u6709".concat(failDetailsSet.size, "\u6761\u9080\u7EA6\u8BE6\u60C5\u83B7\u53D6/\u4E0A\u62A5\u5931\u8D25\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8BD5"));
              task.failDetails = Array.from(failDetailsSet);
            }

            return _context6.abrupt("return", {
              code: task.failDetails && task.failDetails.length > 0 ? 1 : 0,
              msg: task.failDetails && task.failDetails.length > 0 ? "\u6709".concat(task.failDetails.length, "\u6761\u9080\u7EA6\u8BE6\u60C5\u83B7\u53D6/\u4E0A\u62A5\u5931\u8D25\uFF0C\u5C06\u5728\u4E0B\u6B21\u91CD\u8BD5") : ''
            });

          case 9:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6);
  }));

  return function getTargetInvitationDetail(_x10) {
    return _ref7.apply(this, arguments);
  };
}();
// CONCATENATED MODULE: ./src/platform/tiktok/core/createTargetInvitation.js
function createTargetInvitation_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function createTargetInvitation_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? createTargetInvitation_ownKeys(Object(source), !0).forEach(function (key) { createTargetInvitation_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : createTargetInvitation_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function createTargetInvitation_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function createTargetInvitation_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = createTargetInvitation_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function createTargetInvitation_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return createTargetInvitation_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 createTargetInvitation_arrayLikeToArray(o, minLen); }

function createTargetInvitation_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; }

function createTargetInvitation_typeof(obj) { "@babel/helpers - typeof"; return createTargetInvitation_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; }, createTargetInvitation_typeof(obj); }

function createTargetInvitation_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ createTargetInvitation_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" == createTargetInvitation_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 createTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function createTargetInvitation_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { createTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { createTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





var ConflitCreatorIds = []; // 不符合条件的达人列表

var checkQuota = /*#__PURE__*/function () {
  var _ref = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee(task) {
    var query, _yield$tkPost, code, data, message, msg, _msg, _msg2;

    return createTargetInvitation_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context.sent;

            if (query) {
              _context.next = 6;
              break;
            }

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

          case 6:
            _context.next = 8;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/quota/connection/check"), query, {
              creator_ids: task.creator_ids
            });

          case 8:
            _yield$tkPost = _context.sent;
            code = _yield$tkPost.code;
            data = _yield$tkPost.data;
            message = _yield$tkPost.message;

            if (!(code === 0)) {
              _context.next = 21;
              break;
            }

            if (!(data && data.is_pass)) {
              _context.next = 15;
              break;
            }

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

          case 15:
            msg = "\u68C0\u67E5\u914D\u989D\u4E0D\u901A\u8FC7-----".concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context.abrupt("return", false);

          case 21:
            _msg = "\u68C0\u67E5\u914D\u989D\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(_msg);
            task.msg = _msg;
            return _context.abrupt("return", false);

          case 25:
            _context.next = 33;
            break;

          case 27:
            _context.prev = 27;
            _context.t0 = _context["catch"](0);
            _msg2 = "\u68C0\u67E5\u914D\u989D\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context.t0));
            log["a" /* default */].setLog(_msg2);
            task.msg = _msg2;
            return _context.abrupt("return", false);

          case 33:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 27]]);
  }));

  return function checkQuota(_x) {
    return _ref.apply(this, arguments);
  };
}();

var checkSensitiveText = /*#__PURE__*/function () {
  var _ref2 = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee2(task) {
    var _task$invitation_grou, _task$invitation_grou2, query, _yield$tkPost2, code, message, msg, _msg3, _msg4;

    return createTargetInvitation_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;

            if ((_task$invitation_grou = task.invitation_group) !== null && _task$invitation_grou !== void 0 && _task$invitation_grou.message) {
              _context2.next = 5;
              break;
            }

            task.msg = '邀约文案不能为空';
            log["a" /* default */].setLog(task.msg);
            return _context2.abrupt("return", false);

          case 5:
            _context2.next = 7;
            return Object(utils["a" /* getQueryString */])(task);

          case 7:
            query = _context2.sent;

            if (query) {
              _context2.next = 10;
              break;
            }

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

          case 10:
            _context2.next = 12;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/sensitive_text_check"), query, {
              text: (_task$invitation_grou2 = task.invitation_group) === null || _task$invitation_grou2 === void 0 ? void 0 : _task$invitation_grou2.message
            });

          case 12:
            _yield$tkPost2 = _context2.sent;
            code = _yield$tkPost2.code;
            message = _yield$tkPost2.message;

            if (!(code === 0)) {
              _context2.next = 26;
              break;
            }

            if (!(message === 'success')) {
              _context2.next = 20;
              break;
            }

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

          case 20:
            msg = "\u68C0\u67E5\u654F\u611F\u6587\u672C\u4E0D\u901A\u8FC7-----".concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context2.abrupt("return", false);

          case 24:
            _context2.next = 30;
            break;

          case 26:
            _msg3 = "\u68C0\u67E5\u654F\u611F\u6587\u672C\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(_msg3);
            task.msg = _msg3;
            return _context2.abrupt("return", false);

          case 30:
            _context2.next = 37;
            break;

          case 32:
            _context2.prev = 32;
            _context2.t0 = _context2["catch"](0);
            _msg4 = "\u68C0\u67E5\u654F\u611F\u6587\u672C\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0));
            log["a" /* default */].setLog(_msg4);
            task.msg = _msg4;

          case 37:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 32]]);
  }));

  return function checkSensitiveText(_x2) {
    return _ref2.apply(this, arguments);
  };
}(); // const getProductInfo = async (task, retry = 0) => {
//   try {
//     const query = await getQueryString(task)
//     if (!query) return false
//     const { code, product, message } = await tkPost(
//       `${task.host}/api/v1/oec/affiliate/seller/invitation/products_info`,
//       query,
// 			{
// 				product_id_list: task.product_id_list,
// 			}
//     )
//     if(code === 0) {
//       return product
//     } else {
//       const msg = `获取商品信息失败-----${message}`
//       log.setLog(msg)
//       task.msg = msg
//       return false
//     }
// 	} catch (e) {
// 		const msg = `获取商品信息失败-----原生接口返回：${isError(e)}`
// 		log.setLog(msg)
//     if (retry < 3) {
//       log.setLog(`获取商品信息---正在重试第${retry + 1}次........................`)
//       await delayed((retry + 1) * 1000)
//       return getProductInfo(task, retry + 1)
//     }
// 		task.msg = msg
//     return false
// 	}
// }


var checkCreatorConflict = /*#__PURE__*/function () {
  var _ref3 = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee3(task) {
    var iteration, maxIteration, query, params, _yield$tkPost3, code, data, message, _msg5, _ref4, conflict_cids, _ret, msg, _msg6;

    return createTargetInvitation_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            iteration = 0;
            maxIteration = 10; // 补齐达人操作最大循环次数

          case 3:
            if (!(iteration < maxIteration)) {
              _context3.next = 35;
              break;
            }

            log["a" /* default */].setLog("-----\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5E76\u8865\u9F50-----\u7B2C".concat(iteration + 1, "\u6B21-----"));
            iteration++;
            _context3.next = 8;
            return Object(utils["a" /* getQueryString */])(task);

          case 8:
            query = _context3.sent;

            if (query) {
              _context3.next = 11;
              break;
            }

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

          case 11:
            params = getCheckConflictParams(task);
            _context3.next = 14;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/conflict_check"), query, params);

          case 14:
            _yield$tkPost3 = _context3.sent;
            code = _yield$tkPost3.code;
            data = _yield$tkPost3.data;
            message = _yield$tkPost3.message;

            if (!(code !== 0)) {
              _context3.next = 23;
              break;
            }

            _msg5 = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(_msg5);
            task.msg = _msg5;
            return _context3.abrupt("return", false);

          case 23:
            _ref4 = data || {}, conflict_cids = _ref4.conflict_cids;

            if (!(conflict_cids && conflict_cids.length > 0)) {
              _context3.next = 32;
              break;
            }

            _ret = function () {
              var conflictEntries = [];
              conflict_cids.forEach(function (item) {
                var _ref5 = item || {},
                    conflict_type = _ref5.conflict_type,
                    _ref5$cids = _ref5.cids,
                    cids = _ref5$cids === void 0 ? [] : _ref5$cids;

                var msg = Number(conflict_type) === 4 ? '达人邀约重叠' : '达人不符合邀约条件';
                cids.forEach(function (cid) {
                  conflictEntries.push({
                    code: 0,
                    msg: msg,
                    creator_oec_id: String(cid)
                  });
                });
              });
              var conflictSet = new Set(conflictEntries.map(function (i) {
                return i.creator_oec_id;
              }));
              ConflitCreatorIds = ConflitCreatorIds.concat(conflictEntries); // 同步剔除检查参数中的达人
              // if (task.conflict_check_data && Array.isArray(task.conflict_check_data.creator_id_list)) {
              //   task.conflict_check_data.creator_id_list = task.conflict_check_data.creator_id_list.filter(item => {
              //     const cid = item?.base_info?.creator_oec_id
              //     return !conflictSet.has(String(cid))
              //   })
              // }
              // 同步剔除邀请参数中的达人

              if (task.invitation_group && Array.isArray(task.invitation_group.creator_id_list)) {
                task.invitation_group.creator_id_list = task.invitation_group.creator_id_list.filter(function (item) {
                  var _item$base_info;

                  var cid = item === null || item === void 0 ? void 0 : (_item$base_info = item.base_info) === null || _item$base_info === void 0 ? void 0 : _item$base_info.creator_oec_id;
                  return !conflictSet.has(String(cid));
                });
              } // 查询备用达人，补足至 inviteNum


              var fillCreatorFromBackupResult = createTargetInvitation_fillCreatorFromBackup(task);

              if (!fillCreatorFromBackupResult) {
                // 无法补齐达人（人数已满或无可用备用达人），跳出循环使用当前列表
                return {
                  v: true
                };
              } // 补齐达人后继续循环，直到无冲突或无法补齐


              return "continue";
            }();

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

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

          case 28:
            if (!(createTargetInvitation_typeof(_ret) === "object")) {
              _context3.next = 30;
              break;
            }

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

          case 30:
            _context3.next = 33;
            break;

          case 32:
            return _context3.abrupt("return", true);

          case 33:
            _context3.next = 3;
            break;

          case 35:
            msg = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u8D85\u8FC7\u6700\u5927\u8FED\u4EE3\u6B21\u6570".concat(maxIteration);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context3.abrupt("return", false);

          case 41:
            _context3.prev = 41;
            _context3.t0 = _context3["catch"](0);
            _msg6 = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0));
            log["a" /* default */].setLog(_msg6);
            task.msg = _msg6;
            return _context3.abrupt("return", false);

          case 47:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 41]]);
  }));

  return function checkCreatorConflict(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 使用备用达人补齐邀约人数


var createTargetInvitation_fillCreatorFromBackup = function fillCreatorFromBackup(task) {
  var inviteNum = Number(task.invite_num) || 0;

  if (inviteNum <= 0) {
    task.msg = "\u9080\u7EA6\u4EBA\u6570\u4E0D\u8DB3\uFF0C\u65E0\u6CD5\u8865\u9F50\u8FBE\u4EBA\u3002inviteNum:".concat(inviteNum);
    log["a" /* default */].setLog(task.msg);
    return false;
  }

  var backupList = Array.isArray(task.backup_creator_list) ? task.backup_creator_list : [];

  if (backupList.length === 0) {
    task.msg = "\u5907\u7528\u8FBE\u4EBA\u5217\u8868\u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8865\u9F50\u8FBE\u4EBA\u3002backup_creator_list:".concat(backupList);
    log["a" /* default */].setLog(task.msg);
    return false;
  }

  task.invitation_group = task.invitation_group || {}; // task.conflict_check_data = task.conflict_check_data || {}

  var invitationList = Array.isArray(task.invitation_group.creator_id_list) ? task.invitation_group.creator_id_list : []; // const conflictList = Array.isArray(task.conflict_check_data.creator_id_list) ? task.conflict_check_data.creator_id_list : []

  var existSet = new Set(invitationList.map(function (item) {
    var _item$base_info2;

    return String(item === null || item === void 0 ? void 0 : (_item$base_info2 = item.base_info) === null || _item$base_info2 === void 0 ? void 0 : _item$base_info2.creator_oec_id);
  }));
  var needNum = inviteNum - invitationList.length;

  if (needNum <= 0) {
    task.invitation_group.creator_id_list = invitationList; // task.conflict_check_data.creator_id_list = conflictList

    log["a" /* default */].setLog("\u9080\u7EA6\u4EBA\u6570\u5DF2\u6EE1\u8DB3\uFF0C\u65E0\u9700\u8865\u9F50\u8FBE\u4EBA\u3002inviteNum:".concat(inviteNum));
    return false;
  }

  var addItems = [];

  var _iterator = createTargetInvitation_createForOfIteratorHelper(backupList),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _item$base_info6;

      var item = _step.value;
      var cid = item === null || item === void 0 ? void 0 : (_item$base_info6 = item.base_info) === null || _item$base_info6 === void 0 ? void 0 : _item$base_info6.creator_oec_id;
      if (!cid) continue;
      var key = String(cid);
      if (existSet.has(key)) continue;
      addItems.push(item);
      existSet.add(key);
      if (addItems.length >= needNum) break;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  task.invitation_group.creator_id_list = invitationList.concat(addItems.map(function (item) {
    var _item$base_info3, _item$base_info4, _item$base_info5;

    return {
      base_info: {
        creator_id: (_item$base_info3 = item.base_info) === null || _item$base_info3 === void 0 ? void 0 : _item$base_info3.creator_id,
        nick_name: (_item$base_info4 = item.base_info) === null || _item$base_info4 === void 0 ? void 0 : _item$base_info4.nick_name,
        creator_oec_id: (_item$base_info5 = item.base_info) === null || _item$base_info5 === void 0 ? void 0 : _item$base_info5.creator_oec_id
      }
    };
  })); // task.conflict_check_data.creator_id_list = conflictList.concat(addItems)

  log["a" /* default */].setLog("-----\u8865\u9F50\u8FBE\u4EBA".concat(addItems.length, "\u4E2A-----"));
  return addItems.length > 0;
};

var getCheckConflictParams = function getCheckConflictParams(task) {
  var _ref6 = task.invitation_group || {},
      product_list = _ref6.product_list,
      creator_id_list = _ref6.creator_id_list; // const sourceProducts = Array.isArray(product_list) ? product_list : []


  return {
    invitation: {
      product_list: product_list,
      // product_list: (task.invitationProductInfo || []).map(item => {
      //   const matched = sourceProducts.find(p => String(p.product_id) === String(item.product_id))
      //   return matched ? { ...matched, ...item } : { ...item }
      // }),
      creator_id_list: creator_id_list.map(function (item) {
        return createTargetInvitation_objectSpread(createTargetInvitation_objectSpread({}, item), {}, {
          status: 1
        });
      })
    }
  };
};

var createInvitation = /*#__PURE__*/function () {
  var _ref7 = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee4(task) {
    var query, _yield$tkPost4, code, data, message, msg, _msg7, _msg8, _msg9;

    return createTargetInvitation_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context4.sent;

            if (query) {
              _context4.next = 6;
              break;
            }

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

          case 6:
            _context4.next = 8;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/create"), query, {
              invitation_group: task.invitation_group
            });

          case 8:
            _yield$tkPost4 = _context4.sent;
            code = _yield$tkPost4.code;
            data = _yield$tkPost4.data;
            message = _yield$tkPost4.message;

            if (!(code === 0)) {
              _context4.next = 16;
              break;
            }

            return _context4.abrupt("return", {
              code: 0,
              data: data
            });

          case 16:
            if (![50001702].includes(code)) {
              _context4.next = 23;
              break;
            }

            msg = "\u5B58\u5728\u5546\u54C1\u6216\u8FBE\u4EBA\u4E0D\u7B26\u5408TikTok\u521B\u5EFA\u5B9A\u5411\u9080\u7EA6\u8981\u6C42\uFF0C\u8BE5\u5B9A\u5411\u9080\u7EA6\u521B\u5EFA\u5931\u8D25";
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context4.abrupt("return", {
              code: 2
            });

          case 23:
            if (![16024019].includes(code)) {
              _context4.next = 31;
              break;
            }

            // 达人配额不足
            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            _msg7 = message;
            log["a" /* default */].setLog(_msg7);
            task.msg = _msg7;
            return _context4.abrupt("return", {
              code: 2
            });

          case 31:
            _msg8 = "\u521B\u5EFA\u9080\u7EA6\u5931\u8D25\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A".concat(message);
            log["a" /* default */].setLog(_msg8);
            task.msg = _msg8;
            return _context4.abrupt("return", {
              code: 1
            });

          case 35:
            _context4.next = 43;
            break;

          case 37:
            _context4.prev = 37;
            _context4.t0 = _context4["catch"](0);
            _msg9 = "\u521B\u5EFA\u9080\u7EA6\u5931\u8D25\uFF0C\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0));
            log["a" /* default */].setLog(_msg9);
            task.msg = _msg9;
            return _context4.abrupt("return", {
              code: 1
            });

          case 43:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 37]]);
  }));

  return function createInvitation(_x4) {
    return _ref7.apply(this, arguments);
  };
}(); // 检测不合格商品或达人


var checkUnqualifiedProductOrCreator = /*#__PURE__*/function () {
  var _ref8 = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee5(task) {
    var unqualifiedProducts;
    return createTargetInvitation_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.next = 2;
            return checkUnqualifiedProduct(task);

          case 2:
            unqualifiedProducts = _context5.sent;

            if (unqualifiedProducts) {
              _context5.next = 6;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            return _context5.abrupt("return", false);

          case 6:
            if (unqualifiedProducts.length > 0) {
              // task.error_time = TEMU_MAX_RETRY_COUNT
              task.msg = "\u5B58\u5728\u4E0D\u7B26\u5408\u6761\u4EF6\u7684\u5546\u54C1\uFF0C\u5DF2\u5254\u9664\uFF0Cid\uFF1A".concat(unqualifiedProducts.join(','));
            } // 剔除不合格商品，重新创建邀约


            task.invitation_group.product_list = task.invitation_group.product_list.filter(function (item) {
              return !unqualifiedProducts.includes(item.product_id);
            });
            return _context5.abrupt("return", unqualifiedProducts);

          case 9:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function checkUnqualifiedProductOrCreator(_x5) {
    return _ref8.apply(this, arguments);
  };
}(); // 检测不合格商品


var checkUnqualifiedProduct = /*#__PURE__*/function () {
  var _ref9 = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee6(task) {
    var _task$invitation_grou3, _task$invitation_grou4, query, product_id_list, _yield$tkPost5, code, _yield$tkPost5$produc, product, message, msg, _msg10;

    return createTargetInvitation_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;
            _context6.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context6.sent;

            if (query) {
              _context6.next = 6;
              break;
            }

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

          case 6:
            product_id_list = ((_task$invitation_grou3 = task.invitation_group) === null || _task$invitation_grou3 === void 0 ? void 0 : (_task$invitation_grou4 = _task$invitation_grou3.product_list) === null || _task$invitation_grou4 === void 0 ? void 0 : _task$invitation_grou4.map(function (item) {
              return item.product_id;
            })) || [];
            _context6.next = 9;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation/products_info"), query, {
              product_id_list: product_id_list
            });

          case 9:
            _yield$tkPost5 = _context6.sent;
            code = _yield$tkPost5.code;
            _yield$tkPost5$produc = _yield$tkPost5.product;
            product = _yield$tkPost5$produc === void 0 ? [] : _yield$tkPost5$produc;
            message = _yield$tkPost5.message;

            if (!(code === 0)) {
              _context6.next = 18;
              break;
            }

            return _context6.abrupt("return", product_id_list.filter(function (product_id) {
              return !product.find(function (item) {
                return item.product_id == product_id;
              });
            }));

          case 18:
            msg = "\u68C0\u6D4B\u4E0D\u5408\u683C\u5546\u54C1\u5931\u8D25\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A".concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context6.abrupt("return", false);

          case 22:
            _context6.next = 30;
            break;

          case 24:
            _context6.prev = 24;
            _context6.t0 = _context6["catch"](0);
            _msg10 = "\u68C0\u6D4B\u4E0D\u5408\u683C\u5546\u54C1\u6216\u8FBE\u4EBA\u5931\u8D25\uFF0C\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context6.t0));
            log["a" /* default */].setLog(_msg10);
            task.msg = _msg10;
            return _context6.abrupt("return", false);

          case 30:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[0, 24]]);
  }));

  return function checkUnqualifiedProduct(_x6) {
    return _ref9.apply(this, arguments);
  };
}(); // 入口函数


function createTargetInvitation(_x7) {
  return _createTargetInvitation.apply(this, arguments);
}

function _createTargetInvitation() {
  _createTargetInvitation = createTargetInvitation_asyncToGenerator( /*#__PURE__*/createTargetInvitation_regeneratorRuntime().mark(function _callee7(task) {
    var checkSensitiveTextResult, checkCreatorResult, checkUnqualifiedProductOrCreatorResult, createInvitationResult, _ref10, invitation, _task$invitation_grou5;

    return createTargetInvitation_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            // 每次任务开始重置冲突达人记录
            ConflitCreatorIds = []; // 1、检查配额
            // const checkQuotaResult = await checkQuota(task)
            // if (!checkQuotaResult) {
            // 	return {
            //     code: 1,
            //     msg: task.msg
            //   }
            // }
            // 2、检查敏感文本

            _context7.next = 3;
            return checkSensitiveText(task);

          case 3:
            checkSensitiveTextResult = _context7.sent;

            if (checkSensitiveTextResult) {
              _context7.next = 6;
              break;
            }

            return _context7.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 6:
            _context7.next = 8;
            return checkCreatorConflict(task);

          case 8:
            checkCreatorResult = _context7.sent;

            if (checkCreatorResult) {
              _context7.next = 11;
              break;
            }

            return _context7.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 11:
            _context7.next = 13;
            return checkUnqualifiedProductOrCreator(task);

          case 13:
            checkUnqualifiedProductOrCreatorResult = _context7.sent;

            if (checkUnqualifiedProductOrCreatorResult) {
              _context7.next = 16;
              break;
            }

            return _context7.abrupt("return", {
              code: 2,
              msg: task.msg
            });

          case 16:
            if (!(task.invitation_group.creator_id_list.length === 0)) {
              _context7.next = 19;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            return _context7.abrupt("return", {
              code: 2,
              // 2是通知业务方此任务不在重试
              msg: task.msg
            });

          case 19:
            _context7.next = 21;
            return createInvitation(task);

          case 21:
            createInvitationResult = _context7.sent;
            _ref10 = createInvitationResult.data || {}, invitation = _ref10.invitation;

            if (!(createInvitationResult.code === 0 && invitation.id)) {
              _context7.next = 27;
              break;
            }

            return _context7.abrupt("return", {
              code: 0,
              msg: task.msg || "",
              result: {
                message: "success",
                data: {
                  id: invitation.id,
                  creatorIds: ConflitCreatorIds.concat((((_task$invitation_grou5 = task.invitation_group) === null || _task$invitation_grou5 === void 0 ? void 0 : _task$invitation_grou5.creator_id_list) || []).map(function (item) {
                    var _item$base_info7;

                    return {
                      code: 1,
                      msg: '',
                      creator_oec_id: (_item$base_info7 = item.base_info) === null || _item$base_info7 === void 0 ? void 0 : _item$base_info7.creator_oec_id
                    };
                  })),
                  productIds: checkUnqualifiedProductOrCreatorResult
                }
              }
            });

          case 27:
            return _context7.abrupt("return", {
              code: createInvitationResult.code,
              msg: task.msg
            });

          case 28:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7);
  }));
  return _createTargetInvitation.apply(this, arguments);
}
// CONCATENATED MODULE: ./src/platform/tiktok/core/updateTargetInvitation.js
function updateTargetInvitation_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function updateTargetInvitation_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? updateTargetInvitation_ownKeys(Object(source), !0).forEach(function (key) { updateTargetInvitation_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : updateTargetInvitation_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function updateTargetInvitation_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function updateTargetInvitation_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = updateTargetInvitation_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function updateTargetInvitation_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return updateTargetInvitation_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 updateTargetInvitation_arrayLikeToArray(o, minLen); }

function updateTargetInvitation_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; }

function updateTargetInvitation_typeof(obj) { "@babel/helpers - typeof"; return updateTargetInvitation_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; }, updateTargetInvitation_typeof(obj); }

function updateTargetInvitation_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ updateTargetInvitation_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" == updateTargetInvitation_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 updateTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function updateTargetInvitation_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { updateTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { updateTargetInvitation_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





var allUsedCreatorIds = []; // 记录所有被用过的达人，用于上报成功和失败原因

var getInvitationInfo = /*#__PURE__*/function () {
  var _ref = updateTargetInvitation_asyncToGenerator( /*#__PURE__*/updateTargetInvitation_regeneratorRuntime().mark(function _callee(task) {
    var query, _yield$tkPost, code, data, message, _data$invitation, msg, _msg;

    return updateTargetInvitation_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context.sent;

            if (query) {
              _context.next = 6;
              break;
            }

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

          case 6:
            _context.next = 8;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/detail"), query, {
              invitation_group_id: task.id
            });

          case 8:
            _yield$tkPost = _context.sent;
            code = _yield$tkPost.code;
            data = _yield$tkPost.data;
            message = _yield$tkPost.message;

            if (!(code === 0)) {
              _context.next = 21;
              break;
            }

            if (!((_data$invitation = data.invitation) !== null && _data$invitation !== void 0 && _data$invitation.flash_sale_info)) {
              _context.next = 18;
              break;
            }

            task.msg = "\u9080\u7EA6\u4FE1\u606F\u4E2D\u5305\u542B\u79D2\u6740\u6D3B\u52A8\uFF0C\u6682\u4E0D\u652F\u6301\u7F16\u8F91\u9080\u7EA6";
            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            log["a" /* default */].setLog(task.msg);
            return _context.abrupt("return", false);

          case 18:
            return _context.abrupt("return", data);

          case 21:
            msg = "\u83B7\u53D6\u9080\u7EA6\u4FE1\u606F\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context.abrupt("return", false);

          case 25:
            _context.next = 32;
            break;

          case 27:
            _context.prev = 27;
            _context.t0 = _context["catch"](0);
            _msg = "\u83B7\u53D6\u9080\u7EA6\u4FE1\u606F\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context.t0));
            log["a" /* default */].setLog(_msg);
            task.msg = _msg;

          case 32:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 27]]);
  }));

  return function getInvitationInfo(_x) {
    return _ref.apply(this, arguments);
  };
}();

var updateInvitation = /*#__PURE__*/function () {
  var _ref2 = updateTargetInvitation_asyncToGenerator( /*#__PURE__*/updateTargetInvitation_regeneratorRuntime().mark(function _callee2(task, infoRes, customCreatorIds) {
    var query, params, _yield$tkPost2, code, data, message, msg, _msg2;

    return updateTargetInvitation_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            _context2.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context2.sent;

            if (query) {
              _context2.next = 6;
              break;
            }

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

          case 6:
            params = getUpdateParams(task, infoRes, customCreatorIds);
            _context2.next = 9;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/update"), query, params);

          case 9:
            _yield$tkPost2 = _context2.sent;
            code = _yield$tkPost2.code;
            data = _yield$tkPost2.data;
            message = _yield$tkPost2.message;

            if (!(code === 0)) {
              _context2.next = 18;
              break;
            }

            allUsedCreatorIds = allUsedCreatorIds.concat(customCreatorIds.map(function (i) {
              return {
                code: 1,
                // 成功
                msg: "",
                creator_oec_id: i.creator_oec_id
              };
            }));
            return _context2.abrupt("return", true);

          case 18:
            msg = "-----\u66F4\u65B0\u9080\u7EA6\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context2.abrupt("return", false);

          case 22:
            _context2.next = 30;
            break;

          case 24:
            _context2.prev = 24;
            _context2.t0 = _context2["catch"](0);
            _msg2 = "-----\u66F4\u65B0\u9080\u7EA6\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0));
            log["a" /* default */].setLog(_msg2);
            task.msg = _msg2;
            return _context2.abrupt("return", false);

          case 30:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 24]]);
  }));

  return function updateInvitation(_x2, _x3, _x4) {
    return _ref2.apply(this, arguments);
  };
}();

var getUpdateParams = function getUpdateParams(task, infoRes, customCreatorIds) {
  if (!infoRes) return false;
  var invitation = infoRes.invitation;
  var params = {
    id: invitation.id,
    name: invitation.name,
    message: invitation.message,
    contacts_info: invitation.contacts_info,
    free_sample_rule: invitation.free_sample_rule,
    end_time: invitation.end_time,
    product_list: invitation.product_list.map(function (item) {
      return {
        product_id: item.product_id,
        target_commission: item.target_commission
      };
    }),
    delivery_requirements: invitation.delivery_requirements,
    has_flash_sale: invitation.flash_sale_info && invitation.flash_sale_info.flash_sale_status === 1
  };
  params.creator_id_list = customCreatorIds.map(function (i) {
    return {
      base_info: {
        creator_id: i.creator_id,
        nick_name: i.nick_name,
        creator_oec_id: i.creator_oec_id
      }
    };
  }); // 秒杀活动需以下参数
  // if(invitation.flash_sale_info && invitation.flash_sale_info.flash_sale_status === 1) {
  //   const {creator_id, end_time, start_time, limit_one_product,flash_sale_products} = invitation.flash_sale_info
  //   params.flash_sale_info = {
  //     creator_id,
  //     end_time,
  //     start_time,
  //     limit_one_product: Boolean(limit_one_product),
  //     flash_sale_products: flash_sale_products.map(item => ({product_id:item.product_id, skus:item.skus.map(sku => {
  //       const {fixed_sale_price, flash_sale_include, product_id, sku_id, sku_name, exclusive_inventory} = sku
  //       const newSku = {
  //         fixed_sale_price: {
  //           price: fixed_sale_price.price || "",
  //         },
  //         flash_sale_include,
  //         product_id,
  //         sku_id,
  //         sku_name,
  //       }
  //       if(exclusive_inventory) newSku.exclusive_inventory = exclusive_inventory
  //       return newSku
  //     })}))
  //   }
  // }

  return {
    invitation: params
  };
};

var updateTargetInvitation_checkCreatorConflict = /*#__PURE__*/function () {
  var _ref3 = updateTargetInvitation_asyncToGenerator( /*#__PURE__*/updateTargetInvitation_regeneratorRuntime().mark(function _callee3(task) {
    var iteration, maxIteration, query, params, _yield$tkPost3, code, data, message, _msg3, _ref4, conflict_cids, _ret, msg, _msg4;

    return updateTargetInvitation_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            iteration = 0;
            maxIteration = 10; // 补齐达人操作最大循环次数

          case 3:
            if (!(iteration < maxIteration)) {
              _context3.next = 35;
              break;
            }

            log["a" /* default */].setLog("-----\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5E76\u8865\u9F50-----\u7B2C".concat(iteration + 1, "\u6B21-----"));
            iteration++;
            _context3.next = 8;
            return Object(utils["a" /* getQueryString */])(task);

          case 8:
            query = _context3.sent;

            if (query) {
              _context3.next = 11;
              break;
            }

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

          case 11:
            params = updateTargetInvitation_getCheckConflictParams(task);
            _context3.next = 14;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/conflict_check"), query, params);

          case 14:
            _yield$tkPost3 = _context3.sent;
            code = _yield$tkPost3.code;
            data = _yield$tkPost3.data;
            message = _yield$tkPost3.message;

            if (!(code !== 0)) {
              _context3.next = 23;
              break;
            }

            _msg3 = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(_msg3);
            task.msg = _msg3;
            return _context3.abrupt("return", false);

          case 23:
            _ref4 = data || {}, conflict_cids = _ref4.conflict_cids;

            if (!(conflict_cids && conflict_cids.length > 0)) {
              _context3.next = 32;
              break;
            }

            _ret = function () {
              var conflictEntries = [];
              conflict_cids.forEach(function (item) {
                var _ref5 = item || {},
                    conflict_type = _ref5.conflict_type,
                    _ref5$cids = _ref5.cids,
                    cids = _ref5$cids === void 0 ? [] : _ref5$cids;

                var msg = Number(conflict_type) === 4 ? '达人邀约重叠' : '达人不符合邀约条件';
                cids.forEach(function (cid) {
                  conflictEntries.push({
                    code: 0,
                    msg: msg,
                    creator_oec_id: String(cid)
                  });
                });
              });
              var conflictSet = new Set(conflictEntries.map(function (i) {
                return i.creator_oec_id;
              }));
              allUsedCreatorIds = allUsedCreatorIds.concat(conflictEntries); // 同步剔除检查参数中的达人
              // if (task.conflict_check_data && Array.isArray(task.conflict_check_data.creator_id_list)) {
              //   task.conflict_check_data.creator_id_list = task.conflict_check_data.creator_id_list.filter(item => {
              //     const cid = item?.base_info?.creator_oec_id
              //     return !conflictSet.has(String(cid))
              //   })
              // }
              // 同步剔除邀请参数中的达人

              if (task.invitation_group && Array.isArray(task.invitation_group.creator_id_list)) {
                task.invitation_group.creator_id_list = task.invitation_group.creator_id_list.filter(function (item) {
                  var _item$base_info;

                  var cid = item === null || item === void 0 ? void 0 : (_item$base_info = item.base_info) === null || _item$base_info === void 0 ? void 0 : _item$base_info.creator_oec_id;
                  return !conflictSet.has(String(cid));
                });
              } // 查询备用达人，补足至 inviteNum


              var fillCreatorFromBackupResult = updateTargetInvitation_fillCreatorFromBackup(task);

              if (!fillCreatorFromBackupResult) {
                // 无法补齐达人（人数已满或无可用备用达人），跳出循环使用当前列表
                return {
                  v: true
                };
              } // 补齐达人后继续循环，直到无冲突或无法补齐


              return "continue";
            }();

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

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

          case 28:
            if (!(updateTargetInvitation_typeof(_ret) === "object")) {
              _context3.next = 30;
              break;
            }

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

          case 30:
            _context3.next = 33;
            break;

          case 32:
            return _context3.abrupt("return", true);

          case 33:
            _context3.next = 3;
            break;

          case 35:
            msg = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u8D85\u8FC7\u6700\u5927\u8FED\u4EE3\u6B21\u6570".concat(maxIteration);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context3.abrupt("return", false);

          case 41:
            _context3.prev = 41;
            _context3.t0 = _context3["catch"](0);
            _msg4 = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0));
            log["a" /* default */].setLog(_msg4);
            task.msg = _msg4;
            return _context3.abrupt("return", false);

          case 47:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 41]]);
  }));

  return function checkCreatorConflict(_x5) {
    return _ref3.apply(this, arguments);
  };
}(); // 使用新达人补齐邀约人数


var updateTargetInvitation_fillCreatorFromBackup = function fillCreatorFromBackup(task) {
  var inviteNum = Number(task.invite_num) || 0;

  if (inviteNum <= 0) {
    task.msg = "-----\u9080\u7EA6\u4EBA\u6570\u4E0D\u8DB3\uFF0C\u65E0\u6CD5\u8865\u9F50\u8FBE\u4EBA\u3002inviteNum:".concat(inviteNum);
    log["a" /* default */].setLog(task.msg);
    return false;
  }

  var backupList = Array.isArray(task.backup_creator_list) ? task.backup_creator_list : [];

  if (backupList.length === 0) {
    task.msg = "-----\u65B0\u8FBE\u4EBA\u5217\u8868\u4E3A\u7A7A\uFF0C\u65E0\u6CD5\u8865\u9F50\u8FBE\u4EBA\u3002new_creator_list:".concat(backupList);
    log["a" /* default */].setLog(task.msg);
    return false;
  }

  task.invitation_group = task.invitation_group || {}; // task.conflict_check_data = task.conflict_check_data || {}

  var invitationList = Array.isArray(task.invitation_group.creator_id_list) ? task.invitation_group.creator_id_list : []; // const conflictList = Array.isArray(task.conflict_check_data.creator_id_list) ? task.conflict_check_data.creator_id_list : []

  var existSet = new Set(invitationList.map(function (item) {
    var _item$base_info2;

    return String(item === null || item === void 0 ? void 0 : (_item$base_info2 = item.base_info) === null || _item$base_info2 === void 0 ? void 0 : _item$base_info2.creator_oec_id);
  }));
  var needNum = inviteNum - invitationList.length;

  if (needNum <= 0) {
    task.invitation_group.creator_id_list = invitationList; // task.conflict_check_data.creator_id_list = conflictList

    task.msg = "-----\u9080\u7EA6\u4EBA\u6570\u5DF2\u6EE1\u8DB3\uFF0C\u65E0\u9700\u8865\u9F50\u8FBE\u4EBA\u3002inviteNum:".concat(inviteNum);
    log["a" /* default */].setLog(task.msg);
    return false;
  }

  var addItems = [];

  var _iterator = updateTargetInvitation_createForOfIteratorHelper(backupList),
      _step;

  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _item$base_info6;

      var item = _step.value;
      var cid = item === null || item === void 0 ? void 0 : (_item$base_info6 = item.base_info) === null || _item$base_info6 === void 0 ? void 0 : _item$base_info6.creator_oec_id;
      if (!cid) continue;
      var key = String(cid);
      if (existSet.has(key)) continue;
      addItems.push(item);
      existSet.add(key);
      if (addItems.length >= needNum) break;
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }

  task.invitation_group.creator_id_list = invitationList.concat(addItems.map(function (item) {
    var _item$base_info3, _item$base_info4, _item$base_info5;

    return {
      base_info: {
        creator_id: (_item$base_info3 = item.base_info) === null || _item$base_info3 === void 0 ? void 0 : _item$base_info3.creator_id,
        nick_name: (_item$base_info4 = item.base_info) === null || _item$base_info4 === void 0 ? void 0 : _item$base_info4.nick_name,
        creator_oec_id: (_item$base_info5 = item.base_info) === null || _item$base_info5 === void 0 ? void 0 : _item$base_info5.creator_oec_id
      }
    };
  })); // task.conflict_check_data.creator_id_list = conflictList.concat(addItems)

  log["a" /* default */].setLog("-----\u8865\u9F50\u8FBE\u4EBA".concat(addItems.length, "\u4E2A-----"));
  return addItems.length > 0;
};

var updateTargetInvitation_getCheckConflictParams = function getCheckConflictParams(task) {
  var _ref6 = task.invitation_group || {},
      product_list = _ref6.product_list,
      creator_id_list = _ref6.creator_id_list; // const sourceProducts = Array.isArray(product_list) ? product_list : []


  return {
    invitation: {
      product_list: product_list,
      // 检查冲突确实商品信息字段，从后端接口补齐
      // product_list: (task.invitationProductInfo || []).map(item => {
      //   const matched = sourceProducts.find(p => String(p.product_id) === String(item.product_id))
      //   return matched ? { 
      // 		status: matched.status,
      // 		create_time: matched.create_time,
      // 		sales: matched.sales,
      // 		 ...item 
      // 		}
      // 		  :
      // 		{ ...item }
      // }),
      creator_id_list: creator_id_list.map(function (item) {
        return updateTargetInvitation_objectSpread(updateTargetInvitation_objectSpread({}, item), {}, {
          status: 1
        });
      })
    }
  };
}; // 入口函数


function updateTargetInvitation(_x6) {
  return _updateTargetInvitation.apply(this, arguments);
}

function _updateTargetInvitation() {
  _updateTargetInvitation = updateTargetInvitation_asyncToGenerator( /*#__PURE__*/updateTargetInvitation_regeneratorRuntime().mark(function _callee5(task) {
    var infoRes, invitation, allCreators, repliedcreatorIds, noRepliedcreatorIds, updateRes1, updateRes2, newCreatorIds, inviteNum, fillCreatorIds, baseCreatorIds, mergedCreatorIds, updateRes;
    return updateTargetInvitation_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            allUsedCreatorIds = [];
            _context5.next = 3;
            return getInvitationInfo(task);

          case 3:
            infoRes = _context5.sent;

            if (infoRes) {
              _context5.next = 6;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 6:
            invitation = infoRes.invitation || {};
            task.invitation_group = task.invitation_group || {};
            task.invitation_group.product_list = invitation.product_list || [];
            allCreators = (invitation.creator_id_list || []).map(function (i) {
              return (i === null || i === void 0 ? void 0 : i.base_info) || {};
            });
            repliedcreatorIds = [];
            noRepliedcreatorIds = [];
            allCreators.forEach(function (i) {
              if (Number(i.product_add_cnt) > 0) repliedcreatorIds.push(i);else noRepliedcreatorIds.push(i);
            });

            if (!(task.invite_type === 0)) {
              _context5.next = 26;
              break;
            }

            _context5.next = 16;
            return updateInvitation(task, infoRes, repliedcreatorIds);

          case 16:
            updateRes1 = _context5.sent;

            if (updateRes1) {
              _context5.next = 19;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 19:
            _context5.next = 21;
            return updateInvitation(task, infoRes, allCreators);

          case 21:
            updateRes2 = _context5.sent;

            if (updateRes2) {
              _context5.next = 24;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 24:
            _context5.next = 42;
            break;

          case 26:
            // 2：加入新达人（继续邀约新达人或重试该邀约）
            newCreatorIds = Array.isArray(task.new_creator_ids) ? task.new_creator_ids : [];
            inviteNum = Number(task.invite_num) || 0;

            fillCreatorIds = /*#__PURE__*/function () {
              var _ref7 = updateTargetInvitation_asyncToGenerator( /*#__PURE__*/updateTargetInvitation_regeneratorRuntime().mark(function _callee4(baseList) {
                var needNum, newList, checkCreatorConflictResult;
                return updateTargetInvitation_regeneratorRuntime().wrap(function _callee4$(_context4) {
                  while (1) {
                    switch (_context4.prev = _context4.next) {
                      case 0:
                        if (!(baseList.length >= inviteNum)) {
                          _context4.next = 2;
                          break;
                        }

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

                      case 2:
                        needNum = inviteNum - baseList.length;
                        newList = baseList.concat(newCreatorIds.slice(0, needNum)); // task.conflict_check_data.creator_id_list = newList
                        // task.conflict_check_data.product_list = infoRes.invitation?.product_list || []
                        // task.invitationProductInfo = infoRes.invitation?.product_list || []

                        task.invitation_group.creator_id_list = newList; // task.backup_creator_list = newCreatorIds

                        _context4.next = 7;
                        return updateTargetInvitation_checkCreatorConflict(task);

                      case 7:
                        checkCreatorConflictResult = _context4.sent;

                        if (checkCreatorConflictResult) {
                          _context4.next = 12;
                          break;
                        }

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

                      case 12:
                        return _context4.abrupt("return", task.invitation_group.creator_id_list);

                      case 13:
                      case "end":
                        return _context4.stop();
                    }
                  }
                }, _callee4);
              }));

              return function fillCreatorIds(_x7) {
                return _ref7.apply(this, arguments);
              };
            }(); // 2.1 补齐达人至InviteNum


            baseCreatorIds = task.invite_type === 1 ? repliedcreatorIds : allCreators;
            _context5.next = 32;
            return fillCreatorIds(baseCreatorIds);

          case 32:
            mergedCreatorIds = _context5.sent;

            if (!(mergedCreatorIds && mergedCreatorIds.length > 0)) {
              _context5.next = 41;
              break;
            }

            _context5.next = 36;
            return updateInvitation(task, infoRes, mergedCreatorIds.map(function (i) {
              return (i === null || i === void 0 ? void 0 : i.base_info) || {};
            }));

          case 36:
            updateRes = _context5.sent;

            if (updateRes) {
              _context5.next = 39;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg,
              result: {
                creatorIds: allUsedCreatorIds || []
              }
            });

          case 39:
            _context5.next = 42;
            break;

          case 41:
            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg,
              result: {
                creatorIds: allUsedCreatorIds || []
              }
            });

          case 42:
            return _context5.abrupt("return", {
              code: 0,
              msg: task.msg || "",
              result: {
                message: "success",
                data: {},
                creatorIds: allUsedCreatorIds || [],
                removeCreatorIds: task.invite_type === 0 ? [] : noRepliedcreatorIds.map(function (item) {
                  return item.creator_oec_id;
                }) || [],
                invite_num: task.invite_num
              }
            });

          case 43:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));
  return _updateTargetInvitation.apply(this, arguments);
}
// CONCATENATED MODULE: ./src/platform/tiktok/core/getCreators.js
function getCreators_typeof(obj) { "@babel/helpers - typeof"; return getCreators_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; }, getCreators_typeof(obj); }

function getCreators_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = getCreators_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function getCreators_toConsumableArray(arr) { return getCreators_arrayWithoutHoles(arr) || getCreators_iterableToArray(arr) || getCreators_unsupportedIterableToArray(arr) || getCreators_nonIterableSpread(); }

function getCreators_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getCreators_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getCreators_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 getCreators_arrayLikeToArray(o, minLen); }

function getCreators_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getCreators_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getCreators_arrayLikeToArray(arr); }

function getCreators_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; }

function getCreators_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getCreators_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" == getCreators_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 getCreators_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getCreators_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getCreators_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getCreators_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





var PAGE_SIZE = 12;
var MAX_LOOP = 200; // 防止异常循环

var CONFLICT_CHECK_BATCH_SIZE = 50; // TikTok API 限制每次冲突检查最多 50 个达人

var getCreators_search_key = ''; // 每次find接口都会返回search_key，用于下一页的请求（首次除外）

var fetchCreatorPage = /*#__PURE__*/function () {
  var _ref = getCreators_asyncToGenerator( /*#__PURE__*/getCreators_regeneratorRuntime().mark(function _callee(task, curPage) {
    var query, params, _yield$tkPost, code, next_pagination, creator_profile_list, creator_connect_info_list, msg, message, _ref2, _ref2$search_key, nextKey, _ref2$has_more, has_more, profileList, connectList, _msg, _msg2;

    return getCreators_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(utils["a" /* getQueryString */])(task);

          case 3:
            query = _context.sent;

            if (query) {
              _context.next = 6;
              break;
            }

            return _context.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 6:
            params = getFetchCreatorParams(task, curPage);
            _context.next = 9;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/creator/marketplace/find"), query, params);

          case 9:
            _yield$tkPost = _context.sent;
            code = _yield$tkPost.code;
            next_pagination = _yield$tkPost.next_pagination;
            creator_profile_list = _yield$tkPost.creator_profile_list;
            creator_connect_info_list = _yield$tkPost.creator_connect_info_list;
            msg = _yield$tkPost.msg;
            message = _yield$tkPost.message;

            if (!(code === 0)) {
              _context.next = 24;
              break;
            }

            _ref2 = next_pagination || {}, _ref2$search_key = _ref2.search_key, nextKey = _ref2$search_key === void 0 ? '' : _ref2$search_key, _ref2$has_more = _ref2.has_more, has_more = _ref2$has_more === void 0 ? false : _ref2$has_more;
            getCreators_search_key = nextKey || '';
            profileList = creator_profile_list || [];
            connectList = creator_connect_info_list || [];
            return _context.abrupt("return", {
              code: 0,
              profileList: profileList,
              connectList: connectList,
              has_more: has_more
            });

          case 24:
            _msg = "\u67E5\u8BE2\u53EF\u9080\u7EA6\u8FBE\u4EBA-\u83B7\u53D6\u8FBE\u4EBA\u5217\u8868\u5931\u8D25-----".concat(msg || message);
            log["a" /* default */].setLog(_msg);
            task.msg = _msg;
            return _context.abrupt("return", {
              code: 1,
              _msg: _msg
            });

          case 28:
            _context.next = 36;
            break;

          case 30:
            _context.prev = 30;
            _context.t0 = _context["catch"](0);
            _msg2 = "\u67E5\u8BE2\u53EF\u9080\u7EA6\u8FBE\u4EBA-\u83B7\u53D6\u8FBE\u4EBA\u5217\u8868\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            log["a" /* default */].setLog(_msg2);
            task.msg = _msg2;
            return _context.abrupt("return", {
              code: 1,
              msg: _msg2
            });

          case 36:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 30]]);
  }));

  return function fetchCreatorPage(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();

var getFetchCreatorParams = function getFetchCreatorParams(task, curPage) {
  return {
    query: task.query || '',
    query_type: task.query ? 1 : undefined,
    algorithm: 1,
    pagination: curPage > 0 ? {
      next_item_cursor: curPage * PAGE_SIZE,
      page: curPage,
      size: PAGE_SIZE,
      search_key: getCreators_search_key
    } : {},
    filter_params: task.filter_params || {}
  };
};

var getCreators_getCheckConflictParams = function getCheckConflictParams(task, creatorList) {
  var product_list = task.product_list || [];
  var creator_id_list = creatorList.map(function (item) {
    var _item$baseInfo;

    return {
      base_info: {
        creator_oec_id: (_item$baseInfo = item.baseInfo) === null || _item$baseInfo === void 0 ? void 0 : _item$baseInfo.creator_oec_id
      }
    };
  });
  return {
    invitation: {
      product_list: product_list,
      creator_id_list: creator_id_list
    }
  };
};

var checkConflict = /*#__PURE__*/function () {
  var _ref3 = getCreators_asyncToGenerator( /*#__PURE__*/getCreators_regeneratorRuntime().mark(function _callee2(task, creatorList) {
    var query, params, _yield$tkPost2, code, data, message, msg, _ref4, conflict_cids, _msg3;

    return getCreators_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;

            if (creatorList.length) {
              _context2.next = 3;
              break;
            }

            return _context2.abrupt("return", []);

          case 3:
            _context2.next = 5;
            return Object(utils["a" /* getQueryString */])(task);

          case 5:
            query = _context2.sent;

            if (query) {
              _context2.next = 8;
              break;
            }

            return _context2.abrupt("return", []);

          case 8:
            params = getCreators_getCheckConflictParams(task, creatorList);
            _context2.next = 11;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/seller/invitation_group/conflict_check"), query, params);

          case 11:
            _yield$tkPost2 = _context2.sent;
            code = _yield$tkPost2.code;
            data = _yield$tkPost2.data;
            message = _yield$tkPost2.message;

            if (!(code !== 0)) {
              _context2.next = 20;
              break;
            }

            msg = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5931\u8D25-----".concat(message, ",params-----").concat(JSON.stringify(params));
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context2.abrupt("return", false);

          case 20:
            _ref4 = data || {}, conflict_cids = _ref4.conflict_cids;

            if (!(!conflict_cids || conflict_cids.length === 0)) {
              _context2.next = 23;
              break;
            }

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

          case 23:
            return _context2.abrupt("return", creatorList.filter(function (item) {
              var _item$baseInfo2;

              return ((_item$baseInfo2 = item.baseInfo) === null || _item$baseInfo2 === void 0 ? void 0 : _item$baseInfo2.creator_oec_id) && !conflict_cids.includes(item.baseInfo.creator_oec_id);
            }));

          case 26:
            _context2.prev = 26;
            _context2.t0 = _context2["catch"](0);
            _msg3 = "\u68C0\u67E5\u8FBE\u4EBA\u51B2\u7A81\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0, task));
            log["a" /* default */].setLog(_msg3);
            task.msg = _msg3;
            return _context2.abrupt("return", false);

          case 32:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 26]]);
  }));

  return function checkConflict(_x3, _x4) {
    return _ref3.apply(this, arguments);
  };
}(); // 分批冲突检查函数（每批最多 50 个达人）


var checkConflictInBatches = /*#__PURE__*/function () {
  var _ref5 = getCreators_asyncToGenerator( /*#__PURE__*/getCreators_regeneratorRuntime().mark(function _callee3(task, creatorList) {
    var batches, i, allValid, _i, batch, validInBatch;

    return getCreators_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            if (creatorList.length) {
              _context3.next = 2;
              break;
            }

            return _context3.abrupt("return", []);

          case 2:
            // 分批：每 CONFLICT_CHECK_BATCH_SIZE 个达人一组
            batches = [];

            for (i = 0; i < creatorList.length; i += CONFLICT_CHECK_BATCH_SIZE) {
              batches.push(creatorList.slice(i, i + CONFLICT_CHECK_BATCH_SIZE));
            }

            log["a" /* default */].setLog("\u51B2\u7A81\u68C0\u67E5-----\u603B\u5171 ".concat(creatorList.length, " \u4E2A\u8FBE\u4EBA\uFF0C\u5206 ").concat(batches.length, " \u6279\u68C0\u67E5")); // 逐批检查

            allValid = [];
            _i = 0;

          case 7:
            if (!(_i < batches.length)) {
              _context3.next = 22;
              break;
            }

            batch = batches[_i];
            log["a" /* default */].setLog("\u51B2\u7A81\u68C0\u67E5-----\u7B2C ".concat(_i + 1, "/").concat(batches.length, " \u6279\uFF0C\u68C0\u67E5 ").concat(batch.length, " \u4E2A\u8FBE\u4EBA"));
            _context3.next = 12;
            return checkConflict(task, batch);

          case 12:
            validInBatch = _context3.sent;

            if (!(validInBatch === false)) {
              _context3.next = 16;
              break;
            }

            log["a" /* default */].setLog("\u51B2\u7A81\u68C0\u67E5-----\u7B2C ".concat(_i + 1, " \u6279\u68C0\u67E5\u5931\u8D25"));
            return _context3.abrupt("return", false);

          case 16:
            allValid.push.apply(allValid, getCreators_toConsumableArray(validInBatch));
            log["a" /* default */].setLog("\u51B2\u7A81\u68C0\u67E5-----\u7B2C ".concat(_i + 1, " \u6279\u8FD4\u56DE ").concat(validInBatch.length, " \u4E2A\u6709\u6548\u8FBE\u4EBA")); // 批次间延迟，避免限流

            if (_i < batches.length - 1) {// await delayed(100)
            }

          case 19:
            _i++;
            _context3.next = 7;
            break;

          case 22:
            log["a" /* default */].setLog("\u51B2\u7A81\u68C0\u67E5-----\u5B8C\u6210\uFF0C\u603B\u5171 ".concat(allValid.length, " \u4E2A\u6709\u6548\u8FBE\u4EBA"));
            return _context3.abrupt("return", allValid);

          case 24:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function checkConflictInBatches(_x5, _x6) {
    return _ref5.apply(this, arguments);
  };
}(); // 入口函数


function getCreators(_x7) {
  return _getCreators.apply(this, arguments);
}

function _getCreators() {
  _getCreators = getCreators_asyncToGenerator( /*#__PURE__*/getCreators_regeneratorRuntime().mark(function _callee4(task) {
    var _ref6, _ref6$curPage, curPage, _ref6$collected, collected, _ref6$search_key, search_key, inviteNum, seen, has_more, pushCreators, _yield$fetchCreatorPa, code, profileList, connectList, nextHasMore, loopGuard, _loop, _ret;

    return getCreators_regeneratorRuntime().wrap(function _callee4$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            if (!task.resCache) task.resCache = {};
            _ref6 = task.resCache.data || {}, _ref6$curPage = _ref6.curPage, curPage = _ref6$curPage === void 0 ? 1 : _ref6$curPage, _ref6$collected = _ref6.collected, collected = _ref6$collected === void 0 ? [] : _ref6$collected, _ref6$search_key = _ref6.search_key, search_key = _ref6$search_key === void 0 ? '' : _ref6$search_key;
            inviteNum = Number(task.invite_num || task.inviteNum) || 0;

            if (!(inviteNum <= 0)) {
              _context5.next = 8;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            task.msg = 'inviteNum参数异常';
            log["a" /* default */].setLog(task.msg);
            return _context5.abrupt("return", {
              code: 2,
              msg: task.msg
            });

          case 8:
            if (!(!task.product_list || task.product_list.length === 0)) {
              _context5.next = 12;
              break;
            }

            task.error_time = src_config["d" /* TEMU_MAX_RETRY_COUNT */];
            task.msg = '未携带商品信息';
            return _context5.abrupt("return", {
              code: 2,
              msg: task.msg
            });

          case 12:
            // 增加10%的备用达人
            inviteNum += Math.ceil(inviteNum * 0.1);
            seen = new Set();
            has_more = true;

            pushCreators = function pushCreators() {
              var profileList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
              var connectList = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
              var inviteNum = arguments.length > 2 ? arguments[2] : undefined;
              // log.setLog(`第${curPage}页达人数据----进入pushCreators函数：${JSON.stringify(profileList)}-----${JSON.stringify(connectList)}`)
              var connectMap = new Map();
              connectList.forEach(function (info) {
                var _info$creator_id;

                var cid = (info === null || info === void 0 ? void 0 : (_info$creator_id = info.creator_id) === null || _info$creator_id === void 0 ? void 0 : _info$creator_id.value) || (info === null || info === void 0 ? void 0 : info.creator_id);
                if (!cid) return;
                connectMap.set(String(cid), info);
              });

              var _iterator = getCreators_createForOfIteratorHelper(profileList),
                  _step;

              try {
                for (_iterator.s(); !(_step = _iterator.n()).done;) {
                  var _item$creator_oecuid, _item$is_creator_bloc, _item$avatar, _item$handle, _item$nickname, _item$selection_regio;

                  var item = _step.value;
                  if (collected.length >= inviteNum) break;
                  var cid = ((_item$creator_oecuid = item.creator_oecuid) === null || _item$creator_oecuid === void 0 ? void 0 : _item$creator_oecuid.value) || item.creator_oecuid;
                  if (!cid || (_item$is_creator_bloc = item.is_creator_blocked_by_shop) !== null && _item$is_creator_bloc !== void 0 && _item$is_creator_bloc.value) return;
                  var key = String(cid);
                  if (seen.has(key)) return;
                  seen.add(key);
                  var connectInfo = connectMap.get(key);
                  var newItem = {
                    baseInfo: {
                      creator_id: null,
                      creator_oec_id: key,
                      image: (_item$avatar = item.avatar) === null || _item$avatar === void 0 ? void 0 : _item$avatar.value,
                      user_name: (_item$handle = item.handle) === null || _item$handle === void 0 ? void 0 : _item$handle.value,
                      nickname: (_item$nickname = item.nickname) === null || _item$nickname === void 0 ? void 0 : _item$nickname.value,
                      selection_region: (_item$selection_regio = item.selection_region) === null || _item$selection_regio === void 0 ? void 0 : _item$selection_regio.value,
                      is_creator_blocked_by_shop: item.is_creator_blocked_by_shop.value,
                      is_in_flat_fee_whitelist: item.is_in_flat_fee_whitelist.value,
                      creator_connect: connectInfo || null
                    },
                    status: 1
                  };
                  collected.push(newItem);
                }
              } catch (err) {
                _iterator.e(err);
              } finally {
                _iterator.f();
              }
            }; // 逐页获取直至收集的数量超过 inviteNum


          case 16:
            if (!(has_more && curPage <= MAX_LOOP && collected.length < inviteNum)) {
              _context5.next = 34;
              break;
            }

            log["a" /* default */].setLog("\u67E5\u8BE2\u53EF\u9080\u7EA6\u8FBE\u4EBA-----\u7B2C".concat(curPage, "\u9875"));
            _context5.next = 20;
            return fetchCreatorPage(task, curPage);

          case 20:
            _yield$fetchCreatorPa = _context5.sent;
            code = _yield$fetchCreatorPa.code;
            profileList = _yield$fetchCreatorPa.profileList;
            connectList = _yield$fetchCreatorPa.connectList;
            nextHasMore = _yield$fetchCreatorPa.has_more;

            if (!(code !== 0)) {
              _context5.next = 28;
              break;
            }

            // 失败缓存，下次直接从该页开始
            task.resCache.data = {
              curPage: curPage,
              collected: collected,
              search_key: search_key
            };
            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 28:
            pushCreators(profileList || [], connectList || []);
            log["a" /* default */].setLog("\u67E5\u8BE2\u53EF\u9080\u7EA6\u8FBE\u4EBA-----\u5F53\u524D\u6536\u96C6\u7684\u8FBE\u4EBA\u6570\uFF1A".concat(collected.length));
            has_more = nextHasMore;
            curPage++; // await delayed(100)

            _context5.next = 16;
            break;

          case 34:
            // 检查冲突（分批检查，每批最多 50 个达人）
            loopGuard = 0;
            _loop = /*#__PURE__*/getCreators_regeneratorRuntime().mark(function _loop() {
              var currentSlice, valid, validSet, invalidSet, nextCandidates, _yield$fetchCreatorPa2, _code, _profileList, _connectList, _nextHasMore;

              return getCreators_regeneratorRuntime().wrap(function _loop$(_context4) {
                while (1) {
                  switch (_context4.prev = _context4.next) {
                    case 0:
                      loopGuard++;
                      currentSlice = collected.slice(0, inviteNum);
                      _context4.next = 4;
                      return checkConflictInBatches(task, currentSlice);

                    case 4:
                      valid = _context4.sent;

                      if (!(valid === false)) {
                        _context4.next = 8;
                        break;
                      }

                      // 失败缓存，下次直接从该页开始
                      task.resCache.data = {
                        curPage: curPage,
                        collected: collected,
                        search_key: search_key
                      };
                      return _context4.abrupt("return", {
                        v: {
                          code: 1,
                          msg: task.msg
                        }
                      });

                    case 8:
                      if (!(valid.length >= inviteNum)) {
                        _context4.next = 10;
                        break;
                      }

                      return _context4.abrupt("return", {
                        v: {
                          code: 0,
                          msg: task.msg || '',
                          data: {
                            curPage: curPage,
                            collected: collected,
                            search_key: search_key
                          },
                          result: {
                            list: valid.slice(0, inviteNum)
                          }
                        }
                      });

                    case 10:
                      validSet = new Set(valid.map(function (i) {
                        return String(i.creator_oec_id);
                      }));
                      invalidSet = new Set(currentSlice.map(function (i) {
                        return i === null || i === void 0 ? void 0 : i.creator_oec_id;
                      }).filter(Boolean).map(String).filter(function (id) {
                        return !validSet.has(id);
                      }));
                      nextCandidates = collected.filter(function (_ref7) {
                        var cid = _ref7.creator_oec_id;
                        var key = String(cid || '');
                        return cid && !validSet.has(key) && !invalidSet.has(key);
                      });
                      collected.length = 0;
                      valid.forEach(function (i) {
                        return collected.push(i);
                      });
                      nextCandidates.forEach(function (i) {
                        return collected.push(i);
                      }); // 获取下一页达人列表，直至收集的数量超过 inviteNum 或 没有下一页 或 超过最大循环限制

                    case 16:
                      if (!(has_more && curPage <= MAX_LOOP && collected.length < inviteNum)) {
                        _context4.next = 32;
                        break;
                      }

                      _context4.next = 19;
                      return fetchCreatorPage(task, curPage);

                    case 19:
                      _yield$fetchCreatorPa2 = _context4.sent;
                      _code = _yield$fetchCreatorPa2.code;
                      _profileList = _yield$fetchCreatorPa2.profileList;
                      _connectList = _yield$fetchCreatorPa2.connectList;
                      _nextHasMore = _yield$fetchCreatorPa2.has_more;

                      if (!(_code !== 0)) {
                        _context4.next = 27;
                        break;
                      }

                      // 失败缓存，下次直接从该页开始
                      task.resCache.data = {
                        curPage: curPage,
                        collected: collected,
                        search_key: search_key
                      };
                      return _context4.abrupt("return", {
                        v: {
                          code: 1,
                          msg: task.msg
                        }
                      });

                    case 27:
                      pushCreators(_profileList || [], _connectList || [], inviteNum);
                      has_more = _nextHasMore;
                      curPage++; // await delayed(100)

                      _context4.next = 16;
                      break;

                    case 32:
                      if (!(!has_more && collected.length < inviteNum)) {
                        _context4.next = 34;
                        break;
                      }

                      return _context4.abrupt("return", {
                        v: {
                          code: 0,
                          msg: task.msg || '达人数量不足，已返回可用列表',
                          data: {
                            curPage: curPage,
                            collected: collected,
                            search_key: search_key
                          },
                          result: {
                            list: collected
                          }
                        }
                      });

                    case 34:
                    case "end":
                      return _context4.stop();
                  }
                }
              }, _loop);
            });

          case 36:
            if (!(loopGuard < MAX_LOOP)) {
              _context5.next = 43;
              break;
            }

            return _context5.delegateYield(_loop(), "t0", 38);

          case 38:
            _ret = _context5.t0;

            if (!(getCreators_typeof(_ret) === "object")) {
              _context5.next = 41;
              break;
            }

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

          case 41:
            _context5.next = 36;
            break;

          case 43:
            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg || '获取达人失败，超过最大循环次数'
            });

          case 44:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee4);
  }));
  return _getCreators.apply(this, arguments);
}
// EXTERNAL MODULE: ./src/platform/mercado/index.js
var mercado = __webpack_require__("e38f");

// CONCATENATED MODULE: ./src/platform/mercado/constants/pagoReportParams.js
// 跨境
// export const cbPagoSettingsParams = {
//   source: 'local',
//   settings: null,
//   previousSettings: {
//     columns: {
//       groups: [
//         {
//           mainOption: {
//             id: 'date_all',
//             title: 'Dates',
//             subOptions: [
//               { id: 'DATE', title: 'Release date' },
//               { id: 'TRANSACTION_APPROVAL_DATE', title: 'Transaction approval date' }
//             ]
//           }
//         },
//         {
//           mainOption: {
//             id: 'operation_all',
//             title: 'Operation data',
//             subOptions: [
//               { id: 'SOURCE_ID', title: 'Source ID' },
//               { id: 'EXTERNAL_REFERENCE', title: 'SKU' },
//               { id: 'RECORD_TYPE', title: 'Register type' },
//               { id: 'DESCRIPTION', title: 'Description' },
//               { id: 'CURRENCY', title: 'Currency' },
//               { id: 'NET_CREDIT_AMOUNT', title: 'Net credit amount' },
//               { id: 'NET_DEBIT_AMOUNT', title: 'Net debit amount' },
//               { id: 'GROSS_AMOUNT', title: 'Gross amount' },
//               { id: 'MP_FEE_AMOUNT', title: 'MP fee amount' },
//               { id: 'FINANCING_FEE_AMOUNT', title: 'Financing fee amount' },
//               { id: 'SHIPPING_FEE_AMOUNT', title: 'Shipping fee' },
//               { id: 'TAXES_AMOUNT', title: 'Taxes amount' },
//               { id: 'COUPON_AMOUNT', title: 'Coupon amount' },
//               { id: 'INSTALLMENTS', title: 'Installments' },
//               { id: 'PAYMENT_METHOD', title: 'Payment method' },
//               { id: 'TAX_DETAIL', title: 'Tax detail' },
//               { id: 'TAX_AMOUNT_TELCO', title: 'Tax amount telco' },
//               { id: 'TAXES_DISAGGREGATED', title: 'Taxes disaggregated' },
//               { id: 'EFFECTIVE_COUPON_AMOUNT', title: 'Effective coupon amount' },
//               { id: 'METADATA', title: 'Additional details' },
//               { id: 'SELLER_AMOUNT', title: 'Amount received for split payment purchases' },
//               { id: 'CARD_INITIAL_NUMBER', title: 'Your buyer’s card' },
//               { id: 'OPERATION_TAGS', title: 'Transaction labels' },
//               { id: 'ITEM_ID', title: 'Product identifier' },
//               { id: 'BUSINESS_UNIT', title: 'Sales channel' },
//               { id: 'SUB_UNIT', title: 'Payment platform' },
//               { id: 'BALANCE_AMOUNT', title: 'Balance' },
//               { id: 'PAYOUT_BANK_ACCOUNT_NUMBER', title: 'Payout bank account number' },
//               { id: 'PRODUCT_SKU', title: 'Product SKU' },
//               { id: 'SALE_DETAIL', title: 'Order details' },
//               { id: 'TRANSACTION_INTENT_ID', title: 'Transaction intent ID' },
//               { id: 'FRANCHISE', title: 'Franchise' },
//               { id: 'LAST_FOUR_DIGITS', title: 'Last 4 digits' },
//               { id: 'ORDER_MP', title: 'Request ID', isNewOption: true },
//               { id: 'PAYMENT_METHOD_TYPE', title: 'Type of payment', isNewOption: true },
//               { id: 'AVK_ID', title: 'Interbank CLABE number', isNewOption: true },
//               { id: 'PURCHASE_ID', title: 'Purchase ID', isNewOption: true },
//               { id: 'ISSUER_NAME', title: 'Issuer name', isNewOption: true }
//             ]
//           }
//         },
//         {
//           mainOption: {
//             id: 'store_all',
//             title: 'Cash register and Stores details',
//             subOptions: [
//               { id: 'POS_ID', title: 'POS ID' },
//               { id: 'POS_NAME', title: 'Cash register name' },
//               { id: 'EXTERNAL_POS_ID', title: 'Cash register ID set by the user' },
//               { id: 'STORE_ID', title: 'Store ID' },
//               { id: 'STORE_NAME', title: 'Store name' },
//               { id: 'EXTERNAL_STORE_ID', title: 'External store ID' },
//               { id: 'POI_ID', title: 'POI ID' }
//             ]
//           }
//         },
//         {
//           mainOption: {
//             id: 'shipping_all',
//             title: 'Shipment data',
//             subOptions: [
//               { id: 'SHIPPING_ID', title: 'Shipping ID' },
//               { id: 'SHIPMENT_MODE', title: 'Shipping mode' },
//               { id: 'ORDER_ID', title: 'Order ID' },
//               { id: 'PACK_ID', title: 'Pack ID' },
//               { id: 'SHIPPING_ORDER_ID', title: 'Shipment linking ID', isNewOption: true }
//             ]
//           }
//         },
//         {
//           mainOption: {
//             id: 'qr_interop',
//             title: 'Details from other digital wallets and banks',
//             subOptions: [
//               { id: 'POI_WALLET_NAME', title: 'Digital wallet' },
//               { id: 'POI_BANK_NAME', title: 'Bank of origin' }
//             ],
//             tooltipInfo: {
//               linkURL: '',
//               linkText: 'Alerta: Wording no definido',
//               description: 'By selecting these fields you can view in your report which digital wallet or bank your clients use to pay purchases made with a QR code.'
//             }
//           }
//         }
//       ],
//       selected: ['DATE', 'ORDER_ID', 'SHIPPING_ID', 'SOURCE_ID', 'EXTERNAL_REFERENCE', 'RECORD_TYPE', 'DESCRIPTION', 'NET_CREDIT_AMOUNT', 'NET_DEBIT_AMOUNT', 'GROSS_AMOUNT', 'MP_FEE_AMOUNT', 'SHIPPING_FEE_AMOUNT', 'CURRENCY', 'ITEM_ID', 'PACK_ID']
//     },
//     separators: ';',
//     // fileName: 'release-2542362139',
//     fileName: '',
//     displayTimezone: 'GMT-04',
//     displayLanguage: 'en',
//     reportLanguage: 'en',
//     headerLanguage: 'en',
//     isLegacyTranslation: false,
//     countryUserLanguage: 'en',
//     selectedReportLanguage: 'en',
//     advancedSettings: {
//       groups: [
//         {
//           mainOption: {
//             id: 'additional_rows',
//             subOptions: [
//               {
//                 showOption: true,
//                 id: 'check_available_balance',
//                 title: 'Available balance before and after a cash withdrawal',
//                 description: 'Adds two new rows to the report with the available balance before and after a withdrawal.',
//                 shouldValidateNLedger: false,
//                 showKeyName: true,
//                 isNewOption: false
//               },
//               {
//                 showOption: true,
//                 id: 'unite_reserve',
//                 title: 'Hide compensated reserve transactions',
//                 description: 'Marking this option will hide the transactions that show when your money was reserved and released within the period of the requested report.',
//                 shouldValidateNLedger: false,
//                 showKeyName: true,
//                 isNewOption: true
//               },
//               {
//                 showOption: true,
//                 id: 'visible_zero_releases',
//                 title: 'Show releases at zero',
//                 description: 'By selecting this option, the transactions with a zero balance will be displayed, corresponding to cancelled orders or payments.',
//                 shouldValidateNLedger: false,
//                 showKeyName: true,
//                 isNewOption: true
//               }
//             ]
//           }
//         }
//       ],
//       selected: []
//     },
//     ftp: null,
//     webhook: null
//   },
//   sellerId: '',
//   tonicUsername: ''
// }
// 跨境
var cbPagoSettingsParams = {
  source: 'local',
  settings: {
    columns: ['DATE', 'TRANSACTION_APPROVAL_DATE', 'SOURCE_ID', 'EXTERNAL_REFERENCE', 'RECORD_TYPE', 'DESCRIPTION', 'CURRENCY', 'NET_CREDIT_AMOUNT', 'NET_DEBIT_AMOUNT', 'GROSS_AMOUNT', 'MP_FEE_AMOUNT', 'FINANCING_FEE_AMOUNT', 'SHIPPING_FEE_AMOUNT', 'TAXES_AMOUNT', 'COUPON_AMOUNT', 'INSTALLMENTS', 'PAYMENT_METHOD', 'TAX_DETAIL', 'TAX_AMOUNT_TELCO', 'TAXES_DISAGGREGATED', 'EFFECTIVE_COUPON_AMOUNT', 'METADATA', 'SELLER_AMOUNT', 'CARD_INITIAL_NUMBER', 'OPERATION_TAGS', 'ITEM_ID', 'BUSINESS_UNIT', 'SUB_UNIT', 'BALANCE_AMOUNT', 'PAYOUT_BANK_ACCOUNT_NUMBER', 'PRODUCT_SKU', 'SALE_DETAIL', 'TRANSACTION_INTENT_ID', 'FRANCHISE', 'LAST_FOUR_DIGITS', 'ORDER_MP', 'PAYMENT_METHOD_TYPE', 'PURCHASE_ID', 'ISSUER_NAME', 'EXTERNAL_POS_ID', 'STORE_ID', 'STORE_NAME', 'EXTERNAL_STORE_ID', 'POI_ID', 'SHIPPING_ID', 'SHIPMENT_MODE', 'ORDER_ID', 'PACK_ID', 'SHIPPING_ORDER_ID', 'POI_WALLET_NAME', 'POI_BANK_NAME'],
    groups: ['check_available_balance', 'unite_reserve', 'visible_zero_releases'],
    fileConfig: {},
    is_legacy_translation: false,
    country_user_language: 'en',
    selected_report_language: 'en'
  },
  previousSettings: {
    columns: {
      groups: [{
        mainOption: {
          id: 'date_all',
          title: 'Dates',
          subOptions: [{
            id: 'DATE',
            title: 'Release date'
          }, {
            id: 'TRANSACTION_APPROVAL_DATE',
            title: 'Transaction approval date'
          }]
        }
      }, {
        mainOption: {
          id: 'operation_all',
          title: 'Operation data',
          subOptions: [{
            id: 'SOURCE_ID',
            title: 'Source ID'
          }, {
            id: 'EXTERNAL_REFERENCE',
            title: 'SKU'
          }, {
            id: 'RECORD_TYPE',
            title: 'Register type'
          }, {
            id: 'DESCRIPTION',
            title: 'Description'
          }, {
            id: 'CURRENCY',
            title: 'Currency'
          }, {
            id: 'NET_CREDIT_AMOUNT',
            title: 'Net credit amount'
          }, {
            id: 'NET_DEBIT_AMOUNT',
            title: 'Net debit amount'
          }, {
            id: 'GROSS_AMOUNT',
            title: 'Gross amount'
          }, {
            id: 'MP_FEE_AMOUNT',
            title: 'MP fee amount'
          }, {
            id: 'FINANCING_FEE_AMOUNT',
            title: 'Financing fee amount'
          }, {
            id: 'SHIPPING_FEE_AMOUNT',
            title: 'Shipping fee'
          }, {
            id: 'TAXES_AMOUNT',
            title: 'Taxes amount'
          }, {
            id: 'COUPON_AMOUNT',
            title: 'Coupon amount'
          }, {
            id: 'INSTALLMENTS',
            title: 'Installments'
          }, {
            id: 'PAYMENT_METHOD',
            title: 'Payment method'
          }, {
            id: 'TAX_DETAIL',
            title: 'Tax detail'
          }, {
            id: 'TAX_AMOUNT_TELCO',
            title: 'Tax amount telco'
          }, {
            id: 'TAXES_DISAGGREGATED',
            title: 'Taxes disaggregated'
          }, {
            id: 'EFFECTIVE_COUPON_AMOUNT',
            title: 'Effective coupon amount'
          }, {
            id: 'METADATA',
            title: 'Additional details'
          }, {
            id: 'SELLER_AMOUNT',
            title: 'Amount received for split payment purchases'
          }, {
            id: 'CARD_INITIAL_NUMBER',
            title: 'Your buyer’s card'
          }, {
            id: 'OPERATION_TAGS',
            title: 'Transaction labels'
          }, {
            id: 'ITEM_ID',
            title: 'Product identifier'
          }, {
            id: 'BUSINESS_UNIT',
            title: 'Sales channel'
          }, {
            id: 'SUB_UNIT',
            title: 'Payment platform'
          }, {
            id: 'BALANCE_AMOUNT',
            title: 'Balance'
          }, {
            id: 'PAYOUT_BANK_ACCOUNT_NUMBER',
            title: 'Payout bank account number'
          }, {
            id: 'PRODUCT_SKU',
            title: 'Product SKU'
          }, {
            id: 'SALE_DETAIL',
            title: 'Order details'
          }, {
            id: 'TRANSACTION_INTENT_ID',
            title: 'Transaction intent ID'
          }, {
            id: 'FRANCHISE',
            title: 'Franchise'
          }, {
            id: 'LAST_FOUR_DIGITS',
            title: 'Last 4 digits'
          }, {
            id: 'ORDER_MP',
            title: 'Request ID',
            isNewOption: true
          }, {
            id: 'PAYMENT_METHOD_TYPE',
            title: 'Type of payment',
            isNewOption: true
          }, {
            id: 'AVK_ID',
            title: 'Interbank CLABE number',
            isNewOption: true
          }, {
            id: 'PURCHASE_ID',
            title: 'Purchase ID',
            isNewOption: true
          }, {
            id: 'ISSUER_NAME',
            title: 'Issuer name',
            isNewOption: true
          }]
        }
      }, {
        mainOption: {
          id: 'store_all',
          title: 'Cash register and Stores details',
          subOptions: [{
            id: 'EXTERNAL_POS_ID',
            title: 'Cash register ID set by the user'
          }, {
            id: 'STORE_ID',
            title: 'Store ID'
          }, {
            id: 'STORE_NAME',
            title: 'Store name'
          }, {
            id: 'EXTERNAL_STORE_ID',
            title: 'External store ID'
          }, {
            id: 'POI_ID',
            title: 'POI ID'
          }]
        }
      }, {
        mainOption: {
          id: 'shipping_all',
          title: 'Shipment data',
          subOptions: [{
            id: 'SHIPPING_ID',
            title: 'Shipping ID'
          }, {
            id: 'SHIPMENT_MODE',
            title: 'Shipping mode'
          }, {
            id: 'ORDER_ID',
            title: 'Order ID'
          }, {
            id: 'PACK_ID',
            title: 'Pack ID'
          }, {
            id: 'SHIPPING_ORDER_ID',
            title: 'Shipment linking ID',
            isNewOption: true
          }]
        }
      }, {
        mainOption: {
          id: 'qr_interop',
          title: 'Details from other digital wallets and banks',
          subOptions: [{
            id: 'POI_WALLET_NAME',
            title: 'Digital wallet'
          }, {
            id: 'POI_BANK_NAME',
            title: 'Bank of origin'
          }],
          tooltipInfo: {
            linkURL: '',
            linkText: 'Alerta: Wording no definido',
            description: 'By selecting these fields you can view in your report which digital wallet or bank your clients use to pay purchases made with a QR code.'
          }
        }
      }],
      selected: ['DATE', 'TRANSACTION_APPROVAL_DATE', 'SOURCE_ID', 'EXTERNAL_REFERENCE', 'RECORD_TYPE', 'DESCRIPTION', 'CURRENCY', 'NET_CREDIT_AMOUNT', 'NET_DEBIT_AMOUNT', 'GROSS_AMOUNT', 'MP_FEE_AMOUNT', 'FINANCING_FEE_AMOUNT', 'SHIPPING_FEE_AMOUNT', 'TAXES_AMOUNT', 'COUPON_AMOUNT', 'INSTALLMENTS', 'PAYMENT_METHOD', 'TAX_DETAIL', 'TAX_AMOUNT_TELCO', 'TAXES_DISAGGREGATED', 'EFFECTIVE_COUPON_AMOUNT', 'METADATA', 'SELLER_AMOUNT', 'CARD_INITIAL_NUMBER', 'OPERATION_TAGS', 'ITEM_ID', 'BUSINESS_UNIT', 'SUB_UNIT', 'BALANCE_AMOUNT', 'PAYOUT_BANK_ACCOUNT_NUMBER', 'PRODUCT_SKU', 'SALE_DETAIL', 'TRANSACTION_INTENT_ID', 'FRANCHISE', 'LAST_FOUR_DIGITS', 'ORDER_MP', 'PAYMENT_METHOD_TYPE', 'PURCHASE_ID', 'EXTERNAL_POS_ID', 'STORE_ID', 'STORE_NAME', 'EXTERNAL_STORE_ID', 'POI_ID', 'SHIPPING_ID', 'SHIPMENT_MODE', 'ORDER_ID', 'PACK_ID', 'SHIPPING_ORDER_ID', 'POI_WALLET_NAME', 'POI_BANK_NAME']
    },
    separators: ';',
    // fileName: 'release-2715149713',
    fileName: '',
    displayTimezone: 'GMT-04',
    displayLanguage: 'en',
    reportLanguage: 'en',
    headerLanguage: 'en',
    isLegacyTranslation: false,
    countryUserLanguage: 'en',
    selectedReportLanguage: 'en',
    advancedSettings: {
      groups: [{
        mainOption: {
          id: 'additional_rows',
          subOptions: [{
            showOption: true,
            id: 'check_available_balance',
            title: 'Available balance before and after a cash withdrawal',
            description: 'Adds two new rows to the report with the available balance before and after a withdrawal.',
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: false
          }, {
            showOption: true,
            id: 'unite_reserve',
            title: 'Hide compensated reserve transactions',
            description: 'Marking this option will hide the transactions that show when your money was reserved and released within the period of the requested report.',
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: true
          }, {
            showOption: true,
            id: 'visible_zero_releases',
            title: 'Show releases at zero',
            description: 'By selecting this option, the transactions with a zero balance will be displayed, corresponding to cancelled orders or payments.',
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: true
          }]
        }
      }],
      selected: []
    },
    ftp: null,
    webhook: null
  },
  sellerId: '',
  tonicUsername: ''
}; // 跨境-哥伦比亚

var cbPagoSettingsParamsColombia = {
  source: 'local',
  settings: {
    editableColumns: [{
      id: 'DATE',
      order: 1,
      alias: ''
    }, {
      id: 'TRANSACTION_APPROVAL_DATE',
      order: 2,
      alias: ''
    }, {
      id: 'SOURCE_ID',
      order: 3,
      alias: ''
    }, {
      id: 'EXTERNAL_REFERENCE',
      order: 4,
      alias: ''
    }, {
      id: 'RECORD_TYPE',
      order: 5,
      alias: ''
    }, {
      id: 'DESCRIPTION',
      order: 6,
      alias: ''
    }, {
      id: 'CURRENCY',
      order: 7,
      alias: ''
    }, {
      id: 'NET_CREDIT_AMOUNT',
      order: 8,
      alias: ''
    }, {
      id: 'NET_DEBIT_AMOUNT',
      order: 9,
      alias: ''
    }, {
      id: 'GROSS_AMOUNT',
      order: 10,
      alias: ''
    }, {
      id: 'MP_FEE_AMOUNT',
      order: 11,
      alias: ''
    }, {
      id: 'FINANCING_FEE_AMOUNT',
      order: 12,
      alias: ''
    }, {
      id: 'SHIPPING_FEE_AMOUNT',
      order: 13,
      alias: ''
    }, {
      id: 'TAXES_AMOUNT',
      order: 14,
      alias: ''
    }, {
      id: 'COUPON_AMOUNT',
      order: 15,
      alias: ''
    }, {
      id: 'INSTALLMENTS',
      order: 16,
      alias: ''
    }, {
      id: 'PAYMENT_METHOD',
      order: 17,
      alias: ''
    }, {
      id: 'TAX_DETAIL',
      order: 18,
      alias: ''
    }, {
      id: 'TAX_AMOUNT_TELCO',
      order: 19,
      alias: ''
    }, {
      id: 'TAXES_DISAGGREGATED',
      order: 20,
      alias: ''
    }, {
      id: 'EFFECTIVE_COUPON_AMOUNT',
      order: 21,
      alias: ''
    }, {
      id: 'METADATA',
      order: 22,
      alias: ''
    }, {
      id: 'SELLER_AMOUNT',
      order: 23,
      alias: ''
    }, {
      id: 'CARD_INITIAL_NUMBER',
      order: 24,
      alias: ''
    }, {
      id: 'OPERATION_TAGS',
      order: 25,
      alias: ''
    }, {
      id: 'ITEM_ID',
      order: 26,
      alias: ''
    }, {
      id: 'BUSINESS_UNIT',
      order: 27,
      alias: ''
    }, {
      id: 'SUB_UNIT',
      order: 28,
      alias: ''
    }, {
      id: 'BALANCE_AMOUNT',
      order: 29,
      alias: ''
    }, {
      id: 'PAYOUT_BANK_ACCOUNT_NUMBER',
      order: 30,
      alias: ''
    }, {
      id: 'PRODUCT_SKU',
      order: 31,
      alias: ''
    }, {
      id: 'SALE_DETAIL',
      order: 32,
      alias: ''
    }, {
      id: 'TRANSACTION_INTENT_ID',
      order: 33,
      alias: ''
    }, {
      id: 'FRANCHISE',
      order: 34,
      alias: ''
    }, {
      id: 'LAST_FOUR_DIGITS',
      order: 35,
      alias: ''
    }, {
      id: 'ORDER_MP',
      order: 36,
      alias: ''
    }, {
      id: 'PAYMENT_METHOD_TYPE',
      order: 37,
      alias: ''
    }, {
      id: 'POS_ID',
      order: 38,
      alias: ''
    }, {
      id: 'POS_NAME',
      order: 39,
      alias: ''
    }, {
      id: 'EXTERNAL_POS_ID',
      order: 40,
      alias: ''
    }, {
      id: 'STORE_ID',
      order: 41,
      alias: ''
    }, {
      id: 'STORE_NAME',
      order: 42,
      alias: ''
    }, {
      id: 'EXTERNAL_STORE_ID',
      order: 43,
      alias: ''
    }, {
      id: 'POI_ID',
      order: 44,
      alias: ''
    }, {
      id: 'SHIPPING_ID',
      order: 45,
      alias: ''
    }, {
      id: 'SHIPMENT_MODE',
      order: 46,
      alias: ''
    }, {
      id: 'ORDER_ID',
      order: 47,
      alias: ''
    }, {
      id: 'PACK_ID',
      order: 48,
      alias: ''
    }, {
      id: 'POI_WALLET_NAME',
      order: 49,
      alias: ''
    }, {
      id: 'POI_BANK_NAME',
      order: 50,
      alias: ''
    }, {
      id: 'PURCHASE_ID',
      order: 51,
      alias: ''
    }, {
      id: 'SHIPPING_ORDER_ID',
      order: 52,
      alias: ''
    }, {
      id: 'ISSUER_NAME',
      order: 53,
      alias: ''
    }],
    groups: ['check_available_balance', 'compensate_detail', 'unite_reserve', 'visible_zero_releases'],
    fileConfig: {},
    is_legacy_translation: true,
    country_user_language: 'en',
    selected_report_language: 'en',
    selected_header_language: 'en'
  },
  previousSettings: {
    columns: {
      sections: [{
        id: 'DATE',
        title: 'Release date',
        key: 'DATE',
        alias: '',
        checked: true,
        order: 1
      }, {
        id: 'TRANSACTION_APPROVAL_DATE',
        title: 'Transaction approval date',
        key: 'TRANSACTION_APPROVAL_DATE',
        alias: '',
        checked: true,
        order: 2
      }, {
        id: 'SOURCE_ID',
        title: 'Source ID',
        key: 'SOURCE_ID',
        alias: '',
        checked: true,
        order: 3
      }, {
        id: 'EXTERNAL_REFERENCE',
        title: 'SKU',
        key: 'EXTERNAL_REFERENCE',
        alias: '',
        checked: true,
        order: 4
      }, {
        id: 'RECORD_TYPE',
        title: 'Register type',
        key: 'RECORD_TYPE',
        alias: '',
        checked: true,
        order: 5
      }, {
        id: 'DESCRIPTION',
        title: 'Description',
        key: 'DESCRIPTION',
        alias: '',
        checked: true,
        order: 6
      }, {
        id: 'CURRENCY',
        title: 'Currency',
        key: 'CURRENCY',
        alias: '',
        checked: true,
        order: 7
      }, {
        id: 'NET_CREDIT_AMOUNT',
        title: 'Net credit amount',
        key: 'NET_CREDIT_AMOUNT',
        alias: '',
        checked: true,
        order: 8
      }, {
        id: 'NET_DEBIT_AMOUNT',
        title: 'Net debit amount',
        key: 'NET_DEBIT_AMOUNT',
        alias: '',
        checked: true,
        order: 9
      }, {
        id: 'GROSS_AMOUNT',
        title: 'Gross amount',
        key: 'GROSS_AMOUNT',
        alias: '',
        checked: true,
        order: 10
      }, {
        id: 'MP_FEE_AMOUNT',
        title: 'MP fee amount',
        key: 'MP_FEE_AMOUNT',
        alias: '',
        checked: true,
        order: 11
      }, {
        id: 'FINANCING_FEE_AMOUNT',
        title: 'Financing fee amount',
        key: 'FINANCING_FEE_AMOUNT',
        alias: '',
        checked: true,
        order: 12
      }, {
        id: 'SHIPPING_FEE_AMOUNT',
        title: 'Shipping fee',
        key: 'SHIPPING_FEE_AMOUNT',
        alias: '',
        checked: true,
        order: 13
      }, {
        id: 'TAXES_AMOUNT',
        title: 'Taxes on IIBB withholdings',
        key: 'TAXES_AMOUNT',
        alias: '',
        checked: true,
        order: 14
      }, {
        id: 'COUPON_AMOUNT',
        title: 'Coupon amount',
        key: 'COUPON_AMOUNT',
        alias: '',
        checked: true,
        order: 15
      }, {
        id: 'INSTALLMENTS',
        title: 'Installments',
        key: 'INSTALLMENTS',
        alias: '',
        checked: true,
        order: 16
      }, {
        id: 'PAYMENT_METHOD',
        title: 'Payment method',
        key: 'PAYMENT_METHOD',
        alias: '',
        checked: true,
        order: 17
      }, {
        id: 'TAX_DETAIL',
        title: 'Tax detail',
        key: 'TAX_DETAIL',
        alias: '',
        checked: true,
        order: 18
      }, {
        id: 'TAX_AMOUNT_TELCO',
        title: 'Tax amount telco',
        key: 'TAX_AMOUNT_TELCO',
        alias: '',
        checked: true,
        order: 19
      }, {
        id: 'TAXES_DISAGGREGATED',
        title: 'Taxes disaggregated',
        key: 'TAXES_DISAGGREGATED',
        alias: '',
        checked: true,
        order: 20
      }, {
        id: 'EFFECTIVE_COUPON_AMOUNT',
        title: 'Effective coupon amount',
        key: 'EFFECTIVE_COUPON_AMOUNT',
        alias: '',
        checked: true,
        order: 21
      }, {
        id: 'METADATA',
        title: 'Additional details',
        key: 'METADATA',
        alias: '',
        checked: true,
        order: 22
      }, {
        id: 'SELLER_AMOUNT',
        title: 'Amount received for split payment purchases',
        key: 'SELLER_AMOUNT',
        alias: '',
        checked: true,
        order: 23
      }, {
        id: 'CARD_INITIAL_NUMBER',
        title: 'Your buyer’s card',
        key: 'CARD_INITIAL_NUMBER',
        alias: '',
        checked: true,
        order: 24
      }, {
        id: 'OPERATION_TAGS',
        title: 'Transaction labels',
        key: 'OPERATION_TAGS',
        alias: '',
        checked: true,
        order: 25
      }, {
        id: 'ITEM_ID',
        title: 'Product identifier',
        key: 'ITEM_ID',
        alias: '',
        checked: true,
        order: 26
      }, {
        id: 'BUSINESS_UNIT',
        title: 'Sales channel',
        key: 'BUSINESS_UNIT',
        alias: '',
        checked: true,
        order: 27
      }, {
        id: 'SUB_UNIT',
        title: 'Payment platform',
        key: 'SUB_UNIT',
        alias: '',
        checked: true,
        order: 28
      }, {
        id: 'BALANCE_AMOUNT',
        title: 'Balance',
        key: 'BALANCE_AMOUNT',
        alias: '',
        checked: true,
        order: 29
      }, {
        id: 'PAYOUT_BANK_ACCOUNT_NUMBER',
        title: 'Payout bank account number',
        key: 'PAYOUT_BANK_ACCOUNT_NUMBER',
        alias: '',
        checked: true,
        order: 30
      }, {
        id: 'PRODUCT_SKU',
        title: 'Product SKU',
        key: 'PRODUCT_SKU',
        alias: '',
        checked: true,
        order: 31
      }, {
        id: 'SALE_DETAIL',
        title: 'Order details',
        key: 'SALE_DETAIL',
        alias: '',
        checked: true,
        order: 32
      }, {
        id: 'TRANSACTION_INTENT_ID',
        title: 'Transaction intent ID',
        key: 'TRANSACTION_INTENT_ID',
        alias: '',
        checked: true,
        order: 33
      }, {
        id: 'FRANCHISE',
        title: 'Franchise',
        key: 'FRANCHISE',
        alias: '',
        checked: true,
        order: 34
      }, {
        id: 'LAST_FOUR_DIGITS',
        title: 'Last 4 digits',
        key: 'LAST_FOUR_DIGITS',
        alias: '',
        checked: true,
        order: 35
      }, {
        id: 'ORDER_MP',
        title: 'Request ID',
        key: 'ORDER_MP',
        alias: '',
        checked: true,
        order: 36
      }, {
        id: 'PAYMENT_METHOD_TYPE',
        title: 'Type of payment',
        key: 'PAYMENT_METHOD_TYPE',
        alias: '',
        checked: true,
        order: 37
      }, {
        id: 'POS_ID',
        title: 'POS ID',
        key: 'POS_ID',
        alias: '',
        checked: true,
        order: 38
      }, {
        id: 'POS_NAME',
        title: 'Cash register name',
        key: 'POS_NAME',
        alias: '',
        checked: true,
        order: 39
      }, {
        id: 'EXTERNAL_POS_ID',
        title: 'Cash register ID set by the user',
        key: 'EXTERNAL_POS_ID',
        alias: '',
        checked: true,
        order: 40
      }, {
        id: 'STORE_ID',
        title: 'Store ID',
        key: 'STORE_ID',
        alias: '',
        checked: true,
        order: 41
      }, {
        id: 'STORE_NAME',
        title: 'Store name',
        key: 'STORE_NAME',
        alias: '',
        checked: true,
        order: 42
      }, {
        id: 'EXTERNAL_STORE_ID',
        title: 'External store ID',
        key: 'EXTERNAL_STORE_ID',
        alias: '',
        checked: true,
        order: 43
      }, {
        id: 'POI_ID',
        title: 'POI ID',
        key: 'POI_ID',
        alias: '',
        checked: true,
        order: 44
      }, {
        id: 'SHIPPING_ID',
        title: 'Shipping ID',
        key: 'SHIPPING_ID',
        alias: '',
        checked: true,
        order: 45
      }, {
        id: 'SHIPMENT_MODE',
        title: 'Shipping mode',
        key: 'SHIPMENT_MODE',
        alias: '',
        checked: true,
        order: 46
      }, {
        id: 'ORDER_ID',
        title: 'Order ID',
        key: 'ORDER_ID',
        alias: '',
        checked: true,
        order: 47
      }, {
        id: 'PACK_ID',
        title: 'Pack ID',
        key: 'PACK_ID',
        alias: '',
        checked: true,
        order: 48
      }, {
        id: 'POI_WALLET_NAME',
        title: 'Digital wallet',
        key: 'POI_WALLET_NAME',
        alias: '',
        checked: true,
        order: 49
      }, {
        id: 'POI_BANK_NAME',
        title: 'Bank of origin',
        key: 'POI_BANK_NAME',
        alias: '',
        checked: true,
        order: 50
      }, {
        id: 'PURCHASE_ID',
        title: 'Purchase ID',
        key: 'PURCHASE_ID',
        alias: '',
        checked: true,
        order: 51
      }, {
        id: 'SHIPPING_ORDER_ID',
        title: 'Shipment linking ID',
        key: 'SHIPPING_ORDER_ID',
        alias: '',
        checked: true,
        order: 52
      }, {
        id: 'ISSUER_NAME',
        title: 'Issuer name',
        key: 'ISSUER_NAME',
        alias: '',
        checked: true,
        order: 53
      }]
    },
    separators: ';',
    // fileName: 'release-2507950668',
    displayTimezone: 'GMT-04',
    displayLanguage: 'en',
    reportLanguage: 'en',
    headerLanguage: 'en',
    isLegacyTranslation: true,
    countryUserLanguage: 'en',
    selectedReportLanguage: 'en',
    selectedHeaderLanguage: 'en',
    advancedSettings: {
      groups: [{
        mainOption: {
          id: 'additional_rows',
          subOptions: [{
            showOption: true,
            id: 'check_available_balance',
            title: 'Available balance before and after a cash withdrawal',
            description: 'Adds two new rows to the report with the available balance before and after a withdrawal.',
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: false
          }, {
            showOption: true,
            id: 'compensate_detail',
            title: 'Compensated transactions',
            description: 'Includes blocking and unblocking transactions that offset each other (Credit - Debit = 0) in a range of dates.',
            shouldValidateNLedger: true,
            showKeyName: true,
            isNewOption: false
          }, {
            showOption: true,
            id: 'unite_reserve',
            title: 'Hide compensated reserve transactions',
            description: 'Marking this option will hide the transactions that show when your money was reserved and released within the period of the requested report.',
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: true
          }, {
            showOption: true,
            id: 'visible_zero_releases',
            title: 'Show releases at zero',
            description: 'By selecting this option, the transactions with a zero balance will be displayed, corresponding to cancelled orders or payments.',
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: true
          }]
        }
      }],
      selected: []
    },
    ftp: {
      server: '',
      port: '',
      path: '',
      user: '',
      pass: ''
    },
    webhook: {
      url: '',
      password: ''
    }
  },
  sellerId: '',
  userId: '',
  tonicUsername: ''
}; // 本土

var LocalPagoSettingsParams = {
  source: "local",
  settings: {
    editableColumns: [{
      id: "DATE",
      order: 1,
      alias: ""
    }, {
      id: "TRANSACTION_APPROVAL_DATE",
      order: 2,
      alias: ""
    }, {
      id: "SOURCE_ID",
      order: 3,
      alias: ""
    }, {
      id: "DESCRIPTION",
      order: 4,
      alias: ""
    }, {
      id: "NET_CREDIT_AMOUNT",
      order: 5,
      alias: ""
    }, {
      id: "NET_DEBIT_AMOUNT",
      order: 6,
      alias: ""
    }, {
      id: "GROSS_AMOUNT",
      order: 7,
      alias: ""
    }, {
      id: "MP_FEE_AMOUNT",
      order: 8,
      alias: ""
    }, {
      id: "TAXES_AMOUNT",
      order: 9,
      alias: ""
    }, {
      id: "PAYMENT_METHOD",
      order: 10,
      alias: ""
    }, {
      id: "BUSINESS_UNIT",
      order: 11,
      alias: ""
    }, {
      id: "SUB_UNIT",
      order: 12,
      alias: ""
    }, {
      id: "BALANCE_AMOUNT",
      order: 13,
      alias: ""
    }, {
      id: "PAYMENT_METHOD_TYPE",
      order: 14,
      alias: ""
    }, {
      id: "PURCHASE_ID",
      order: 15,
      alias: ""
    }, {
      id: "ORDER_ID",
      order: 16,
      alias: ""
    }, {
      id: "PRODUCT_SKU",
      order: 17,
      alias: ""
    }, {
      id: "EXTERNAL_REFERENCE",
      order: 18
    }, {
      id: "CURRENCY",
      order: 19
    }, {
      id: "FINANCING_FEE_AMOUNT",
      order: 20
    }, {
      id: "RECORD_TYPE",
      order: 21
    }, {
      id: "SHIPPING_FEE_AMOUNT",
      order: 22
    }, {
      id: "COUPON_AMOUNT",
      order: 23
    }, {
      id: "INSTALLMENTS",
      order: 24
    }, {
      id: "TAX_DETAIL",
      order: 25
    }, {
      id: "TAX_AMOUNT_TELCO",
      order: 26
    }, {
      id: "TAXES_DISAGGREGATED",
      order: 27
    }, {
      id: "EFFECTIVE_COUPON_AMOUNT",
      order: 28
    }, {
      id: "METADATA",
      order: 29
    }, {
      id: "SELLER_AMOUNT",
      order: 30
    }, {
      id: "CARD_INITIAL_NUMBER",
      order: 31
    }, {
      id: "OPERATION_TAGS",
      order: 32
    }, {
      id: "ITEM_ID",
      order: 33
    }, {
      id: "PAYOUT_BANK_ACCOUNT_NUMBER",
      order: 34
    }, {
      id: "SALE_DETAIL",
      order: 35
    }, {
      id: "TRANSACTION_INTENT_ID",
      order: 36
    }, {
      id: "FRANCHISE",
      order: 37
    }, {
      id: "LAST_FOUR_DIGITS",
      order: 38
    }, {
      id: "ORDER_MP",
      order: 39
    }, {
      id: "POS_ID",
      order: 40
    }, {
      id: "POS_NAME",
      order: 41
    }, {
      id: "EXTERNAL_POS_ID",
      order: 42
    }, {
      id: "STORE_ID",
      order: 43
    }, {
      id: "STORE_NAME",
      order: 44
    }, {
      id: "EXTERNAL_STORE_ID",
      order: 45
    }, {
      id: "POI_ID",
      order: 46
    }, {
      id: "SHIPPING_ID",
      order: 47
    }, {
      id: "SHIPMENT_MODE",
      order: 48
    }, {
      id: "PACK_ID",
      order: 49
    }, {
      id: "POI_WALLET_NAME",
      order: 50
    }, {
      id: "POI_BANK_NAME",
      order: 51
    }, {
      id: "SHIPPING_ORDER_ID",
      order: 52
    }, {
      id: "ISSUER_NAME",
      order: 53
    }, {
      id: "COUNTRY_ISSUER",
      order: 54
    }],
    groups: ["check_available_balance", "compensate_detail", "unite_reserve", "visible_zero_releases"],
    fileConfig: {},
    is_legacy_translation: true,
    country_user_language: "en",
    selected_report_language: "en",
    selected_header_language: "en"
  },
  previousSettings: {
    columns: {
      sections: [{
        id: "DATE",
        title: "Data da liberação",
        key: "DATE",
        alias: "",
        order: 1,
        checked: true
      }, {
        id: "TRANSACTION_APPROVAL_DATE",
        title: "Data de aprovação",
        key: "TRANSACTION_APPROVAL_DATE",
        alias: "",
        order: 2,
        checked: true
      }, {
        id: "SOURCE_ID",
        title: "ID da operação no Mercado Pago",
        key: "SOURCE_ID",
        alias: "",
        order: 3,
        checked: true
      }, {
        id: "DESCRIPTION",
        title: "Descrição",
        key: "DESCRIPTION",
        alias: "",
        order: 4,
        checked: true
      }, {
        id: "NET_CREDIT_AMOUNT",
        title: "Valor líquido creditado",
        key: "NET_CREDIT_AMOUNT",
        alias: "",
        order: 5,
        checked: true
      }, {
        id: "NET_DEBIT_AMOUNT",
        title: "Valor líquido debitado",
        key: "NET_DEBIT_AMOUNT",
        alias: "",
        order: 6,
        checked: true
      }, {
        id: "GROSS_AMOUNT",
        title: "Valor bruto da operação",
        key: "GROSS_AMOUNT",
        alias: "",
        order: 7,
        checked: true
      }, {
        id: "MP_FEE_AMOUNT",
        title: "Tarifa do Mercado Pago ou do Mercado Livre",
        key: "MP_FEE_AMOUNT",
        alias: "",
        order: 8,
        checked: true
      }, {
        id: "TAXES_AMOUNT",
        title: "Impostos cobrados por retenções de IIBB",
        key: "TAXES_AMOUNT",
        alias: "",
        order: 9,
        checked: true
      }, {
        id: "PAYMENT_METHOD",
        title: "Meio de pagamento",
        key: "PAYMENT_METHOD",
        alias: "",
        order: 10,
        checked: true
      }, {
        id: "BUSINESS_UNIT",
        title: "Canal de venda",
        key: "BUSINESS_UNIT",
        alias: "",
        order: 11,
        checked: true
      }, {
        id: "SUB_UNIT",
        title: "Plataforma de pagamento",
        key: "SUB_UNIT",
        alias: "",
        order: 12,
        checked: true
      }, {
        id: "BALANCE_AMOUNT",
        title: "Saldo",
        key: "BALANCE_AMOUNT",
        alias: "",
        order: 13,
        checked: true
      }, {
        id: "PAYMENT_METHOD_TYPE",
        title: "Tipo de meio de pagamento",
        key: "PAYMENT_METHOD_TYPE",
        alias: "",
        order: 14,
        checked: true
      }, {
        id: "PURCHASE_ID",
        title: "ID da compra",
        key: "PURCHASE_ID",
        alias: "",
        order: 15,
        checked: true
      }, {
        id: "ORDER_ID",
        title: "ID do pedido",
        key: "ORDER_ID",
        alias: "",
        order: 16,
        checked: true
      }, {
        id: "PRODUCT_SKU",
        title: "Código SKU do produto",
        key: "PRODUCT_SKU",
        alias: "",
        order: 17,
        checked: true
      }, {
        id: "EXTERNAL_REFERENCE",
        title: "Código de referência",
        checked: false,
        order: 18
      }, {
        id: "RECORD_TYPE",
        title: "Tipo de registro",
        checked: false,
        order: 19
      }, {
        id: "CURRENCY",
        title: "Moeda",
        checked: false,
        order: 20
      }, {
        id: "FINANCING_FEE_AMOUNT",
        title: "Tarifa por oferecer parcelamento sem acréscimo",
        checked: false,
        order: 21
      }, {
        id: "SHIPPING_FEE_AMOUNT",
        title: "Custo de envio",
        checked: false,
        order: 22
      }, {
        id: "COUPON_AMOUNT",
        title: "Cupom de desconto",
        checked: false,
        order: 23
      }, {
        id: "INSTALLMENTS",
        title: "Parcelas",
        checked: false,
        order: 24
      }, {
        id: "TAX_DETAIL",
        title: "Detalhes dos impostos",
        checked: false,
        order: 25
      }, {
        id: "TAX_AMOUNT_TELCO",
        title: "Imposto descontado do valor bruto para telecomunicações",
        checked: false,
        order: 26
      }, {
        id: "TAXES_DISAGGREGATED",
        title: "Impostos desagregados",
        checked: false,
        order: 27
      }, {
        id: "EFFECTIVE_COUPON_AMOUNT",
        title: "Custo de oferecer desconto",
        checked: false,
        order: 28
      }, {
        id: "METADATA",
        title: "Dados adicionais",
        checked: false,
        order: 29
      }, {
        id: "SELLER_AMOUNT",
        title: "Valor recebido por compras com split de pagamento",
        checked: false,
        order: 30
      }, {
        id: "CARD_INITIAL_NUMBER",
        title: "Cartão do seu comprador",
        checked: false,
        order: 31
      }, {
        id: "OPERATION_TAGS",
        title: "Etiquetas da transação",
        checked: false,
        order: 32
      }, {
        id: "ITEM_ID",
        title: "Código do produto",
        checked: false,
        order: 33
      }, {
        id: "PAYOUT_BANK_ACCOUNT_NUMBER",
        title: "Conta de destino da retirada",
        checked: false,
        order: 34
      }, {
        id: "SALE_DETAIL",
        title: "Detalhe da venda",
        checked: false,
        order: 35
      }, {
        id: "TRANSACTION_INTENT_ID",
        title: "ID de tentativa de transação",
        checked: false,
        order: 36
      }, {
        id: "FRANCHISE",
        title: "Bandeira",
        checked: false,
        order: 37
      }, {
        id: "LAST_FOUR_DIGITS",
        title: "Últimos 4 dígitos",
        checked: false,
        order: 38
      }, {
        id: "ORDER_MP",
        title: "ID da solicitação",
        checked: false,
        order: 39
      }, {
        id: "POS_ID",
        title: "ID do caixa",
        checked: false,
        order: 40
      }, {
        id: "POS_NAME",
        title: "Nome do caixa",
        checked: false,
        order: 41
      }, {
        id: "EXTERNAL_POS_ID",
        title: "ID do caixa, definido pelo usuário",
        checked: false,
        order: 42
      }, {
        id: "STORE_ID",
        title: "ID da loja",
        checked: false,
        order: 43
      }, {
        id: "STORE_NAME",
        title: "Nome da loja",
        checked: false,
        order: 44
      }, {
        id: "EXTERNAL_STORE_ID",
        title: "ID da loja, definido pelo usuário",
        checked: false,
        order: 45
      }, {
        id: "POI_ID",
        title: "Número de série da maquininha (S/N)",
        checked: false,
        order: 46
      }, {
        id: "SHIPPING_ID",
        title: "ID do envio",
        checked: false,
        order: 47
      }, {
        id: "SHIPMENT_MODE",
        title: "Modalidade de Frete",
        checked: false,
        order: 48
      }, {
        id: "PACK_ID",
        title: "ID do pacote",
        checked: false,
        order: 49
      }, {
        id: "POI_WALLET_NAME",
        title: "Carteira digital",
        checked: false,
        order: 50
      }, {
        id: "POI_BANK_NAME",
        title: "Banco de origem",
        checked: false,
        order: 51
      }, {
        id: "SHIPPING_ORDER_ID",
        title: "ID de associação de envios",
        checked: false,
        order: 52
      }, {
        id: "ISSUER_NAME",
        title: "Nome do emissor",
        checked: false,
        order: 53
      }, {
        id: "COUNTRY_ISSUER",
        title: "País emissor",
        checked: false,
        order: 54
      }]
    },
    separators: ";",
    fileName: "",
    displayTimezone: "GMT-03",
    displayLanguage: "en",
    reportLanguage: "en",
    headerLanguage: "en",
    isLegacyTranslation: true,
    countryUserLanguage: "en",
    selectedReportLanguage: "en",
    selectedHeaderLanguage: "en",
    advancedSettings: {
      groups: [{
        mainOption: {
          id: "additional_rows",
          subOptions: [{
            showOption: true,
            id: "check_available_balance",
            title: "Saldo disponível antes e depois de sacar dinheiro",
            description: "Acrescenta duas novas linhas ao relatório com saldo disponível antes e depois de um saque.",
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: false
          }, {
            showOption: true,
            id: "compensate_detail",
            title: "Movimentações compensadas",
            description: "Inclui movimentações de bloqueio e desbloqueio de dinheiro compensadas entre si (Crédito - Débito = 0) em um determinado período.",
            shouldValidateNLedger: true,
            showKeyName: true,
            isNewOption: false
          }, {
            showOption: true,
            id: "unite_reserve",
            title: "Ocultar transações de reserva compensadas",
            description: "Ao selecionar essa opção, vamos ocultar as transações que são mostradas quando seu dinheiro foi reservado e liberado dentro do período do relatório solicitado.",
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: true
          }, {
            showOption: true,
            id: "visible_zero_releases",
            title: "Mostrar liberações em zero",
            description: "Marcando esta opção, serão mostradas as transações com balanço zero, que correspondem a vendas ou pagamentos cancelados.",
            shouldValidateNLedger: false,
            showKeyName: true,
            isNewOption: true
          }]
        }
      }],
      selected: []
    },
    emails: [],
    ftp: {
      server: "",
      port: "",
      path: "",
      user: "",
      pass: ""
    },
    webhook: {
      url: "",
      password: ""
    }
  },
  sellerId: "",
  userId: "",
  tonicUsername: ""
};
// CONCATENATED MODULE: ./src/platform/mercado/utils/index.js
function utils_typeof(obj) { "@babel/helpers - typeof"; return utils_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; }, utils_typeof(obj); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || utils_unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function utils_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return utils_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 utils_arrayLikeToArray(o, minLen); }

function utils_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; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function utils_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ utils_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" == utils_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 utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function utils_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { utils_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }


 // 记录任务期间所有站点 Cookie 覆盖规则 ID（每次切换站点都会新增一条），任务结束后需要全部清除

var siteCookieRuleIds = []; // 站点 key 到 IANA 时区名称的映射

var SITE_TIMEZONE_IANA_MAP = {
  MLM: 'America/Mexico_City',
  MLB: 'America/Sao_Paulo',
  MLC: 'America/Santiago',
  MCO: 'America/Bogota',
  MLA: 'America/Argentina/Buenos_Aires',
  MLU: 'America/Montevideo',
  AR: 'America/Argentina/Buenos_Aires',
  MX: 'America/Mexico_City',
  CO: 'America/Bogota',
  PE: 'America/Lima',
  UY: 'America/Montevideo',
  VE: 'America/Caracas',
  EC: 'America/Guayaquil',
  PA: 'America/Panama',
  PY: 'America/Asuncion',
  HN: 'America/Tegucigalpa',
  NI: 'America/Managua',
  SV: 'America/El_Salvador',
  GT: 'America/Guatemala',
  DO: 'America/Santo_Domingo',
  BO: 'America/La_Paz',
  BR: 'America/Sao_Paulo',
  CL: 'America/Santiago',
  CR: 'America/Costa_Rica'
};
/**
 * @description 切换 mercado 站点 cookie
 */

var changeMercadoSite = /*#__PURE__*/function () {
  var _ref = utils_asyncToGenerator( /*#__PURE__*/utils_regeneratorRuntime().mark(function _callee(site, host) {
    var url, _cookie, hasSiteId, hasSiteSelector, arr, newCookies, ruleId, msg;

    return utils_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            url = (host || '').trim();

            if (url) {
              _context.next = 4;
              break;
            }

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

          case 4:
            _context.next = 6;
            return Object(util["o" /* getAllCookies */])({
              url: url
            });

          case 6:
            _cookie = _context.sent;
            hasSiteId = false;
            hasSiteSelector = false;
            arr = _cookie.map(function (_ref2) {
              var name = _ref2.name,
                  value = _ref2.value;

              if (name === 'cbtSiteId') {
                hasSiteId = true;
                return "cbtSiteId=".concat(site.site_key);
              }

              if (name === 'cbtSiteSelector') {
                hasSiteSelector = true;
                return "cbtSiteSelector=".concat(site.site_user_id);
              }

              return "".concat(name, "=").concat(value);
            });
            if (!hasSiteId) arr.push("cbtSiteId=".concat(site.site_key));
            if (!hasSiteSelector) arr.push("cbtSiteSelector=".concat(site.site_user_id));
            newCookies = arr.join(';');
            log["a" /* default */].setLog('changeMercadoSite', "url:".concat(url, "---"), 'arr:', arr, '---', '_cookie:', _cookie);

            if (!(newCookies === _cookie.map(function (_ref3) {
              var name = _ref3.name,
                  value = _ref3.value;
              return "".concat(name, "=").concat(value);
            }).join(';'))) {
              _context.next = 17;
              break;
            }

            log["a" /* default */].setLog("cookie\u672A\u4FEE\u6539\uFF0C\u4E0D\u9700\u8981\u76D1\u542C");
            return _context.abrupt("return", true);

          case 17:
            _context.next = 19;
            return Object(util["I" /* setRequestHearder */])([{
              name: 'Cookie',
              value: newCookies
            }], url + '/*');

          case 19:
            ruleId = _context.sent;
            // await setCookies({ url, name: 'cbtSiteId', value: site.site_key })
            // await setCookies({ url, name: 'cbtSiteSelector', value: site.site_user_id })
            if (ruleId) siteCookieRuleIds.push(ruleId);
            log["a" /* default */].setLog("\u5207\u6362\u7AD9\u70B9 cookie \u6210\u529F\uFF1A".concat(site.site_key));
            return _context.abrupt("return", true);

          case 25:
            _context.prev = 25;
            _context.t0 = _context["catch"](0);
            msg = "\u76D1\u542Cmercado\u8BF7\u6C42\u5E76\u4FEE\u6539cookie\u5931\u8D25,\u5931\u8D25\u539F\u56E0\uFF1A".concat(Object(util["u" /* isError */])(_context.t0));
            log["a" /* default */].report(msg, 'error', site.site_key);
            return _context.abrupt("return", false);

          case 30:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 25]]);
  }));

  return function changeMercadoSite(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();
/**
 * 清除站点 Cookie 覆盖规则，恢复客户浏览器正常的站点切换能力
 * 在跨境报表任务结束后调用
 */

var clearMercadoSiteCookie = /*#__PURE__*/function () {
  var _ref4 = utils_asyncToGenerator( /*#__PURE__*/utils_regeneratorRuntime().mark(function _callee2() {
    return utils_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            if (!(siteCookieRuleIds.length === 0)) {
              _context2.next = 2;
              break;
            }

            return _context2.abrupt("return");

          case 2:
            _context2.prev = 2;
            _context2.next = 5;
            return Object(util["D" /* removeDeclarativeNetRequestRules */])(siteCookieRuleIds);

          case 5:
            log["a" /* default */].setLog("\u5DF2\u6E05\u9664 ".concat(siteCookieRuleIds.length, " \u6761\u7AD9\u70B9 Cookie \u8986\u76D6\u89C4\u5219\uFF08ruleIds: ").concat(siteCookieRuleIds.join(','), "\uFF09"));
            _context2.next = 11;
            break;

          case 8:
            _context2.prev = 8;
            _context2.t0 = _context2["catch"](2);
            log["a" /* default */].setLog("\u6E05\u9664\u7AD9\u70B9 Cookie \u8986\u76D6\u89C4\u5219\u5931\u8D25\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0)));

          case 11:
            _context2.prev = 11;
            siteCookieRuleIds = [];
            return _context2.finish(11);

          case 14:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[2, 8, 11, 14]]);
  }));

  return function clearMercadoSiteCookie() {
    return _ref4.apply(this, arguments);
  };
}();
/**
 * 根据站点 key 获取当前时刻对应的 GMT 偏移字符串，自动处理夏令时
 * @param {string} siteKey - 站点key（如 'MLC', 'PY', 'CL'）
 * @returns {string} GMT 偏移字符串（如 'GMT-03', 'GMT-04'）
 */

var getGmtOffset = function getGmtOffset(siteKey) {
  var ianaName = SITE_TIMEZONE_IANA_MAP[siteKey];
  if (!ianaName) return 'GMT-06';

  try {
    var parts = new Intl.DateTimeFormat('en', {
      timeZone: ianaName,
      timeZoneName: 'shortOffset'
    }).formatToParts(new Date());
    var rawOffset = (parts.find(function (p) {
      return p.type === 'timeZoneName';
    }) || {}).value || ''; // rawOffset 格式如 'GMT-3'、'GMT-4'，补零为 'GMT-03' 格式

    var match = rawOffset.match(/GMT([+-])(\d+)/);
    if (!match) return 'GMT-06';
    return "GMT".concat(match[1]).concat(String(match[2]).padStart(2, '0'));
  } catch (e) {
    return 'GMT-06';
  }
};
/**
 * 将 UTC ISO 字符串根据站点减去对应小时数，转为 YYYY-MM-DD 格式
 * @param {string} isoString - UTC ISO 字符串（如 "2025-12-01T00:00:00Z"）
 * @param {string} siteKey - 站点key
 * @returns {string} YYYY-MM-DD 格式的日期字符串
 */

var convertUtcToSiteDate = function convertUtcToSiteDate(isoString, siteKey) {
  // 1. 解析 ISO 字符串为 Date 对象
  var utcDate = new Date(isoString); // 2. 获取站点对应的 IANA 时区名称

  var timeZone = SITE_TIMEZONE_IANA_MAP[siteKey] || 'America/Mexico_City'; // 3. 使用站点时区格式化日期（会自动处理时区转换）

  return new Intl.DateTimeFormat('en-CA', {
    timeZone: timeZone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).format(utcDate);
};
/**
 * 将日期字符串转换为 UTC ISO 字符串
 * @param {string} dateStr - 日期字符串（如 "2025-12-01"）
 * @returns {string} UTC 时间的 ISO 字符串
 */

var convertToUtc = function convertToUtc(dateStr) {
  // 解析日期字符串，构造 UTC 时间的 Date 对象
  var _dateStr$split$map = dateStr.split('-').map(Number),
      _dateStr$split$map2 = _slicedToArray(_dateStr$split$map, 3),
      year = _dateStr$split$map2[0],
      month = _dateStr$split$map2[1],
      day = _dateStr$split$map2[2];

  var utcDate = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0)); // 转换为 ISO 字符串

  return utcDate.toISOString();
};
// CONCATENATED MODULE: ./src/platform/mercado/report/getPagoReport.js
function getPagoReport_typeof(obj) { "@babel/helpers - typeof"; return getPagoReport_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; }, getPagoReport_typeof(obj); }

function getPagoReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getPagoReport_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" == getPagoReport_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 getPagoReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getPagoReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getPagoReport_ownKeys(Object(source), !0).forEach(function (key) { getPagoReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getPagoReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getPagoReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getPagoReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getPagoReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getPagoReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getPagoReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }








/**
 * 判断异常是否为美客多限流（返回 403 + HTML 页面）
 * fetchAdapter 抛出的错误消息格式固定为：HTTP error! Status: 403, Reaponse: <html>...
 * 限流返回 HTML，真实鉴权失败返回 JSON，可通过响应体是否含 <html 来区分
 */

var isRateLimited403 = function isRateLimited403(e) {
  var msg = e instanceof Error ? e.message : String(e);
  return /Status:\s*403/.test(msg) && /<html/i.test(msg);
}; // 生成报告前，保存报表设置


var saveReportSettings = /*#__PURE__*/function () {
  var _ref = getPagoReport_asyncToGenerator( /*#__PURE__*/getPagoReport_regeneratorRuntime().mark(function _callee(task) {
    var _task$currentSite, _task$currentSite2, siteKey, currentSiteKey, settingsParams, params, res, msg, _msg;

    return getPagoReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            siteKey = task.store_type === 'GLOBAL' ? (((_task$currentSite = task.currentSite) === null || _task$currentSite === void 0 ? void 0 : _task$currentSite.site_key) || '').substring(0, 3) : task.area;
            currentSiteKey = ((_task$currentSite2 = task.currentSite) === null || _task$currentSite2 === void 0 ? void 0 : _task$currentSite2.site_key) || '';
            settingsParams = LocalPagoSettingsParams;

            if (task.store_type === 'GLOBAL') {
              // 跨境中哥伦比亚站点（MCO-*）使用单独的报表参数
              settingsParams = currentSiteKey.startsWith('MCO') ? cbPagoSettingsParamsColombia : cbPagoSettingsParams;
            }

            params = getPagoReport_objectSpread(getPagoReport_objectSpread({}, settingsParams), {}, {
              previousSettings: getPagoReport_objectSpread(getPagoReport_objectSpread({}, settingsParams.previousSettings), {}, {
                displayTimezone: getGmtOffset(siteKey)
              })
            }); // 根据当前站点动态计算时区偏移，自动处理夏令时

            _context.next = 8;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/balance/reports/api/reports/release/settings"), 'post', params);

          case 8:
            res = _context.sent;

            if (!(res && res.response === 'ok')) {
              _context.next = 13;
              break;
            }

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

          case 13:
            msg = "\u4FDD\u5B58\u62A5\u8868\u8BBE\u7F6E\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(res === null || res === void 0 ? void 0 : res.errorMsg);
            task.msg = msg;
            task.status = 3;
            log["a" /* default */].setLog(msg);
            return _context.abrupt("return", false);

          case 18:
            _context.next = 27;
            break;

          case 20:
            _context.prev = 20;
            _context.t0 = _context["catch"](0);
            _msg = isRateLimited403(_context.t0) ? "\u4FDD\u5B58\u62A5\u8868\u8BBE\u7F6E\u5931\u8D25\uFF0C\u7F8E\u5BA2\u591A\u540E\u53F0\u9650\u6D41\uFF08\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF09\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0)) : "\u4FDD\u5B58\u62A5\u8868\u8BBE\u7F6E\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context.t0, task));
            task.msg = _msg;
            task.status = 3;
            log["a" /* default */].setLog(_msg);
            return _context.abrupt("return", false);

          case 27:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 20]]);
  }));

  return function saveReportSettings(_x) {
    return _ref.apply(this, arguments);
  };
}(); // 生成报告


var getPagoReport_generateReport = /*#__PURE__*/function () {
  var _ref2 = getPagoReport_asyncToGenerator( /*#__PURE__*/getPagoReport_regeneratorRuntime().mark(function _callee2(task) {
    var paramsRes, dateEnd, res;
    return getPagoReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            _context2.next = 3;
            return saveReportSettings(task);

          case 3:
            paramsRes = _context2.sent;

            if (paramsRes) {
              _context2.next = 6;
              break;
            }

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

          case 6:
            // 使用调整后的结束日期（如果被调整过）
            dateEnd = task.isEndDateAdjusted ? moment_default()(task.report_custom_date_end).subtract(1, 'days').format('YYYY-MM-DD') : task.report_custom_date_end;
            _context2.next = 9;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/balance/reports/api/reports/release/statements"), 'post', {
              type: "date_range",
              data: {
                date_start: convertToUtc(task.report_custom_date_start),
                date_end: convertToUtc(dateEnd),
                format: 'XLSX',
                selectedDates: {
                  from: convertToUtc(task.report_custom_date_start),
                  to: convertToUtc(dateEnd)
                }
              }
            });

          case 9:
            res = _context2.sent;

            if (!res) {
              _context2.next = 15;
              break;
            }

            // todo: 暂未知接口成功如何返回
            log["a" /* default */].setLog('半托管财务报表生成成功');
            return _context2.abrupt("return", true);

          case 15:
            return _context2.abrupt("return", true);

          case 16:
            _context2.next = 24;
            break;

          case 18:
            _context2.prev = 18;
            _context2.t0 = _context2["catch"](0);
            task.msg = isRateLimited403(_context2.t0) ? "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7F8E\u5BA2\u591A\u540E\u53F0\u9650\u6D41\uFF08\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF09\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0)) : "\u62A5\u544A\u751F\u6210\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context2.t0, task));
            task.status = 3;
            log["a" /* default */].setLog(task.msg);
            return _context2.abrupt("return", false);

          case 24:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 18]]);
  }));

  return function generateReport(_x2) {
    return _ref2.apply(this, arguments);
  };
}();
/**
 * 查询报表生成状态
 * @param {Object} task
 * @param {number} count - 当前重试次数
 * @param {boolean} waitIfNotFound - 已触发生成时传 true：列表中找不到报告也视为"生成中"继续等待，
 *   用于处理数据量大时报告不出现在列表（美客多提示 "We are processing your data"）的场景
 * @returns {boolean} true=报告已就绪可下载；false=失败或超时（task.status=6）或未找到（task.status不变）
 *   注意：未找到历史报告时（waitIfNotFound=false）不修改 task.status，由上层决定是否触发生成
 */


var getPagoReport_awaitReportDownload = /*#__PURE__*/function () {
  var _ref3 = getPagoReport_asyncToGenerator( /*#__PURE__*/getPagoReport_regeneratorRuntime().mark(function _callee3(task) {
    var count,
        waitIfNotFound,
        res,
        hasResults,
        list,
        compareDateEnd,
        taskStart,
        taskStartMinusOne,
        compareEndPlusOne,
        compareEndMinusOne,
        find,
        _args3 = arguments;
    return getPagoReport_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            count = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : 0;
            waitIfNotFound = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : false;
            _context3.prev = 2;

            if (!(count >= 5)) {
              _context3.next = 9;
              break;
            }

            log["a" /* default */].setLog('文件正在生成，超过最大重试次数，退出执行下一任务');
            task.run_time = 0;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D";
            task.status = 6;
            return _context3.abrupt("return", false);

          case 9:
            _context3.next = 11;
            return Object(util["z" /* nativeRequest */])("".concat(task.host, "/balance/reports/api/reports/release/statements"), 'get', {
              page: 1,
              year: 'creation'
            });

          case 11:
            res = _context3.sent;
            hasResults = Array.isArray(res === null || res === void 0 ? void 0 : res.results);

            if (!(hasResults && res.results.length > 0)) {
              _context3.next = 54;
              break;
            }

            list = res.results; // 期望的 task 日期范围；compareDateEnd 仅本土店铺(LOCAL)在 endDate==今天时被减一天

            compareDateEnd = task.isEndDateAdjusted ? moment_default()(task.report_custom_date_end).subtract(1, 'days').format('YYYY-MM-DD') : task.report_custom_date_end;
            taskStart = task.report_custom_date_start;
            taskStartMinusOne = moment_default()(taskStart).subtract(1, 'days').format('YYYY-MM-DD');
            compareEndPlusOne = moment_default()(compareDateEnd).add(1, 'days').format('YYYY-MM-DD');
            compareEndMinusOne = moment_default()(compareDateEnd).subtract(1, 'days').format('YYYY-MM-DD'); // 匹配逻辑：
            // 1) 只处理整天 XLSX 报表（use_exact_time=false），按放款自动生成的 CSV 报表跳过
            // 2) 用浏览器本地时区把 UTC 转日期 —— 客户的浏览器 TZ ≈ 客户 Mercado 账户 displayTimezone，
            //    所以"浏览器看到的本地日期"与"账户里存的本地日期"几乎总是一致
            // 3) ±1 天容差兜住两类边界：
            //    - localStart 容差 [-1, 0]：Mercado 跨境 GMT-6 会把 dateStart 往前推 1 天
            //    - localEnd 容差 [-1, 0, +1]：兼容客户在 UI 多选一天、本土 -1 调整、新旧任务并存

            find = list.find(function (item) {
              var _item$internalManagem, _item$download;

              if ((item === null || item === void 0 ? void 0 : (_item$internalManagem = item.internalManagement) === null || _item$internalManagem === void 0 ? void 0 : _item$internalManagem.use_exact_time) !== false) return false;
              if (!(item !== null && item !== void 0 && (_item$download = item.download) !== null && _item$download !== void 0 && _item$download.xlsx)) return false;
              var itemDateStart = moment_default()(item.dateStart).format('YYYY-MM-DD');
              var itemDateEnd = moment_default()(item.dateEnd).format('YYYY-MM-DD');
              var startOk = itemDateStart === taskStart || itemDateStart === taskStartMinusOne;
              var endOk = itemDateEnd === compareDateEnd || itemDateEnd === compareEndPlusOne || itemDateEnd === compareEndMinusOne;

              if (startOk && endOk) {
                log["a" /* default */].setLog("\u5339\u914D\u5230\u62A5\u8868 ".concat(item.id, ": \u672C\u5730\u8303\u56F4=").concat(itemDateStart, "~").concat(itemDateEnd, ", ") + "\u671F\u671B=".concat(taskStart, "~").concat(compareDateEnd, " (store_type=").concat(task.store_type || 'LOCAL', ")"));
                return true;
              }

              return false;
            });

            if (!find) {
              _context3.next = 38;
              break;
            }

            // 报告已在列表中：已完成则下载，否则等待
            log["a" /* default */].setLog('find===匹配到文件了====', JSON.stringify(find));
            log["a" /* default */].setLog('===waitIfNotFound====', waitIfNotFound);

            if (!(find.status === 'processed' && find.download)) {
              _context3.next = 28;
              break;
            }

            task.status = 2;
            task.downloadId = find.download.xlsx;
            return _context3.abrupt("return", true);

          case 28:
            // 报告存在但未完成（status 非 processed，或 download 尚未就绪）
            task.status = 6;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D\uFF08\u72B6\u6001\uFF1A".concat(find.status || '未知', "\uFF09");
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context3.next = 33;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 33:
            _context3.next = 35;
            return getPagoReport_awaitReportDownload(task, ++count, waitIfNotFound);

          case 35:
            return _context3.abrupt("return", _context3.sent);

          case 38:
            if (!waitIfNotFound) {
              _context3.next = 49;
              break;
            }

            // 已触发生成，但报告未在列表中出现（数据量大，后台提示 "We are processing your data"）
            task.status = 6;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D";
            log["a" /* default */].setLog(task.msg, "\u62A5\u544A\u5C1A\u672A\u51FA\u73B0\u5728\u5217\u8868\u4E2D\uFF0C\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context3.next = 44;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 44:
            _context3.next = 46;
            return getPagoReport_awaitReportDownload(task, ++count, waitIfNotFound);

          case 46:
            return _context3.abrupt("return", _context3.sent);

          case 49:
            // 第一次查询，列表中无匹配的历史报告，需要触发生成
            // 注意：此处不修改 task.status，上层通过 task.status 是否为 6 来判断是否应触发 generateReport
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"----not find";
            log["a" /* default */].setLog(task.msg);
            return _context3.abrupt("return", false);

          case 52:
            _context3.next = 75;
            break;

          case 54:
            if (!waitIfNotFound) {
              _context3.next = 65;
              break;
            }

            // 列表为空且已触发生成，继续等待（后台仍在处理数据）
            task.status = 6;
            task.msg = "\u6587\u4EF6\u6B63\u5728\u751F\u6210\u4E2D";
            log["a" /* default */].setLog(task.msg, "\u5F53\u524D\u91CD\u8BD5\u6B21\u6570-".concat(count));
            _context3.next = 60;
            return Object(util["h" /* delayed */])(30 * 1000);

          case 60:
            _context3.next = 62;
            return getPagoReport_awaitReportDownload(task, ++count, waitIfNotFound);

          case 62:
            return _context3.abrupt("return", _context3.sent);

          case 65:
            if (!hasResults) {
              _context3.next = 71;
              break;
            }

            // 第一次查询，结果列表为空，按未找到历史报表处理，继续触发生成
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"----not find";
            log["a" /* default */].setLog(task.msg);
            return _context3.abrupt("return", false);

          case 71:
            task.status = 6;
            task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0CMercado\u89C4\u5219\u53EF\u80FD\u6539\u53D8\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"";
            log["a" /* default */].setLog(task.msg);
            return _context3.abrupt("return", false);

          case 75:
            _context3.next = 83;
            break;

          case 77:
            _context3.prev = 77;
            _context3.t0 = _context3["catch"](2);
            task.status = 6;

            if (isRateLimited403(_context3.t0)) {
              // 限流是暂时性的，不设置 error_time，允许任务稍后重试
              task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7F8E\u5BA2\u591A\u540E\u53F0\u9650\u6D41\uFF08\u8BF7\u7A0D\u540E\u91CD\u8BD5\uFF09\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0));
            } else {
              task.msg = "\u67E5\u8BE2\u62A5\u8868\u751F\u6210\u72B6\u6001\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context3.t0, task));
            }

            log["a" /* default */].setLog(task.msg);
            return _context3.abrupt("return", false);

          case 83:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[2, 77]]);
  }));

  return function awaitReportDownload(_x3) {
    return _ref3.apply(this, arguments);
  };
}(); // 下载报表


var getPagoReport_downloadReport = /*#__PURE__*/function () {
  var _ref4 = getPagoReport_asyncToGenerator( /*#__PURE__*/getPagoReport_regeneratorRuntime().mark(function _callee4(task) {
    var res, url, name, oFile, fileRes, zip;
    return getPagoReport_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios_default()({
              method: 'GET',
              url: task.host + task.downloadId,
              responseType: 'blob'
            });

          case 3:
            res = _context4.sent;

            if (!(res && res.data)) {
              _context4.next = 20;
              break;
            }

            url = task.host + task.downloadId;
            name = Object(util["q" /* getNameByUrl */])(url);

            if (!name.includes('.')) {
              name = "".concat(name, ".xlsx");
            }

            oFile = new File([res.data], name, {
              type: 'application/zip'
            });
            // 文件压缩
            log["a" /* default */].setLog('源文件大小', "".concat(oFile.size, "b"));
            zip = new jszip_min_default.a();
            zip.file(name, res.data, {
              binary: true
            });
            _context4.next = 14;
            return zip.generateAsync({
              type: "nodebuffer",
              compression: "DEFLATE",
              // STORE：默认不压缩 DEFLATE：需要压缩
              compressionOptions: {
                level: 9 // 压缩等级1~9    1压缩速度最快，9最优压缩方式

              }
            }).then(function (res) {
              var cFile = new File([res], "".concat(name.split('.')[0], ".zip"), {
                type: 'application/zip'
              });
              log["a" /* default */].setLog('压缩后文件大小', "".concat(cFile.size, "b"), cFile.name);
              fileRes = {
                file: cFile
              };
            }).catch(function (e) {
              log["a" /* default */].setLog('财务报表压缩失败', Object(util["u" /* isError */])(e));
              fileRes = {
                file: oFile
              };
            });

          case 14:
            log["a" /* default */].setLog('下载成功');
            task.status = 4;
            task.report_get_date = moment_default()().format('YYYY-MM-DD HH:mm:ss');
            return _context4.abrupt("return", fileRes);

          case 20:
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u54CD\u5E94\u4F53\u4E3A\u7A7A";
            log["a" /* default */].setLog(task.msg);
            return _context4.abrupt("return", false);

          case 24:
            _context4.next = 32;
            break;

          case 26:
            _context4.prev = 26;
            _context4.t0 = _context4["catch"](0);
            task.status = 5;
            task.msg = "\u4E0B\u8F7D\u5931\u8D25\uFF0C\u7A0D\u540E\u53EF\u5C1D\u8BD5\"\u91CD\u65B0\u83B7\u53D6\"\uFF0C\u4EE5\u4E0B\u4E3A\u9875\u9762\u539F\u59CB\u62A5\u9519\uFF1A".concat(Object(util["u" /* isError */])(_context4.t0, task));
            log["a" /* default */].setLog(task.msg);
            return _context4.abrupt("return", false);

          case 32:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 26]]);
  }));

  return function downloadReport(_x4) {
    return _ref4.apply(this, arguments);
  };
}();

var getPagoReport = /*#__PURE__*/function () {
  var _ref5 = getPagoReport_asyncToGenerator( /*#__PURE__*/getPagoReport_regeneratorRuntime().mark(function _callee5(task) {
    var today, isEndDateToday, param, res, uploadRes;
    return getPagoReport_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            // 判断结束时间是否是当天，如果是则修改为前一天并设置标记
            // 注意：仅本土店铺保留此调整；跨境/半托（store_type === 'GLOBAL'）经验证可以生成"当天"
            // 截止的报表，不再做 -1 天调整，避免与客户后台实际生成的报表对不上 dateEnd。
            if (task.store_type === 'GLOBAL') {
              task.isEndDateAdjusted = false;
            } else {
              // 获取北京时间的当前日期（UTC+8）
              today = new Intl.DateTimeFormat('en-CA', {
                timeZone: 'Asia/Shanghai',
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
              }).format(new Date());
              isEndDateToday = task.report_custom_date_end === today;

              if (isEndDateToday) {
                task.isEndDateAdjusted = true;
                log["a" /* default */].setLog("\u7ED3\u675F\u65F6\u95F4\u4E3A\u5F53\u5929\uFF0C\u5BF9\u6BD4\u65F6\u5C06\u4F7F\u7528\u524D\u4E00\u5929\uFF1A".concat(moment_default()(task.report_custom_date_end).subtract(1, 'days').format('YYYY-MM-DD')));
              } else {
                task.isEndDateAdjusted = false;
              }
            } // 先查询历史报告列表，有则直接复用，没有则触发生成


            _context5.next = 3;
            return getPagoReport_awaitReportDownload(task);

          case 3:
            if (_context5.sent) {
              _context5.next = 10;
              break;
            }

            if (!(task.status === 6)) {
              _context5.next = 6;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 6:
            _context5.next = 8;
            return getPagoReport_generateReport(task);

          case 8:
            if (_context5.sent) {
              _context5.next = 10;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 10:
            _context5.t0 = task.status !== 2;

            if (!_context5.t0) {
              _context5.next = 15;
              break;
            }

            _context5.next = 14;
            return getPagoReport_awaitReportDownload(task, 0, true);

          case 14:
            _context5.t0 = !_context5.sent;

          case 15:
            if (!_context5.t0) {
              _context5.next = 17;
              break;
            }

            return _context5.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 17:
            // 默认参数
            param = {
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: null,
              code: 0,
              msg: null
            };
            _context5.next = 20;
            return getPagoReport_downloadReport(task);

          case 20:
            res = _context5.sent;

            if (!(res && res.file)) {
              _context5.next = 31;
              break;
            }

            _context5.next = 24;
            return Object(util["L" /* uploadFile */])(res.file);

          case 24:
            uploadRes = _context5.sent;
            log["a" /* default */].setLog('文件上传结果：', JSON.stringify(uploadRes));

            if (!(uploadRes && uploadRes.code === 1)) {
              _context5.next = 28;
              break;
            }

            return _context5.abrupt("return", getPagoReport_objectSpread(getPagoReport_objectSpread({}, param), {}, {
              result: {
                report_file: uploadRes.data,
                cosKey: uploadRes.data.key,
                originFileName: uploadRes.data.originFileName,
                report_custom_date_start: task.report_custom_date_start,
                report_custom_date_end: task.report_custom_date_end,
                reportType: task.report_type,
                reportDate: task.report_date_month
              }
            }));

          case 28:
            // 上传失败
            task.status = 7;
            task.msg = '文件上传cos失败';
            param.result = {
              requestId: uploadRes.requestId,
              msg: uploadRes.msg
            };

          case 31:
            if (![8, 12].includes(task.status)) {
              _context5.next = 34;
              break;
            }

            task.isDelete = true;
            return _context5.abrupt("return", getPagoReport_objectSpread(getPagoReport_objectSpread({}, param), {}, {
              msg: task.msg,
              code: task.status === 8 ? 3 : 1
            }));

          case 34:
            return _context5.abrupt("return", getPagoReport_objectSpread(getPagoReport_objectSpread({}, param), {}, {
              code: 2,
              msg: task.msg
            }));

          case 35:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function getPagoReport(_x5) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var report_getPagoReport = (getPagoReport);
// CONCATENATED MODULE: ./src/platform/mercado/report/index.js
function report_typeof(obj) { "@babel/helpers - typeof"; return report_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; }, report_typeof(obj); }

function report_createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = report_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function report_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return report_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 report_arrayLikeToArray(o, minLen); }

function report_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; }

function report_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ report_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" == report_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 report_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function report_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { report_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { report_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function report_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function report_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? report_ownKeys(Object(source), !0).forEach(function (key) { report_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : report_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function report_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }






/**
 * @description 响应结构构建，对齐temu上传结构
 */

var buildSiteResult = function buildSiteResult(site, reportRes, task) {
  return report_objectSpread(report_objectSpread({
    site_key: site.site_key,
    site_name: site.site_name,
    code: reportRes ? reportRes.code : 1,
    msg: reportRes ? reportRes.msg : '未知错误'
  }, reportRes && reportRes.result ? reportRes.result : {}), {}, {
    report_type: getReportType(site.site_key) || '',
    reportType: getReportType(site.site_key) || ''
  });
};

var getReportType = function getReportType(siteKey) {
  switch (siteKey) {
    case 'MLM-remote':
      return 701;

    case 'MLM-fulfillment':
      return 702;

    case 'MLB-remote':
      return 703;

    case 'MLC-remote':
      return 704;

    case 'MLC-fulfillment':
      return 705;

    case 'MCO-remote':
      return 706;

    case 'MLA-remote':
      return 707;

    case 'MLU-remote':
      return 708;

    case 'LOCAL':
    default:
      return 7;
  }
};
/**
 * @description 处理单个站点报表获取，并构建响应结构
 * @param {Object} task 任务对象
 * @param {Object} site 站点对象
 * @param {Object} res 响应对象
 * @param {Object} taskMap 任务映射对象
 * @param {boolean} shouldChangeCookie 是否需要切换站点cookie（仅跨境需要切换）
 */


var handleSingleSiteReport = /*#__PURE__*/function () {
  var _ref = report_asyncToGenerator( /*#__PURE__*/report_regeneratorRuntime().mark(function _callee(task, site, res, taskMap, shouldChangeCookie) {
    var findIndex, newTask, changed, msg, _siteResult, reportRes, siteResult;

    return report_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            findIndex = res.result.findIndex(function (item) {
              return item.site_key === site.site_key;
            });

            if (!(findIndex !== -1 && res.result[findIndex].code === 0)) {
              _context.next = 3;
              break;
            }

            return _context.abrupt("return");

          case 3:
            log["a" /* default */].setLog("\u5F00\u59CB\u5904\u7406\u7AD9\u70B9\uFF1A".concat(site.site_name, " (").concat(site.site_key, ")"));
            newTask = report_objectSpread({}, task);
            taskMap[site.site_key] = newTask;

            if (!shouldChangeCookie) {
              _context.next = 19;
              break;
            }

            _context.next = 9;
            return changeMercadoSite(site, task.host);

          case 9:
            changed = _context.sent;

            if (changed) {
              _context.next = 17;
              break;
            }

            msg = "\u5207\u6362\u7AD9\u70B9".concat(site.site_name, "(").concat(site.site_key, ")cookie\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7AD9\u70B9\u4FE1\u606F");
            newTask.status = 3;
            newTask.msg = msg;
            _siteResult = {
              site_key: site.site_key,
              site_name: site.site_name,
              code: 1,
              msg: msg
            };

            if (findIndex !== -1) {
              res.result[findIndex] = _siteResult;
            } else {
              res.result.push(_siteResult);
            }

            return _context.abrupt("return");

          case 17:
            _context.next = 19;
            return Object(util["h" /* delayed */])(5000);

          case 19:
            task.currentSite = site;
            newTask.currentSite = site; // newTask.platform_store_id = site.site_user_id

            newTask.status = 0;
            newTask.msg = '';
            newTask.downloadId = null;
            newTask.fileUrl = null;
            _context.next = 27;
            return report_getPagoReport(newTask);

          case 27:
            reportRes = _context.sent;
            siteResult = buildSiteResult(site, reportRes, newTask);

            if (findIndex !== -1) {
              res.result[findIndex] = siteResult;
            } else {
              res.result.push(siteResult);
            }

          case 30:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function handleSingleSiteReport(_x, _x2, _x3, _x4, _x5) {
    return _ref.apply(this, arguments);
  };
}(); // mercado pago 报表入口


var getMercadoReportEntry = /*#__PURE__*/function () {
  var _ref2 = report_asyncToGenerator( /*#__PURE__*/report_regeneratorRuntime().mark(function _callee2(task) {
    var res, taskMap, currentSites, siteKey, localSite, sites, _iterator, _step, site, siteKeys, index, errRes, errTask;

    return report_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            res = task.resCache ? task.resCache : {
              code: 0,
              msg: '',
              result: []
            };
            taskMap = {};
            task.currentSite = {};
            currentSites = [];
            _context2.prev = 4;

            if (!(task.store_type !== 'GLOBAL')) {
              _context2.next = 13;
              break;
            }

            // 本土
            siteKey = task.area || 'LOCAL';
            localSite = {
              site_key: siteKey,
              site_name: siteKey
            };
            currentSites = [localSite];
            _context2.next = 11;
            return handleSingleSiteReport(task, localSite, res, taskMap, false);

          case 11:
            _context2.next = 37;
            break;

          case 13:
            // 跨境
            sites = mercado["c" /* mercado */].cbSiteInfo || [];

            if (!(sites.length === 0)) {
              _context2.next = 19;
              break;
            }

            task.status = 3;
            task.msg = '未找到站点信息，可能登录已过期，请重新登录';
            log["a" /* default */].setLog("".concat(task.msg, "\uFF0C\u65E0\u6CD5\u6267\u884C\u4EFB\u52A1"));
            return _context2.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 19:
            currentSites = sites;
            _iterator = report_createForOfIteratorHelper(sites);
            _context2.prev = 21;

            _iterator.s();

          case 23:
            if ((_step = _iterator.n()).done) {
              _context2.next = 29;
              break;
            }

            site = _step.value;
            _context2.next = 27;
            return handleSingleSiteReport(task, site, res, taskMap, true);

          case 27:
            _context2.next = 23;
            break;

          case 29:
            _context2.next = 34;
            break;

          case 31:
            _context2.prev = 31;
            _context2.t0 = _context2["catch"](21);

            _iterator.e(_context2.t0);

          case 34:
            _context2.prev = 34;

            _iterator.f();

            return _context2.finish(34);

          case 37:
            _context2.prev = 37;
            task.currentSite = null; // 清除站点 Cookie 覆盖规则，恢复客户浏览器正常的站点切换能力

            _context2.next = 41;
            return clearMercadoSiteCookie();

          case 41:
            return _context2.finish(37);

          case 42:
            // resCache 里可能混有历史失败站点（比如上次跨境任务失败的某个站点），而本次任务可能是本土或站点集合不同;
            // 只在本次站点集合里找失败,避免旧缓存干扰当前任务;
            siteKeys = new Set(currentSites.map(function (site) {
              return site.site_key;
            }));
            index = res.result.findIndex(function (_ref3) {
              var code = _ref3.code,
                  site_key = _ref3.site_key;
              return siteKeys.has(site_key) && code !== 0;
            });

            if (index !== -1) {
              errRes = res.result[index];
              errTask = taskMap[errRes.site_key] || task;
              res.msg = errRes.msg;
              res.code = errRes.code;
              task.status = errTask.status;
              task.msg = errRes.msg;
              task.error_time = errTask.error_time; // 缓存获取成功的站点报表

              task.resCache = res;
            } else {
              res.code = 0;
              res.msg = '';
            }

            return _context2.abrupt("return", {
              code: res.code,
              msg: res.code === 0 ? '获取Mercado Pago Report完成' : res.msg,
              type_id: task.type_id,
              platform_store_id: task.platform_store_id,
              result: res.result
            });

          case 46:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[4,, 37, 42], [21, 31, 34, 37]]);
  }));

  return function getMercadoReportEntry(_x6) {
    return _ref2.apply(this, arguments);
  };
}();

/* harmony default export */ var report = (getMercadoReportEntry);
// CONCATENATED MODULE: ./src/platform/tiktok/core/getCompassReport.js
function getCompassReport_typeof(obj) { "@babel/helpers - typeof"; return getCompassReport_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; }, getCompassReport_typeof(obj); }

function getCompassReport_toConsumableArray(arr) { return getCompassReport_arrayWithoutHoles(arr) || getCompassReport_iterableToArray(arr) || getCompassReport_unsupportedIterableToArray(arr) || getCompassReport_nonIterableSpread(); }

function getCompassReport_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function getCompassReport_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return getCompassReport_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 getCompassReport_arrayLikeToArray(o, minLen); }

function getCompassReport_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function getCompassReport_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return getCompassReport_arrayLikeToArray(arr); }

function getCompassReport_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; }

function getCompassReport_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function getCompassReport_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? getCompassReport_ownKeys(Object(source), !0).forEach(function (key) { getCompassReport_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : getCompassReport_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function getCompassReport_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function getCompassReport_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ getCompassReport_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" == getCompassReport_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 getCompassReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function getCompassReport_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { getCompassReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { getCompassReport_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }




 // 任务类型配置

var REPORT_CONFIG = {
  30002: {
    module_type: 103,
    detail_list_type: 1,
    list_params_key: 'creator_list_params',
    detail_list_key: 'creator_list_segments',
    data_key: 'creator_performances',
    metric_types: [2, 3, 5, 6, 7, 10, 11, 8, 9, 4, 12],
    name: '达人'
  },
  30006: {
    module_type: 104,
    detail_list_type: 2,
    list_params_key: 'product_list_params',
    detail_list_key: 'product_list_segments',
    data_key: 'product_performances',
    metric_types: [1, 2, 3, 4, 9, 10, 7, 8, 12, 11, 13, 14, 5, 6],
    name: '商品'
  }
};
/**
 * 获取可用时间范围
 * @param {object} task - 任务对象
 * @returns {Promise<object>} { code, startTime, endTime, timezone_offset }
 */

var getAvailableDate = /*#__PURE__*/function () {
  var _ref = getCompassReport_asyncToGenerator( /*#__PURE__*/getCompassReport_regeneratorRuntime().mark(function _callee(task, module_type) {
    var retry,
        query,
        _yield$tkPost,
        code,
        data,
        message,
        available_time_range_list,
        _available_time_range,
        start_time,
        end_time,
        timezone_offset,
        msg,
        _msg,
        _args = arguments;

    return getCompassReport_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            retry = _args.length > 2 && _args[2] !== undefined ? _args[2] : 0;
            _context.prev = 1;
            _context.next = 4;
            return Object(utils["a" /* getQueryString */])(task);

          case 4:
            query = _context.sent;

            if (query) {
              _context.next = 7;
              break;
            }

            return _context.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 7:
            _context.next = 9;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/compass/available_date/get"), query, {
              module_types: [105, 104, 106, 103]
            });

          case 9:
            _yield$tkPost = _context.sent;
            code = _yield$tkPost.code;
            data = _yield$tkPost.data;
            message = _yield$tkPost.message;

            if (!(code === 0 && data)) {
              _context.next = 20;
              break;
            }

            available_time_range_list = data.available_time_range_list;
            _available_time_range = available_time_range_list.find(function (item) {
              return item.module_type === module_type;
            }), start_time = _available_time_range.start_time, end_time = _available_time_range.end_time, timezone_offset = _available_time_range.timezone_offset;
            log["a" /* default */].setLog("\u83B7\u53D6\u53EF\u7528\u65F6\u95F4\u8303\u56F4\u6210\u529F-----\u5F00\u59CB\u65F6\u95F4\uFF1A".concat(start_time, "\uFF0C\u7ED3\u675F\u65F6\u95F4\uFF1A").concat(end_time, "\uFF0C\u65F6\u533A\u504F\u79FB\uFF1A").concat(timezone_offset));
            return _context.abrupt("return", {
              code: 0,
              startTime: start_time,
              endTime: end_time,
              timezone_offset: timezone_offset
            });

          case 20:
            msg = "\u83B7\u53D6\u53EF\u7528\u65F6\u95F4\u8303\u56F4\u5931\u8D25-----".concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 24:
            _context.next = 37;
            break;

          case 26:
            _context.prev = 26;
            _context.t0 = _context["catch"](1);
            _msg = "\u83B7\u53D6\u53EF\u7528\u65F6\u95F4\u8303\u56F4\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A".concat(Object(util["u" /* isError */])(_context.t0));
            log["a" /* default */].setLog(_msg);
            task.msg = _msg; // 重试3次

            if (!(retry < 3)) {
              _context.next = 36;
              break;
            }

            log["a" /* default */].setLog('正在重试........................');
            _context.next = 35;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 35:
            return _context.abrupt("return", getAvailableDate(task, module_type, ++retry));

          case 36:
            return _context.abrupt("return", {
              code: 2,
              msg: _msg
            });

          case 37:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[1, 26]]);
  }));

  return function getAvailableDate(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();
/**
 * 生成时间段参数数组
 * @param {number} startTime - 开始时间戳（秒）
 * @param {number} endTime - 结束时间戳（秒）
 * @param {number} timezone_offset - 时区偏移（秒）
 * @param {number} metric_types
 * @returns {Array} 时间段配置数组
 */


var getCompassReport_generateTimeRanges = function generateTimeRanges(_ref2) {
  var startTime = _ref2.startTime,
      endTime = _ref2.endTime,
      timezone_offset = _ref2.timezone_offset,
      metric_types = _ref2.metric_types;
  var timeRanges = [];
  var oneDaySeconds = 86400; // 一天的秒数
  // 从开始时间到结束时间，每天生成一个时间段
  // 这里获取到的startTime - endTime是九十天的范围，但是tk貌似最大只支持30个间隔，所以这里直接改成获取近30天的

  var currentStart = endTime - oneDaySeconds * 30;

  while (currentStart < endTime) {
    var currentEnd = Math.min(currentStart + oneDaySeconds, endTime);
    timeRanges.push({
      time_descriptor: {
        granularity_type: 1,
        timezone_offset: timezone_offset,
        start_time: currentStart,
        end_time: currentEnd
      },
      metric_types: metric_types,
      page_param: {
        page_no: 1,
        page_size: 200
      },
      sorter: {
        sort_type: 2,
        order_type: 1
      },
      filter: {},
      currentPage: 1 // 新增：记录当前时间段的页码

    });
    currentStart = currentEnd;
  }

  log["a" /* default */].setLog("\u751F\u6210\u65F6\u95F4\u6BB5\u53C2\u6570-----\u5171".concat(timeRanges.length, "\u4E2A\u65F6\u95F4\u6BB5"));
  return timeRanges;
};
/**
 * 批量获取报告数据（每次请求最多 2 个时间段）
 * @param {object} task - 任务对象
 * @param {Array} timeRanges - 时间段参数数组（最多2个）
 * @param {object} config - 报告配置
 * @param {number} retry - 重试次数
 * @returns {Promise<object>} { code, data, pendingRanges }
 */


var fetchReport = /*#__PURE__*/function () {
  var _ref4 = getCompassReport_asyncToGenerator( /*#__PURE__*/getCompassReport_regeneratorRuntime().mark(function _callee2(_ref3) {
    var task, timeRanges, config, _ref3$retry, retry, query, params, _yield$tkPost2, code, data, message, detailList, pendingRanges, msg, _msg2;

    return getCompassReport_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            task = _ref3.task, timeRanges = _ref3.timeRanges, config = _ref3.config, _ref3$retry = _ref3.retry, retry = _ref3$retry === void 0 ? 0 : _ref3$retry;
            _context2.prev = 1;
            _context2.next = 4;
            return Object(utils["a" /* getQueryString */])(task);

          case 4:
            query = _context2.sent;

            if (query) {
              _context2.next = 7;
              break;
            }

            return _context2.abrupt("return", {
              code: 1,
              msg: task.msg
            });

          case 7:
            params = {
              params: getCompassReport_defineProperty({
                detail_list_type: config.detail_list_type
              }, config.list_params_key, timeRanges)
            };
            _context2.next = 10;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/oec/affiliate/compass/transaction/detail_list/get"), query, params);

          case 10:
            _yield$tkPost2 = _context2.sent;
            code = _yield$tkPost2.code;
            data = _yield$tkPost2.data;
            message = _yield$tkPost2.message;

            if (!(code === 0 && data)) {
              _context2.next = 22;
              break;
            }

            detailList = data[config.detail_list_key] || []; // 分析哪些时间段还有更多数据（返回数据达到200条的时间段）

            pendingRanges = [];
            detailList.forEach(function (item, index) {
              var total = item.total,
                  _item$config$data_key = item[config.data_key],
                  data = _item$config$data_key === void 0 ? [] : _item$config$data_key;
              var currentPage = timeRanges[index].page_param.page_no; // 如果某个时间段的数据达到200条，且未达到总数，说明还有下一页

              if (data.length >= 200 && currentPage * 200 < total) {
                pendingRanges.push(index);
              }
            });
            log["a" /* default */].setLog("\u83B7\u53D6".concat(config.name, "\u62A5\u544A\u6210\u529F-----\u672C\u6279\u6B21").concat((detailList === null || detailList === void 0 ? void 0 : detailList.length) || 0, "\u4E2A\u65F6\u95F4\u6BB5\uFF0C\u5176\u4E2D").concat((pendingRanges === null || pendingRanges === void 0 ? void 0 : pendingRanges.length) || 0, "\u4E2A\u9700\u8981\u7EE7\u7EED\u83B7\u53D6\u4E0B\u4E00\u9875"));
            return _context2.abrupt("return", {
              code: 0,
              data: detailList,
              pendingRanges: pendingRanges
            });

          case 22:
            msg = "\u83B7\u53D6".concat(config.name, "\u62A5\u544A\u5931\u8D25-----").concat(message);
            log["a" /* default */].setLog(msg);
            task.msg = msg;
            return _context2.abrupt("return", {
              code: 1,
              msg: msg
            });

          case 26:
            _context2.next = 40;
            break;

          case 28:
            _context2.prev = 28;
            _context2.t0 = _context2["catch"](1);
            _msg2 = "\u83B7\u53D6".concat(config.name, "\u62A5\u544A\u5931\u8D25-----\u539F\u751F\u63A5\u53E3\u8FD4\u56DE\uFF1A").concat(Object(util["u" /* isError */])(_context2.t0));
            log["a" /* default */].setLog(_msg2);
            task.msg = _msg2; // 重试2次

            if (!(retry < 2)) {
              _context2.next = 38;
              break;
            }

            log["a" /* default */].setLog("\u6B63\u5728\u91CD\u8BD5\u7B2C ".concat(retry + 1, "/2 \u6B21........................"));
            _context2.next = 37;
            return Object(util["h" /* delayed */])(3 * 1000);

          case 37:
            return _context2.abrupt("return", fetchReport({
              task: task,
              timeRanges: timeRanges,
              config: config,
              retry: ++retry
            }));

          case 38:
            // 重试2次后仍失败，返回失败状态
            log["a" /* default */].setLog("\u91CD\u8BD52\u6B21\u540E\u4ECD\u5931\u8D25\uFF0C\u653E\u5F03\u5F53\u524D\u6279\u6B21");
            return _context2.abrupt("return", {
              code: 2,
              msg: _msg2
            });

          case 40:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[1, 28]]);
  }));

  return function fetchReport(_x3) {
    return _ref4.apply(this, arguments);
  };
}();
/**
 * 主流程：获取报告（达人或商品）
 * @param {object} task - 任务对象
 * @returns {Promise<object>} { code, msg, result }
 */


var getCompassReport = /*#__PURE__*/function () {
  var _ref5 = getCompassReport_asyncToGenerator( /*#__PURE__*/getCompassReport_regeneratorRuntime().mark(function _callee4(task) {
    var _ret, msg;

    return getCompassReport_regeneratorRuntime().wrap(function _callee4$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;
            return _context6.delegateYield( /*#__PURE__*/getCompassReport_regeneratorRuntime().mark(function _callee3() {
              var _task$resCache;

              var config, msg, _ref6, timeRangesConfig, pendingIndexes, _ref6$failedIndexes, failedIndexes, _yield$getAvailableDa, code, startTime, endTime, timezone_offset, BATCH_SIZE, _loop;

              return getCompassReport_regeneratorRuntime().wrap(function _callee3$(_context5) {
                while (1) {
                  switch (_context5.prev = _context5.next) {
                    case 0:
                      // 根据 type_id 获取配置
                      config = REPORT_CONFIG[task.type_id];

                      if (config) {
                        _context5.next = 6;
                        break;
                      }

                      msg = "\u4E0D\u652F\u6301\u7684\u4EFB\u52A1\u7C7B\u578B\uFF1A".concat(task.type_id);
                      log["a" /* default */].setLog(msg);
                      task.status = 14;
                      return _context5.abrupt("return", {
                        v: {
                          code: 1,
                          msg: msg
                        }
                      });

                    case 6:
                      // 1. 检查是否有缓存（断点续传）
                      _ref6 = ((_task$resCache = task.resCache) === null || _task$resCache === void 0 ? void 0 : _task$resCache.data) || {}, timeRangesConfig = _ref6.timeRangesConfig, pendingIndexes = _ref6.pendingIndexes, _ref6$failedIndexes = _ref6.failedIndexes, failedIndexes = _ref6$failedIndexes === void 0 ? [] : _ref6$failedIndexes; // 2. 如果没有缓存，获取可用时间范围并生成时间段参数

                      if (timeRangesConfig) {
                        _context5.next = 21;
                        break;
                      }

                      _context5.next = 10;
                      return getAvailableDate(task, config.module_type);

                    case 10:
                      _yield$getAvailableDa = _context5.sent;
                      code = _yield$getAvailableDa.code;
                      startTime = _yield$getAvailableDa.startTime;
                      endTime = _yield$getAvailableDa.endTime;
                      timezone_offset = _yield$getAvailableDa.timezone_offset;
                      msg = _yield$getAvailableDa.msg;

                      if (!(code !== 0)) {
                        _context5.next = 19;
                        break;
                      }

                      task.status = 14;
                      return _context5.abrupt("return", {
                        v: {
                          code: code,
                          msg: msg
                        }
                      });

                    case 19:
                      // 生成所有时间段的配置（第一页）
                      timeRangesConfig = getCompassReport_generateTimeRanges({
                        startTime: startTime,
                        endTime: endTime,
                        timezone_offset: timezone_offset,
                        metric_types: config.metric_types
                      }); // 初始化：所有时间段都需要获取

                      pendingIndexes = timeRangesConfig.map(function (_, index) {
                        return index;
                      });

                    case 21:
                      BATCH_SIZE = 2; // 每批请求 2 个时间段
                      // 3. 循环获取数据，每次处理 2 个时间段

                      _loop = /*#__PURE__*/getCompassReport_regeneratorRuntime().mark(function _loop() {
                        var batches, i, newPendingIndexes, currentRoundData, _loop2, batchIdx;

                        return getCompassReport_regeneratorRuntime().wrap(function _loop$(_context4) {
                          while (1) {
                            switch (_context4.prev = _context4.next) {
                              case 0:
                                log["a" /* default */].setLog("\u5F00\u59CB\u65B0\u4E00\u8F6E\u83B7\u53D6-----\u5F85\u83B7\u53D6\u65F6\u95F4\u6BB5\uFF1A".concat(pendingIndexes.length, "\u4E2A")); // 分批处理：每次处理 2 个时间段

                                batches = [];

                                for (i = 0; i < pendingIndexes.length; i += BATCH_SIZE) {
                                  batches.push(pendingIndexes.slice(i, i + BATCH_SIZE));
                                }

                                log["a" /* default */].setLog("\u5171\u5206\u4E3A ".concat(batches.length, " \u6279\uFF0C\u6BCF\u6279\u6700\u591A ").concat(BATCH_SIZE, " \u4E2A\u65F6\u95F4\u6BB5"));
                                newPendingIndexes = []; // 下一轮需要继续处理的时间段（需要获取下一页的）

                                currentRoundData = []; // 当前轮收集的数据
                                // 逐批请求（每批2个时间段）

                                _loop2 = /*#__PURE__*/getCompassReport_regeneratorRuntime().mark(function _loop2(batchIdx) {
                                  var batchIndexes, pageInfo, currentTimeRanges, _yield$fetchReport, code, data, pendingRanges, msg;

                                  return getCompassReport_regeneratorRuntime().wrap(function _loop2$(_context3) {
                                    while (1) {
                                      switch (_context3.prev = _context3.next) {
                                        case 0:
                                          batchIndexes = batches[batchIdx]; // 获取每个时间段的页码信息

                                          pageInfo = batchIndexes.map(function (idx) {
                                            return "\u7D22\u5F15".concat(idx, ":\u7B2C").concat(timeRangesConfig[idx].currentPage, "\u9875");
                                          }).join(', ');
                                          log["a" /* default */].setLog("\u5904\u7406\u7B2C ".concat(batchIdx + 1, "/").concat(batches.length, " \u6279-----").concat(pageInfo)); // 构建当前批次的时间段配置（使用每个时间段自己的页码）

                                          currentTimeRanges = batchIndexes.map(function (index) {
                                            var range = getCompassReport_objectSpread({}, timeRangesConfig[index]);

                                            var currentPage = timeRangesConfig[index].currentPage;
                                            range.page_param = {
                                              page_no: currentPage,
                                              page_size: 200
                                            };
                                            return range;
                                          }); // 请求当前批次（fetchReport 内部会重试 2 次）

                                          _context3.next = 6;
                                          return fetchReport({
                                            task: task,
                                            timeRanges: currentTimeRanges,
                                            config: config,
                                            retry: 0
                                          });

                                        case 6:
                                          _yield$fetchReport = _context3.sent;
                                          code = _yield$fetchReport.code;
                                          data = _yield$fetchReport.data;
                                          pendingRanges = _yield$fetchReport.pendingRanges;
                                          msg = _yield$fetchReport.msg;

                                          if (code !== 0) {
                                            // 重试 2 次后仍然失败，记录失败的时间段
                                            log["a" /* default */].setLog("\u6279\u6B21\u5931\u8D25\uFF08\u5DF2\u91CD\u8BD52\u6B21\uFF09-----\u65F6\u95F4\u6BB5\u7D22\u5F15\uFF1A".concat(batchIndexes.join(','), "\uFF0C\u9519\u8BEF\uFF1A").concat(msg)); // 将失败的时间段索引记录下来

                                            batchIndexes.forEach(function (idx) {
                                              if (!failedIndexes.includes(idx)) {
                                                failedIndexes.push(idx);
                                              }
                                            });
                                          } else {
                                            // 成功，收集数据
                                            log["a" /* default */].setLog("\u6279\u6B21\u6210\u529F-----\u83B7\u53D6\u5230 ".concat((data === null || data === void 0 ? void 0 : data.length) || 0, " \u4E2A\u65F6\u95F4\u6BB5\u7684\u6570\u636E"));
                                            currentRoundData.push.apply(currentRoundData, getCompassReport_toConsumableArray(data || [])); // 检查是否有时间段需要继续获取下一页

                                            if (pendingRanges && pendingRanges.length > 0) {
                                              pendingRanges.forEach(function (i) {
                                                var index = batchIndexes[i]; // 更新该时间段的页码

                                                timeRangesConfig[index].currentPage += 1;
                                                newPendingIndexes.push(index);
                                                log["a" /* default */].setLog("\u65F6\u95F4\u6BB5".concat(index, "\u9700\u8981\u83B7\u53D6\u4E0B\u4E00\u9875\uFF08\u7B2C").concat(timeRangesConfig[index].currentPage, "\u9875\uFF09"));
                                              });
                                            }
                                          } // 批次间延迟，避免请求过快


                                          if (!(batchIdx < batches.length - 1)) {
                                            _context3.next = 15;
                                            break;
                                          }

                                          _context3.next = 15;
                                          return Object(util["h" /* delayed */])(2 * 1000);

                                        case 15:
                                        case "end":
                                          return _context3.stop();
                                      }
                                    }
                                  }, _loop2);
                                });
                                batchIdx = 0;

                              case 8:
                                if (!(batchIdx < batches.length)) {
                                  _context4.next = 13;
                                  break;
                                }

                                return _context4.delegateYield(_loop2(batchIdx), "t0", 10);

                              case 10:
                                batchIdx++;
                                _context4.next = 8;
                                break;

                              case 13:
                                if (!(currentRoundData.length > 0)) {
                                  _context4.next = 17;
                                  break;
                                }

                                log["a" /* default */].setLog("\u4E0A\u4F20\u5F53\u524D\u8F6E\u6570\u636E-----\u5171 ".concat(currentRoundData.length, " \u4E2A\u65F6\u95F4\u6BB5\u7684\u6570\u636E"));
                                _context4.next = 17;
                                return common_newTask["a" /* default */].uploadTask({
                                  code: 4,
                                  data: {
                                    timeRangesConfig: timeRangesConfig,
                                    // 包含每个时间段的 currentPage
                                    pendingIndexes: newPendingIndexes,
                                    failedIndexes: failedIndexes // 失败的时间段索引

                                  },
                                  result: {
                                    list: currentRoundData
                                  }
                                }, task);

                              case 17:
                                if (!(newPendingIndexes.length > 0)) {
                                  _context4.next = 24;
                                  break;
                                }

                                // 还有时间段需要继续获取下一页
                                log["a" /* default */].setLog("\u8FD8\u6709 ".concat(newPendingIndexes.length, " \u4E2A\u65F6\u95F4\u6BB5\u9700\u8981\u7EE7\u7EED\u83B7\u53D6\u4E0B\u4E00\u9875"));
                                pendingIndexes = newPendingIndexes;
                                _context4.next = 22;
                                return Object(util["h" /* delayed */])(2 * 1000);

                              case 22:
                                _context4.next = 25;
                                break;

                              case 24:
                                // 当前轮所有时间段都处理完毕
                                pendingIndexes = [];

                              case 25:
                              case "end":
                                return _context4.stop();
                            }
                          }
                        }, _loop);
                      });

                    case 23:
                      if (!(pendingIndexes && pendingIndexes.length > 0)) {
                        _context5.next = 27;
                        break;
                      }

                      return _context5.delegateYield(_loop(), "t0", 25);

                    case 25:
                      _context5.next = 23;
                      break;

                    case 27:
                      // 最后缓存进度（包括失败的时间段）
                      task.resCache = {
                        data: {
                          timeRangesConfig: timeRangesConfig,
                          pendingIndexes: [],
                          failedIndexes: failedIndexes
                        }
                      }; // 判断是否有失败的时间段

                      if (!(failedIndexes.length > 0)) {
                        _context5.next = 35;
                        break;
                      }

                      log["a" /* default */].setLog("".concat(config.name, "\u62A5\u544A\u83B7\u53D6\u5B8C\u6BD5-----\u5171 ").concat(timeRangesConfig.length, " \u4E2A\u65F6\u95F4\u6BB5\uFF0C\u5176\u4E2D ").concat(failedIndexes.length, " \u4E2A\u5931\u8D25"));
                      log["a" /* default */].setLog("\u5931\u8D25\u7684\u65F6\u95F4\u6BB5\u7D22\u5F15\uFF1A".concat(failedIndexes.join(',')));
                      task.status = 14;
                      return _context5.abrupt("return", {
                        v: {
                          code: 1,
                          msg: "\u83B7\u53D6".concat(config.name, "\u62A5\u544A\u90E8\u5206\u5931\u8D25\uFF0C\u5931\u8D25\u65F6\u95F4\u6BB5\uFF1A").concat(failedIndexes.join(','))
                        }
                      });

                    case 35:
                      log["a" /* default */].setLog("".concat(config.name, "\u62A5\u544A\u83B7\u53D6\u5B8C\u6BD5-----\u5171 ").concat(timeRangesConfig.length, " \u4E2A\u65F6\u95F4\u6BB5\uFF0C\u5168\u90E8\u6210\u529F"));
                      task.status = 15;
                      return _context5.abrupt("return", {
                        v: {
                          code: 0,
                          msg: "\u83B7\u53D6".concat(config.name, "\u62A5\u544A\u6210\u529F")
                        }
                      });

                    case 38:
                    case "end":
                      return _context5.stop();
                  }
                }
              }, _callee3);
            })(), "t0", 2);

          case 2:
            _ret = _context6.t0;

            if (!(getCompassReport_typeof(_ret) === "object")) {
              _context6.next = 5;
              break;
            }

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

          case 5:
            _context6.next = 14;
            break;

          case 7:
            _context6.prev = 7;
            _context6.t1 = _context6["catch"](0);
            msg = "\u83B7\u53D6\u62A5\u544A\u5F02\u5E38-----".concat(Object(util["u" /* isError */])(_context6.t1));
            log["a" /* default */].setLog(msg);
            task.status = 14;
            task.msg = msg;
            return _context6.abrupt("return", {
              code: 2,
              msg: msg
            });

          case 14:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee4, null, [[0, 7]]);
  }));

  return function getCompassReport(_x4) {
    return _ref5.apply(this, arguments);
  };
}();

/* harmony default export */ var core_getCompassReport = (getCompassReport);
// CONCATENATED MODULE: ./src/platform/common/taskType.js
function taskType_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function taskType_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? taskType_ownKeys(Object(source), !0).forEach(function (key) { taskType_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : taskType_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function taskType_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }














var cores = {
  getSupplierPrice: temu_getSupplierPrice,
  getSaleVolume: temu_getSaleVolume,
  getQtReport: qtReport,
  getTodaySaleVolume: temu_getTodaySaleVolume,
  getActivityPrice: temu_getActivityPrice,
  getGoodsTraffic: temu_getGoodsTraffic,
  getStorageServiceFee: temu_getStorageServiceFee,
  getTargetInvitation: getTargetInvitation,
  getTargetInvitationDetail: getTargetInvitationDetail,
  createTargetInvitation: createTargetInvitation,
  updateTargetInvitation: updateTargetInvitation,
  getCreators: getCreators,
  getMercadoReportEntry: report,
  getCompassReport: core_getCompassReport
}; // temu任务类型

var temuTaskType = {
  // temum半托
  22003: {
    name: '财务/账务明细-半托',
    type: 'temuReport',
    platform_code: 10024,
    handle: 'getQtReport',
    component: 'SaleVolume'
  },
  22005: {
    name: '发货面单费-半托',
    type: 'temuReport',
    platform_code: 10024,
    handle: 'getQtReport',
    component: 'SaleVolume'
  },
  22004: {
    name: '退货面单费-半托',
    type: 'temuReport',
    platform_code: 10024,
    handle: 'getQtReport',
    component: 'ReverseReport'
  },
  22002: {
    name: '最新供货价-半托',
    type: 'supplierPrice',
    platform_code: 10022,
    handle: 'getSupplierPrice',
    component: 'SupplierPrice'
  },
  22008: {
    name: '活动价-半托',
    type: 'activityPrice',
    platform_code: 10022,
    handle: 'getActivityPrice',
    component: 'SaleVolume'
  },
  22017: {
    name: '流量分析-半托',
    type: 'goodsTraffic',
    platform_code: 10022,
    handle: 'getGoodsTraffic',
    component: 'SaleVolume'
  },
  // temu全托
  22006: {
    name: '财务/账务明细-全托',
    type: 'temuReport',
    platform_code: 10024,
    handle: 'getQtReport',
    component: 'SaleVolume'
  },
  22015: {
    name: '支出详情-全托',
    type: 'temuReport',
    platform_code: 10024,
    handle: 'getQtReport',
    component: 'SaleVolume'
  },
  22009: {
    name: 'ERP费用-全托',
    type: 'temuReport',
    platform_code: 10024,
    handle: 'getQtReport',
    component: 'SaleVolume'
  },
  22001: {
    name: '近30天销量-全托',
    type: 'sale',
    platform_code: 10022,
    handle: 'getSaleVolume',
    component: 'SaleVolume'
  },
  22010: {
    name: '最新供货价-全托',
    type: 'supplierPrice',
    platform_code: 10022,
    handle: 'getSupplierPrice',
    component: 'SupplierPrice'
  },
  22016: {
    name: '活动价-全托',
    type: 'activityPrice',
    platform_code: 10022,
    handle: 'getActivityPrice',
    component: 'SaleVolume'
  },
  22020: {
    name: '仓储综合服务费-全托',
    type: 'storageServiceFee',
    platform_code: 10022,
    handle: 'getStorageServiceFee',
    component: 'SaleVolume'
  },
  //temu本土
  22011: {
    name: '最新供货价-本土',
    type: 'supplierPrice',
    platform_code: 10022,
    handle: 'getSupplierPrice',
    component: 'SupplierPrice'
  },
  // temu半托po明细
  22018: {
    name: 'PO明细-本土',
    type: 'temuReport',
    platform_code: 10022,
    handle: 'getQtReport',
    component: 'SaleVolume'
  },
  22019: {
    name: 'Temu本土付款报告',
    type: 'temuReport',
    platform_code: 10022,
    handle: 'getQtReport',
    component: 'SaleVolume'
  }
}; // tiktok任务类型

var tiktokTaskType = {
  30001: {
    name: '获取定向邀约-半托',
    type: 'tiktokCreator',
    platform_code: 10011,
    handle: 'getTargetInvitation'
  },
  30002: {
    name: '获取达人报告-半托',
    type: 'tiktokCompassReport',
    platform_code: 10011,
    handle: 'getCompassReport'
  },
  30003: {
    name: '创建定向邀约-半托',
    type: 'tiktokCreator',
    platform_code: 10011,
    handle: 'createTargetInvitation'
  },
  30004: {
    name: '更新定向邀约-半托',
    type: 'tiktokCreator',
    platform_code: 10011,
    handle: 'updateTargetInvitation'
  },
  30005: {
    name: '查询可邀约达人-半托',
    type: 'tiktokCreator',
    platform_code: 10011,
    handle: 'getCreators'
  },
  30006: {
    name: '获取商品报告-半托',
    type: 'tiktokCompassReport',
    platform_code: 10011,
    handle: 'getCompassReport'
  },
  30007: {
    name: '单个获取定向邀约-半托',
    type: 'tiktokCreator',
    platform_code: 10011,
    handle: 'getTargetInvitationDetail'
  }
}; // mercado跨境

var mercadoTaskType = {
  40001: {
    name: '财务/账务明细-跨境',
    type: 'mercadoReport',
    platform_code: 10012,
    handle: 'getMercadoReportEntry',
    component: 'SaleVolume'
  },
  40002: {
    name: '财务/账务明细-本土',
    type: 'mercadoReport',
    platform_code: 10012,
    handle: 'getMercadoReportEntry',
    component: 'SaleVolume'
  }
};
var multiTskHandleMap = taskType_objectSpread(taskType_objectSpread(taskType_objectSpread({}, temuTaskType), tiktokTaskType), mercadoTaskType);

/***/ }),

/***/ "5e61":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("c1df");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("ca00");
/* harmony import */ var _data_log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("6b23");
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("db49");
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__("a1d0");
/* harmony import */ var _taskType__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__("2f79");
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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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







/**
 * 重构后的多平台任务管理类
 * 采用扁平化数据结构，以 platform_store_id+report_date_month 作为分组key
 */

var MultiPlatformTaskV2 = /*#__PURE__*/function () {
  function MultiPlatformTaskV2() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        sleepTime = _ref.sleepTime;

    _classCallCheck(this, MultiPlatformTaskV2);

    // 任务类型相关
    this.taskTypeTotal = 0; // 扁平化任务分组 - 核心数据结构

    this.taskGroups = {}; // 执行顺序管理

    this.orderedKeys = []; // 指针式调度核心

    this.currentGroupPointer = null; // 当前执行的分组key

    this.currentTaskPointer = 0; // 当前分组内的任务索引

    this.isExecuting = false; // 是否正在执行任务

    this.currentRunningTaskId = null; // 当前正在执行的任务ID
    // 任务状态

    this.taskStatus = 'idle'; // repeat任务缓存（不受月份分组影响）

    this.repeatMap = {}; // 轮次执行跟踪器

    this.executionRound = 1;
    this.roundExecutionRecord = {}; // 记录每个分组在当前轮次的执行状态
    // 重试定时器

    this.retryTimerName = null;
    this.nextRetryAt = null; // 重试配置

    this.retryConfig = {
      noRetryTypes: [30005],
      // 不需要重试的任务类型（如重复任务）,30005即时性要求高，失败就不要重试了
      maxRetryCount: _config__WEBPACK_IMPORTED_MODULE_3__[/* TEMU_MAX_RETRY_COUNT */ "d"],
      // 最大延迟时间是2的12次方秒，即4096秒，约1小时15分钟
      retryInterval: function retryInterval(errorTime) {
        return Math.min(Math.pow(2, errorTime) * 1000, Math.pow(2, 12) * 1000);
      }
    }; // 配置参数

    this.notCoverTypes = [22002, 22001, 22010, 22011, 22008, 22016, 30003, 30004, 30005, 30007]; // 不需要覆盖的任务类型

    this.runningNotCoverTypes = [22017]; // 正在执行的不需要覆盖的任务类型

    this.sleepTime = sleepTime || 3000; // 1-3s

    this.taskTimeout = 20 * 60 * 1000;
    this.force = false; // 初始化

    this.getTaskList();
  }
  /**
   * @description 获取任务列表
   * @param {boolean} force 是否强制获取
   */


  _createClass(MultiPlatformTaskV2, [{
    key: "getTaskList",
    value: function () {
      var _getTaskList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(force) {
        var storeIdsSet, storeIdMap, res;
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                // 兼容 mallId/uniqueId：以 storeInfo 为基准，追加映射值后去重
                storeIdsSet = new Set(_index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].storeInfo || []);
                storeIdMap = _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].storeIdMap || {};
                (_index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].storeInfo || []).forEach(function (id) {
                  var mapped = storeIdMap[id];
                  if (mapped) storeIdsSet.add(mapped);
                });
                _context.next = 5;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* gatePost */ "m"])('api/mp/getTask', {
                  platform_code: _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].platformCode,
                  platform_store_ids: _toConsumableArray(storeIdsSet),
                  force: force
                }, 'task').catch(function (e) {
                  _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('获取任务列表失败----', Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(e));
                });

              case 5:
                res = _context.sent;

                if (res && res.code === 0) {
                  this.initTaskList(res.data, force);
                }

              case 7:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function getTaskList(_x) {
        return _getTaskList.apply(this, arguments);
      }

      return getTaskList;
    }()
    /**
     * @description 任务数据初始化
     * @param {Object} item 任务项
     * @returns {Object} 初始化后的任务
     */

  }, {
    key: "initTask",
    value: function initTask(item) {
      var data = _typeof(item.data) === 'object' ? item.data : JSON.parse(item.data);
      return _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, item), item.store_info || {}), data || {}), {}, {
        status: 0,
        error_time: 0,
        hide: false,
        isDelete: false,
        isInit: true,
        endTime: null,
        isRetryable: !this.retryConfig.noRetryTypes.includes(+item.type_id)
      });
    }
    /**
     * @description 检查任务是否可执行（基础条件检查）
     * @param {Object} task 任务对象
     * @returns {boolean} 是否可执行
     */

  }, {
    key: "isTaskExecutable",
    value: function isTaskExecutable(task) {
      if (!task) return false;
      if (task.isDelete) return false;
      if (task.status === 1) return false;
      if (task.error_time >= this.retryConfig.maxRetryCount) return false;
      if (!this.shouldRetryNow(task)) return false;
      return true;
    }
    /**
     * @description 弹窗重新获取触发回调，将错误次数大于等于9的任务重置为0
     */

  }, {
    key: "handleReGet",
    value: function handleReGet() {
      var _loop = function _loop() {
        var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
            groupKey = _Object$entries$_i[0],
            group = _Object$entries$_i[1];

        if (group.tasks && group.tasks.length) {
          group.tasks.forEach(function (task) {
            if (task.error_time >= 10) {
              task.error_time = 0;
              _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u91CD\u7F6E\u4EFB\u52A1\u9519\u8BEF\u6B21\u6570\uFF1AtaskId-".concat(task.task_id, "\uFF0C\u6240\u5728\u5206\u7EC4\uFF1A").concat(groupKey));
            }
          });
        }
      };

      for (var _i = 0, _Object$entries = Object.entries(this.taskGroups); _i < _Object$entries.length; _i++) {
        _loop();
      }

      this.taskSchedule();
    }
    /**
     * @description 检查是否应该重试
     * @param {Object} task 任务对象
     * @returns {boolean} 是否应该重试
     */

  }, {
    key: "shouldRetryNow",
    value: function shouldRetryNow(task) {
      if (!task.isRetryable && task.error_time > 0) return false;
      if (!task.endTime || task.error_time === 0) return true;
      var nextRetryTime = task.endTime + this.retryConfig.retryInterval(task.error_time);
      return Date.now() >= nextRetryTime;
    }
    /**
     * @description 判断任务是否属于重试候选
     */

  }, {
    key: "isRetryCandidate",
    value: function isRetryCandidate(task) {
      if (!task) return false;
      if (task.repeat > 0) return false; // 重复任务不走重试定时器

      if (!task.isRetryable && task.error_time > 0) return false;
      if (task.isDelete || task.status === 1) return false;
      if (typeof task.endTime !== 'number') return false;
      if (task.error_time <= 0 || task.error_time >= this.retryConfig.maxRetryCount) return false; // 仅考虑未来时间点的重试

      var next = this.getTaskNextRetryTime(task);
      return typeof next === 'number' && next > Date.now();
    }
    /**
     * @description 计算任务下一次重试时间戳
     */

  }, {
    key: "getTaskNextRetryTime",
    value: function getTaskNextRetryTime(task) {
      var interval = this.retryConfig.retryInterval(task.error_time);
      return task.endTime + interval;
    }
    /**
     * @description 汇总所有任务，返回最近的下一次重试时间戳
     */

  }, {
    key: "computeNextRetryAt",
    value: function computeNextRetryAt() {
      var minTs = null;

      for (var _i2 = 0, _Object$values = Object.values(this.taskGroups); _i2 < _Object$values.length; _i2++) {
        var group = _Object$values[_i2];
        if (!group || !group.tasks || group.tasks.length === 0) continue;

        var _iterator = _createForOfIteratorHelper(group.tasks),
            _step;

        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var task = _step.value;
            if (!this.isRetryCandidate(task)) continue;
            var ts = this.getTaskNextRetryTime(task);

            if (minTs === null || ts < minTs) {
              minTs = ts;
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }

      return minTs;
    }
    /**
     * @description 清除重试定时器
     */

  }, {
    key: "clearRetryTimer",
    value: function clearRetryTimer() {
      if (this.retryTimerName) {
        chrome.alarms.clear(this.retryTimerName);
        this.retryTimerName = null;
        this.nextRetryAt = null;
        _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('已清除重试定时器');
      }
    }
    /**
     * @description 设置重试定时器（当当前无可执行任务时）
     */

  }, {
    key: "scheduleRetryTimer",
    value: function () {
      var _scheduleRetryTimer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
        var _this = this;

        var ts, delay, timerName;
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return this.discontinue();

              case 2:
                if (!_context3.sent) {
                  _context3.next = 5;
                  break;
                }

                this.clearRetryTimer();
                return _context3.abrupt("return");

              case 5:
                ts = this.computeNextRetryAt();

                if (ts) {
                  _context3.next = 9;
                  break;
                }

                this.clearRetryTimer();
                return _context3.abrupt("return");

              case 9:
                if (!(this.retryTimerName && this.nextRetryAt === ts)) {
                  _context3.next = 11;
                  break;
                }

                return _context3.abrupt("return");

              case 11:
                this.clearRetryTimer();
                delay = Math.max(0, ts - Date.now());
                this.nextRetryAt = ts;
                timerName = "retryTimer";
                this.retryTimerName = timerName;
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u8BBE\u7F6E\u91CD\u8BD5\u5B9A\u65F6\u5668\uFF0C".concat(Math.ceil(delay / 1000), "s \u540E\u89E6\u53D1")); // 设置定时器回调

                _utils_util__WEBPACK_IMPORTED_MODULE_1__[/* alarms */ "b"].setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
                  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                    while (1) {
                      switch (_context2.prev = _context2.next) {
                        case 0:
                          _this.retryTimerName = null;
                          _this.nextRetryAt = null; // 回调时再次校验状态

                          _context2.next = 4;
                          return _this.discontinue();

                        case 4:
                          if (!_context2.sent) {
                            _context2.next = 6;
                            break;
                          }

                          return _context2.abrupt("return");

                        case 6:
                          // 执行一次调度（此时应有任务达到重试时间）
                          _this.taskSchedule();

                        case 7:
                        case "end":
                          return _context2.stop();
                      }
                    }
                  }, _callee2);
                })), timerName, delay);

              case 18:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this);
      }));

      function scheduleRetryTimer() {
        return _scheduleRetryTimer.apply(this, arguments);
      }

      return scheduleRetryTimer;
    }()
    /**
     * @description 初始化分组的轮次执行记录
     * @param {string} groupKey 分组key
     */

  }, {
    key: "initGroupRoundRecord",
    value: function initGroupRoundRecord(groupKey) {
      if (!this.roundExecutionRecord[groupKey]) {
        this.roundExecutionRecord[groupKey] = {
          currentRound: this.executionRound,
          executedTaskIds: new Set(),
          // 本轮已执行过的任务ID
          allTasksTriedInRound: false // 本轮是否所有任务都已尝试

        };
      }
    }
    /**
     * @description 标记任务在当前轮次已执行
     * @param {string} groupKey 分组key
     * @param {string} taskId 任务ID
     */

  }, {
    key: "markTaskExecutedInRound",
    value: function markTaskExecutedInRound(groupKey, taskId) {
      this.initGroupRoundRecord(groupKey);
      this.roundExecutionRecord[groupKey].executedTaskIds.add(taskId);
    }
    /**
     * @description 检查任务在当前轮次是否已执行过
     * @param {string} groupKey 分组key
     * @param {string} taskId 任务ID
     * @returns {boolean} 是否已执行过
     */

  }, {
    key: "isTaskExecutedInCurrentRound",
    value: function isTaskExecutedInCurrentRound(groupKey, taskId) {
      var record = this.roundExecutionRecord[groupKey];
      return record && record.executedTaskIds.has(taskId);
    }
    /**
     * @description 检查分组在当前轮次是否已完成
     * @param {string} groupKey 分组key
     * @returns {boolean} 是否已完成当前轮次
     */

  }, {
    key: "isGroupRoundComplete",
    value: function isGroupRoundComplete(groupKey) {
      var _this2 = this;

      var group = this.taskGroups[groupKey];
      if (!group || !group.tasks) return true;
      this.initGroupRoundRecord(groupKey);
      var record = this.roundExecutionRecord[groupKey]; // 检查所有可执行任务是否都已在本轮尝试过

      return group.tasks.every(function (task) {
        if (!_this2.isTaskExecutable(task)) {
          return true; // 已删除、已完成或超过最大错误次数的任务不影响轮次完成
        }

        return record.executedTaskIds.has(task.task_id);
      });
    }
    /**
     * @description 重置轮次执行记录，开始新的轮次
     */

  }, {
    key: "startNewExecutionRound",
    value: function startNewExecutionRound() {
      this.executionRound++; // 清除所有分组的轮次记录，但保留分组结构

      for (var _i3 = 0, _Object$keys = Object.keys(this.roundExecutionRecord); _i3 < _Object$keys.length; _i3++) {
        var groupKey = _Object$keys[_i3];
        this.roundExecutionRecord[groupKey] = {
          currentRound: this.executionRound,
          executedTaskIds: new Set(),
          allTasksTriedInRound: false
        };
      }

      _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u5F00\u59CB\u65B0\u7684\u6267\u884C\u8F6E\u6B21: ".concat(this.executionRound));
    }
    /**
     * @description 过滤相同任务（扁平化key内按type_id去重）
     * @param {Array} taskList 新任务列表
     * @param {boolean} force 是否强制获取
     */

  }, {
    key: "filterTaskList",
    value: function filterTaskList(taskList) {
      var _this3 = this;

      var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var clearRepeatMap = {};
      taskList.forEach(function (item, index) {
        // 任务初始化
        taskList[index] = _this3.initTask(item);
        var task = taskList[index]; // 生成分组key

        var groupKey = MultiPlatformTaskV2.generateStoreMonthKey(task.platform_store_id, task.report_date_month); // 特殊处理repeat任务

        if (task.repeat > 0) {
          _this3.initRepeatTask(task, force);

          return;
        }

        if (task.isDelete) return; // 过滤新进任务中相同的任务
        // 在对应分组中查找相同任务（需要覆盖任务根据type_id去重，不需要覆盖任务根据task_id去重）

        var group = _this3.taskGroups[groupKey];

        if (group && group.tasks) {
          var sameTaskIndex = group.tasks.findIndex(function (existingTask) {
            if (_this3.runningNotCoverTypes.includes(+task.type_id)) {
              // 运行中不覆盖类型（如 22017）：同 store_id + 同 type_id 视为同一个任务
              return existingTask.store_id === task.store_id && existingTask.type_id === task.type_id && !existingTask.isDelete;
            }

            return (_this3.notCoverTypes.includes(+task.type_id) ? existingTask.task_id === task.task_id : existingTask.type_id === task.type_id) && !existingTask.isDelete;
          });

          if (sameTaskIndex !== -1) {
            var sameTask = group.tasks[sameTaskIndex]; // 如果是正在执行的任务，则不删除，但重置任务状态

            if (_this3.currentRunningTaskId === sameTask.task_id) {
              task.isDelete = true;
              sameTask.error_time = 0;
              sameTask.hide = false;
              sameTask.isDelete = false;
              sameTask.status = 0;
              return;
            }

            sameTask.isDelete = true;
          }
        }
      });
    }
    /**
     * @description 初始化repeat任务（不受月份分组影响）
     * @param {Object} task 任务对象
     * @param {boolean} force 是否强制获取
     */

  }, {
    key: "initRepeatTask",
    value: function initRepeatTask(task) {
      var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      if (task.repeat <= 0) return;
      var copy = Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* deepClone */ "g"])(task);
      copy.count = 0;
      copy.isRepeatMap = true; // 新的数据结构：{typeId: [task1, task2]}

      if (!this.repeatMap[task.type_id]) {
        this.repeatMap[task.type_id] = [];
      }

      var repeatList = this.repeatMap[task.type_id];
      var existingIndex = repeatList.findIndex(function (item) {
        return item.platform_store_id === task.platform_store_id;
      });

      if (existingIndex !== -1) {
        // 相同站点&不是点击的立即获取&不是repeatMap派遣的任务，则继续走repeat任务管理流程，删掉新进来的任务
        // 防止循环请求拉任务导致repeat任务重复执行
        if (!force && !task.isRepeatMap) {
          task.isDelete = true;
          copy.count = repeatList[existingIndex].count;
        } // 替换现有任务


        repeatList[existingIndex] = copy;
      } else {
        // 添加新任务
        repeatList.push(copy);
      }
    }
    /**
     * @description 任务队列初始化（扁平化分组、优先级排序、去重）
     * @param {Array} taskList 新任务列表
     * @param {boolean} force 是否强制获取
     */

  }, {
    key: "initTaskList",
    value: function () {
      var _initTaskList = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(taskList) {
        var _this4 = this;

        var force,
            newStoreIds,
            newGroups,
            _loop2,
            _i4,
            _Object$entries2,
            _ret,
            _args4 = arguments;

        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                force = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : false;

                if (!(taskList.length === 0)) {
                  _context4.next = 3;
                  break;
                }

                return _context4.abrupt("return");

              case 3:
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('任务初始化（扁平化分组、去重、优先级排序、店铺优先级排序）'); // 过滤相同任务

                this.filterTaskList(taskList, force); // 收集新店铺ID，用于优先级排序

                newStoreIds = new Set(); // 按扁平化key分组新任务

                newGroups = {};
                taskList.forEach(function (task) {
                  // 丢弃被删除任务和repeat任务
                  if (task.isDelete) return;
                  var groupKey = MultiPlatformTaskV2.generateStoreMonthKey(task.platform_store_id, task.report_date_month); // 记录新店铺ID

                  newStoreIds.add(task.platform_store_id);

                  if (newGroups[groupKey]) {
                    newGroups[groupKey].tasks.push(task);
                  } else if (_this4.taskGroups[groupKey]) {
                    _this4.taskGroups[groupKey].tasks.push(task);

                    newGroups[groupKey] = _this4.taskGroups[groupKey];
                  } else {
                    newGroups[groupKey] = {
                      storeInfo: _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].storeInfoOfExhibition.find(function (item) {
                        return item.mallId == task.platform_store_id || _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].storeIdMap[item.mallId] == task.platform_store_id;
                      }) || task.store_info || {},
                      tasks: [task],
                      storeId: task.platform_store_id,
                      monthId: task.report_date_month
                    };
                  }
                }); // 合并旧任务

                Object.keys(this.taskGroups).forEach(function (key) {
                  var group = _this4.taskGroups[key];

                  if (!newGroups[key]) {
                    newGroups[key] = group;
                  }
                }); // 处理分组中待删除任务&任务排序

                _loop2 = function _loop2() {
                  var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i4], 2),
                      key = _Object$entries2$_i[0],
                      group = _Object$entries2$_i[1];

                  group.tasks = group.tasks.filter(function (task) {
                    return !task.isDelete;
                  }); // 删除没有任务的分组

                  if (group.tasks.length === 0) {
                    delete newGroups[key];
                    newStoreIds.delete(group.storeId);
                    _this4.orderedKeys = _this4.orderedKeys.filter(function (k) {
                      return k !== key;
                    });
                    return "continue";
                  } // 根据任务类型优先级排序后再根据任务优先级排序


                  group.tasks.forEach(function (item) {
                    var obj = _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].taskTypesMap[item.type_id];

                    if (obj) {
                      obj.list.push(item);
                    }
                  });
                  var arr = [];
                  _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].taskTypes.forEach(function (item) {
                    if (item.list && item.list.length) {
                      item.list.sort(function (a, b) {
                        return b.priority - a.priority;
                      });
                      arr.push.apply(arr, _toConsumableArray(item.list));
                      item.list = [];
                    }
                  });
                  group.tasks = arr;
                };

                _i4 = 0, _Object$entries2 = Object.entries(newGroups);

              case 11:
                if (!(_i4 < _Object$entries2.length)) {
                  _context4.next = 18;
                  break;
                }

                _ret = _loop2();

                if (!(_ret === "continue")) {
                  _context4.next = 15;
                  break;
                }

                return _context4.abrupt("continue", 15);

              case 15:
                _i4++;
                _context4.next = 11;
                break;

              case 18:
                // 更新分组
                this.taskGroups = newGroups; // 更新执行顺序（新店铺优先）

                this.updateExecutionOrderWithPriority(Array.from(newStoreIds)); // 如果没有正在执行任务，开始任务调度

                if (!this.isExecuting) {
                  this.taskSchedule();
                }

              case 21:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this);
      }));

      function initTaskList(_x2) {
        return _initTaskList.apply(this, arguments);
      }

      return initTaskList;
    }()
    /**
     * @description 更新执行顺序（新店铺优先）
     * @param {Array} newStoreIds 新店铺ID列表
     */

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

      // 获取现有店铺顺序（排除新店铺）
      var existingStoreIds = this.orderedKeys.map(function (key) {
        return MultiPlatformTaskV2.parseStoreMonthKey(key).storeId;
      }).filter(function (storeId, index, arr) {
        return arr.indexOf(storeId) === index;
      }) // 去重
      .filter(function (storeId) {
        return !newStoreIds.includes(storeId);
      }); // 新的店铺顺序：新店铺优先，然后是现有店铺顺序

      var finalStoreOrder = [].concat(_toConsumableArray(newStoreIds), _toConsumableArray(existingStoreIds)); // 生成新的执行顺序

      var newOrderedKeys = [];
      finalStoreOrder.forEach(function (storeId) {
        var storeKeys = Object.keys(_this5.taskGroups).filter(function (key) {
          return key.startsWith("".concat(storeId, "_"));
        }).sort(function (a, b) {
          // 按月份倒序
          var monthA = MultiPlatformTaskV2.parseStoreMonthKey(a).monthId;
          var monthB = MultiPlatformTaskV2.parseStoreMonthKey(b).monthId;
          return (monthB || '').localeCompare(monthA || '');
        });
        newOrderedKeys.push.apply(newOrderedKeys, _toConsumableArray(storeKeys));
      }); // 调整当前指针位置

      var oldCurrentKey = this.currentGroupPointer;
      this.orderedKeys = newOrderedKeys; // 如果当前指针指向的分组仍存在，保持指针位置

      if (oldCurrentKey && this.taskGroups[oldCurrentKey]) {
        this.currentGroupPointer = oldCurrentKey;
      } else {
        // 否则重置到第一个分组
        this.currentGroupPointer = newOrderedKeys.length > 0 ? newOrderedKeys[0] : null;
      } // 重置组内任务索引
      // this.currentTaskPointer = 0


      _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u6267\u884C\u987A\u5E8F\u5DF2\u66F4\u65B0\uFF0C\u65B0\u5E97\u94FA\u4F18\u5148\uFF1A".concat(newStoreIds.join(','), "\uFF0C\u603B\u6267\u884C\u987A\u5E8F\uFF1A").concat(newOrderedKeys.join(',')));
    }
    /**
     * @description 判断任务能否执行
     * @param {Object} task 任务对象
     * @returns {boolean} 能否执行
     */

  }, {
    key: "canRunTask",
    value: function () {
      var _canRunTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(task) {
        var task_id, res, msg;
        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                task_id = task.task_id; // if (repeat >= 0) return true

                _context5.next = 3;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* gatePost */ "m"])('api/mp/handleReportInfoByType', {
                  // type: 4,
                  // data: { task_id }
                  task_id: task_id
                }, 'task').catch(function () {});

              case 3:
                res = _context5.sent;

                if (!(res && res.data)) {
                  _context5.next = 28;
                  break;
                }

                _context5.t0 = res.data.status;
                _context5.next = _context5.t0 === 0 ? 8 : _context5.t0 === 1 ? 9 : _context5.t0 === 2 ? 12 : _context5.t0 === 3 ? 20 : 28;
                break;

              case 8:
                return _context5.abrupt("return", true);

              case 9:
                task.isDelete = true;
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u4EFB\u52A1\u88AB\u5220\u9664\u6216\u5DF2\u8FC7\u671F,task_id:".concat(task.task_id, " \u5E97\u94FA\uFF1A").concat(task.platform_store_id));
                return _context5.abrupt("return", false);

              case 12:
                task.error_time = this.retryConfig.maxRetryCount;
                task.run_status = 4;
                task.status = 17;
                msg = '任务已失效';
                _context5.next = 18;
                return MultiPlatformTaskV2.uploadTask({
                  code: 1,
                  msg: msg
                }, task);

              case 18:
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u4EFB\u52A1\u5DF2\u5931\u6548,task_id:".concat(task.task_id, " \u5E97\u94FA\uFF1A").concat(task.platform_store_id));
                return _context5.abrupt("return", false);

              case 20:
                if (!(task.error_time > 0)) {
                  _context5.next = 24;
                  break;
                }

                return _context5.abrupt("return", true);

              case 24:
                task.error_time = this.retryConfig.maxRetryCount;
                task.msg = '任务已被其他插件执行';
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u4EFB\u52A1\u5DF2\u88AB\u5176\u4ED6\u63D2\u4EF6\u6267\u884C,task_id:".concat(task.task_id, " \u5E97\u94FA\uFF1A").concat(task.platform_store_id));
                return _context5.abrupt("return", false);

              case 28:
                task.error_time++;
                return _context5.abrupt("return", false);

              case 30:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this);
      }));

      function canRunTask(_x3) {
        return _canRunTask.apply(this, arguments);
      }

      return canRunTask;
    }()
    /**
     * @description 检查分组是否有可执行任务
     * @param {string} groupKey 分组key
     * @returns {boolean} 是否有可执行任务
     */

  }, {
    key: "hasExecutableInGroup",
    value: function hasExecutableInGroup(groupKey) {
      var _this6 = this;

      var group = this.taskGroups[groupKey];
      if (!group || !group.tasks) return false;
      return group.tasks.some(function (task) {
        return _this6.isTaskExecutable(task);
      });
    }
    /**
     * @description 检查是否还有可执行任务
     * @returns {boolean} 是否有可执行任务
     */

  }, {
    key: "hasExecutable",
    value: function () {
      var _hasExecutable = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
        var _iterator2, _step2, key;

        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                _context6.next = 2;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* executable */ "i"])();

              case 2:
                if (_context6.sent) {
                  _context6.next = 4;
                  break;
                }

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

              case 4:
                _iterator2 = _createForOfIteratorHelper(this.orderedKeys);
                _context6.prev = 5;

                _iterator2.s();

              case 7:
                if ((_step2 = _iterator2.n()).done) {
                  _context6.next = 18;
                  break;
                }

                key = _step2.value;
                _context6.t0 = this.hasExecutableInGroup(key);

                if (!_context6.t0) {
                  _context6.next = 14;
                  break;
                }

                _context6.next = 13;
                return this.discontinue();

              case 13:
                _context6.t0 = !_context6.sent;

              case 14:
                if (!_context6.t0) {
                  _context6.next = 16;
                  break;
                }

                return _context6.abrupt("return", true);

              case 16:
                _context6.next = 7;
                break;

              case 18:
                _context6.next = 23;
                break;

              case 20:
                _context6.prev = 20;
                _context6.t1 = _context6["catch"](5);

                _iterator2.e(_context6.t1);

              case 23:
                _context6.prev = 23;

                _iterator2.f();

                return _context6.finish(23);

              case 26:
                return _context6.abrupt("return", false);

              case 27:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this, [[5, 20, 23, 26]]);
      }));

      function hasExecutable() {
        return _hasExecutable.apply(this, arguments);
      }

      return hasExecutable;
    }() // 初始化指针位置

  }, {
    key: "initPointer",
    value: function initPointer() {
      if (!this.currentGroupPointer && this.orderedKeys.length > 0) {
        this.currentGroupPointer = this.orderedKeys[0];
        this.currentTaskPointer = 0;
      }
    }
    /**
     * @description 任务调度核心方法（指针式调度）
     */

  }, {
    key: "taskSchedule",
    value: function () {
      var _taskSchedule = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
        var curStatus, executed, nextTask, foundNext;
        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                _context7.prev = 0;
                curStatus = this.multiPlatformTaskStatus();

                if (!curStatus) {
                  _context7.next = 5;
                  break;
                }

                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u5F53\u524D\u6B63\u5728\u6267\u884C".concat(curStatus));
                return _context7.abrupt("return");

              case 5:
                // 设置执行状态
                this.multiPlatformTaskStatus(999);
                this.isExecuting = true; // 初始化指针位置

                this.initPointer(); // 指针式执行任务

              case 8:
                _context7.next = 10;
                return this.hasExecutable();

              case 10:
                if (!_context7.sent) {
                  _context7.next = 34;
                  break;
                }

                _context7.next = 13;
                return this.executeCurrentTask();

              case 13:
                executed = _context7.sent;

                if (!executed) {
                  _context7.next = 20;
                  break;
                }

                // 任务执行成功，移动到下一个任务
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u4EFB\u52A1\u6267\u884C\u5B8C\u6BD5\uFF0C\u79FB\u52A8\u5230\u4E0B\u4E00\u4E2A\u4EFB\u52A1");
                nextTask = this.moveToNextTask();

                if (!nextTask) {
                  _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u672A\u627E\u5230\u5F53\u524D\u7EC4\uFF1A".concat(this.currentGroupPointer, "\u7684\u4E0B\u4E00\u4E2A\u53EF\u6267\u884C\u4EFB\u52A1"));
                }

                _context7.next = 26;
                break;

              case 20:
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u5F53\u524D\u4F4D\u7F6E\u6CA1\u6709\u53EF\u6267\u884C\u4EFB\u52A1\uFF0C\u5C1D\u8BD5\u627E\u5230\u4E0B\u4E00\u4E2A\u53EF\u6267\u884C\u4EFB\u52A1"); // 当前位置没有可执行任务，尝试找到下一个可执行任务

                foundNext = this.findNextExecutableTask();

                if (foundNext) {
                  _context7.next = 26;
                  break;
                }

                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('本轮已没有更多可执行任务，进行下一轮');
                this.checkAndStartNewRound();
                return _context7.abrupt("break", 34);

              case 26:
                _context7.next = 28;
                return this.discontinue();

              case 28:
                if (!_context7.sent) {
                  _context7.next = 32;
                  break;
                }

                this.isExecuting = false;
                this.multiPlatformTaskStatus('idle');
                return _context7.abrupt("return");

              case 32:
                _context7.next = 8;
                break;

              case 34:
                // 切换空闲状态
                this.isExecuting = false;
                this.multiPlatformTaskStatus('idle');
                Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* setBadge */ "G"])(10);
                this.clearTaskList(); // 检查是否还有可执行任务

                _context7.next = 40;
                return this.hasExecutable();

              case 40:
                if (!_context7.sent) {
                  _context7.next = 44;
                  break;
                }

                this.taskSchedule();
                _context7.next = 45;
                break;

              case 44:
                // 无可执行任务时评估重试定时器
                this.scheduleRetryTimer();

              case 45:
                _context7.next = 53;
                break;

              case 47:
                _context7.prev = 47;
                _context7.t0 = _context7["catch"](0);
                this.isExecuting = false;
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].report("taskSchedule\u6267\u884C\u51FA\u9519".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context7.t0)), 'error');
                this.multiPlatformTaskStatus('idle'); // 异常情况下也要设置重试定时器，确保任务调度能够恢复

                this.scheduleRetryTimer();

              case 53:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, this, [[0, 47]]);
      }));

      function taskSchedule() {
        return _taskSchedule.apply(this, arguments);
      }

      return taskSchedule;
    }()
    /**
     * @description 执行当前指针指向的任务
     * @returns {boolean} 是否执行了任务
     */

  }, {
    key: "executeCurrentTask",
    value: function () {
      var _executeCurrentTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
        var group, task;
        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                if (this.currentGroupPointer) {
                  _context8.next = 2;
                  break;
                }

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

              case 2:
                group = this.taskGroups[this.currentGroupPointer];

                if (!(!group || !group.tasks || this.currentTaskPointer >= group.tasks.length)) {
                  _context8.next = 5;
                  break;
                }

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

              case 5:
                task = group.tasks[this.currentTaskPointer]; // 检查任务是否可执行

                _context8.t1 = !this.isTaskExecutable(task);

                if (_context8.t1) {
                  _context8.next = 11;
                  break;
                }

                _context8.next = 10;
                return this.discontinue();

              case 10:
                _context8.t1 = _context8.sent;

              case 11:
                _context8.t0 = _context8.t1;

                if (_context8.t0) {
                  _context8.next = 16;
                  break;
                }

                _context8.next = 15;
                return this.canRunTask(task);

              case 15:
                _context8.t0 = !_context8.sent;

              case 16:
                if (!_context8.t0) {
                  _context8.next = 18;
                  break;
                }

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

              case 18:
                if (!this.isTaskExecutedInCurrentRound(this.currentGroupPointer, task.task_id)) {
                  _context8.next = 20;
                  break;
                }

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

              case 20:
                // 标记任务在当前轮次已执行
                this.markTaskExecutedInRound(this.currentGroupPointer, task.task_id); // 执行任务

                this.currentRunningTaskId = task.task_id;
                _context8.next = 24;
                return this.executeTask(task);

              case 24:
                return _context8.abrupt("return", true);

              case 25:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee8, this);
      }));

      function executeCurrentTask() {
        return _executeCurrentTask.apply(this, arguments);
      }

      return executeCurrentTask;
    }()
    /**
     * @description 查找当前分组优先级最高的一条未在本轮执行过的任务指针（优先级已按顺序排列）
     */

  }, {
    key: "findHighestPriorityTaskInGroup",
    value: function findHighestPriorityTaskInGroup(curGroup) {
      var _this7 = this;

      var group = this.taskGroups[curGroup];
      if (!group || !group.tasks) return -1;
      return group.tasks.findIndex(function (task) {
        return _this7.isTaskExecutable(task) && !_this7.isTaskExecutedInCurrentRound(curGroup, task.task_id);
      });
    }
    /**
     * @description 移动指针到下一个任务
     */

  }, {
    key: "moveToNextTask",
    value: function moveToNextTask() {
      if (!this.currentGroupPointer) {
        this.initPointer();
        return false;
      }

      var group = this.taskGroups[this.currentGroupPointer];

      if (!group || !group.tasks) {
        _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("[\u5F53\u524D\u7EC4]\u6CA1\u6709\u4EFB\u52A1\uFF0C\u79FB\u52A8\u5230\u4E0B\u4E00\u4E2A\u5206\u7EC4\uFF1A".concat(this.currentGroupPointer));
        this.moveToNextGroup();
        return true;
      } // 查找当前组还未在本轮次执行的任务


      var taskIndex = this.findHighestPriorityTaskInGroup(this.currentGroupPointer);

      if (taskIndex === -1) {
        _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("[\u5F53\u524D\u7EC4]\u6CA1\u6709\u53EF\u6267\u884C\u4EFB\u52A1\uFF0C\u51C6\u5907\u79FB\u52A8\u5230\u4E0B\u4E00\u4E2A\u5206\u7EC4");
        this.moveToNextGroup();
        return true;
      }

      this.currentTaskPointer = taskIndex;
      _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u79FB\u52A8\u5230\u4E0B\u4E00\u4E2A\u4EFB\u52A1\uFF1A".concat(group.tasks[taskIndex].task_id, " \u5E97\u94FA\uFF1A").concat(this.currentGroupPointer));
      return true;
    }
    /**
     * @description 移动指针到下一个分组
     */

  }, {
    key: "moveToNextGroup",
    value: function moveToNextGroup() {
      var currentIndex = this.orderedKeys.indexOf(this.currentGroupPointer);

      if (currentIndex === -1 || currentIndex >= this.orderedKeys.length - 1) {
        // 已经是最后一个分组，检查是否需要开始新轮次
        this.checkAndStartNewRound();
      } else {
        // 移动到下一个分组
        this.currentGroupPointer = this.orderedKeys[currentIndex + 1];
        this.currentTaskPointer = 0;
      }
    }
    /**
     * @description 检查并开始新轮次
     */

  }, {
    key: "checkAndStartNewRound",
    value: function checkAndStartNewRound() {
      var _this8 = this;

      // 检查是否所有分组都完成了当前轮次
      var allGroupsComplete = this.orderedKeys.every(function (key) {
        return _this8.isGroupRoundComplete(key);
      });

      if (allGroupsComplete) {
        // 开始新轮次
        _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('所有分组都完成了当前轮次，开始新轮次');
        this.startNewExecutionRound();
      } // 重置到第一个分组


      this.currentGroupPointer = this.orderedKeys.length > 0 ? this.orderedKeys[0] : null;
      this.currentTaskPointer = 0;
    }
    /**
     * @description 查找下一个可执行任务
     * @returns {boolean} 是否找到可执行任务
     */

  }, {
    key: "findNextExecutableTask",
    value: function findNextExecutableTask() {
      console.log("\n      \u5F00\u59CB\u67E5\u627E\u4E0B\u4E00\u4E2A\u53EF\u6267\u884C\u4EFB\u52A1\n      \u5F53\u524D\u6240\u5728\u7EC4\uFF1A".concat(this.currentGroupPointer, "\n      \u6267\u884C\u987A\u5E8F\uFF1A\n      "), this.orderedKeys, '当前任务组列表：', this.taskGroups);

      if (!this.currentGroupPointer || this.orderedKeys.length === 0) {
        return false;
      } // 查找当前组还未在本轮次执行的任务


      var taskIndex = this.findHighestPriorityTaskInGroup(this.currentGroupPointer);

      if (taskIndex > -1) {
        this.currentTaskPointer = taskIndex;
        var task = this.taskGroups[this.currentGroupPointer].tasks[this.currentTaskPointer];
        _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("[\u5F53\u524D\u7EC4]\u627E\u5230\u53EF\u6267\u884C\u4EFB\u52A1\uFF1A".concat(task.task_id, " \u5E97\u94FA\uFF1A").concat(this.currentGroupPointer));
        return true;
      } // 从开头查找，直到找到可执行任务


      for (var groupIndex = 0; groupIndex < this.orderedKeys.length; groupIndex++) {
        var groupKey = this.orderedKeys[groupIndex]; // 跳过当前组

        if (this.currentGroupPointer === groupKey) {
          continue;
        }

        var group = this.taskGroups[groupKey];
        if (!group || !group.tasks) continue;

        for (var _taskIndex = 0; _taskIndex < group.tasks.length; _taskIndex++) {
          var _task = group.tasks[_taskIndex];

          if (this.isTaskExecutable(_task) && !this.isTaskExecutedInCurrentRound(groupKey, _task.task_id)) {
            // 找到可执行任务，更新指针
            this.currentGroupPointer = groupKey;
            this.currentTaskPointer = _taskIndex;
            _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("[\u5F53\u524D\u8F6E\u6B21]\u627E\u5230\u53EF\u6267\u884C\u4EFB\u52A1\uFF1A".concat(_task.task_id, " \u5E97\u94FA\uFF1A").concat(groupKey));
            return true;
          }
        }
      }

      return false; // 没有找到可执行任务
    }
    /**
     * @description 执行单个任务
     * @param {Object} task 任务对象
     * @param {string} groupKey 分组key
     * @param {number} taskIndex 任务索引
     */

  }, {
    key: "executeTask",
    value: function () {
      var _executeTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(task) {
        var _multiPlatform$taskTy, taskName, res, taskHandler, errorCode, _yield$multiPlatformO, onlineSiteStatus, mall, msg, changeSiteRes;

        return _regeneratorRuntime().wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                _context9.prev = 0;
                taskName = ((_multiPlatform$taskTy = _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].taskTypesMap[task.type_id]) === null || _multiPlatform$taskTy === void 0 ? void 0 : _multiPlatform$taskTy.taskName) || task.type_id;
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u5F00\u59CB\u6267\u884C\u4EFB\u52A1\uFF0C\u5F53\u524D\u6240\u5728\u7EC4\uFF1A".concat(this.currentGroupPointer));
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("\u5F53\u524D\u6267\u884C\u4EFB\u52A1".concat(taskName, "\n        --task_id:").concat(task.task_id, "\n        --type_id:").concat(task.type_id, "\n        --platform_store_id:").concat(task.platform_store_id, "\n        --report_date_month:").concat(task.report_date_month, "\n        ")); // 设置任务状态

                this.multiPlatformTaskStatus(task.type_id);
                task.isRun = true;

                if (task.status !== 6) {
                  task.status = 0;
                }

                !task.startTime && (task.startTime = Date.now());
                console.time("".concat(taskName, "\u8017\u65F6")); // 延时执行

                _context9.next = 11;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* delayed */ "h"])(Math.ceil(Math.random() * this.sleepTime));

              case 11:
                taskHandler = _taskType__WEBPACK_IMPORTED_MODULE_5__[/* multiTskHandleMap */ "b"][task.type_id];

                if (!(!taskHandler || !taskHandler.handle)) {
                  _context9.next = 17;
                  break;
                }

                task.msg = '未找到任务处理器';
                task.isDelete = true;
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].report(task.msg, 'error', task);
                return _context9.abrupt("return");

              case 17:
                errorCode = task.repeat > 0 ? 4 : 1; // 检查站点状态并执行任务

                _context9.next = 20;
                return Object(_index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatformOnlineSite */ "g"])(task);

              case 20:
                _yield$multiPlatformO = _context9.sent;
                onlineSiteStatus = _yield$multiPlatformO.onlineSiteStatus;
                mall = _yield$multiPlatformO.mall;
                msg = _yield$multiPlatformO.msg;

                if (!(onlineSiteStatus === 1)) {
                  _context9.next = 38;
                  break;
                }

                _context9.next = 27;
                return Object(_index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatformChangeSite */ "b"])(task);

              case 27:
                changeSiteRes = _context9.sent;

                if (!changeSiteRes) {
                  _context9.next = 32;
                  break;
                }

                _context9.next = 31;
                return _taskType__WEBPACK_IMPORTED_MODULE_5__[/* cores */ "a"][taskHandler.handle](task);

              case 31:
                res = _context9.sent;

              case 32:
                if (!(typeof changeSiteRes === 'number')) {
                  _context9.next = 35;
                  break;
                }

                _context9.next = 35;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* removeDeclarativeNetRequestRules */ "D"])([changeSiteRes]);

              case 35:
                res ? res.code !== 0 && ++task.error_time : task.isDelete = true;
                _context9.next = 39;
                break;

              case 38:
                if (onlineSiteStatus === 2) {
                  // 站点离线
                  task.error_time = this.retryConfig.maxRetryCount;
                  task.status = 11;
                  task.msg = "\u5E97\u94FA\u79BB\u7EBF\uFF0C\u8BF7\u767B\u5F55".concat(_index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].platformCode, "\u5356\u5BB6\u4E2D\u5FC3");
                  res = {
                    code: errorCode,
                    msg: task.msg,
                    result: null
                  };
                } else if (onlineSiteStatus === 3) {
                  // 店铺被切换
                  task.error_time = this.retryConfig.maxRetryCount;
                  task.status = 11;
                  task.msg = "\u5E97\u94FA\u5DF2\u88AB\u5207\u6362,\u5F53\u524D\u5E97\u94FA:".concat(mall);
                  res = {
                    code: errorCode,
                    msg: task.msg,
                    result: null
                  };
                } else {
                  // 其他异常
                  task.error_time = this.retryConfig.maxRetryCount;
                  task.status = 16;
                  task.msg = msg;
                  res = {
                    code: errorCode,
                    msg: msg,
                    result: null
                  };
                }

              case 39:
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('获取结果', JSON.stringify(res)); // 上传结果

                _context9.t0 = res;

                if (!_context9.t0) {
                  _context9.next = 45;
                  break;
                }

                _context9.next = 44;
                return this.discontinue();

              case 44:
                _context9.t0 = !_context9.sent;

              case 45:
                if (!_context9.t0) {
                  _context9.next = 48;
                  break;
                }

                _context9.next = 48;
                return MultiPlatformTaskV2.uploadTask(res, task);

              case 48:
                // 记录结束时间
                task.endTime = Date.now();
                console.timeEnd("".concat(taskName, "\u8017\u65F6"));
                _context9.next = 57;
                break;

              case 52:
                _context9.prev = 52;
                _context9.t1 = _context9["catch"](0);
                task.error_time++;
                task.endTime = Date.now();
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].report("\n        \u4EFB\u52A1\u6267\u884C\u51FA\u9519: ".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context9.t1), "\n        --type_id:").concat(task.type_id, "\n        --task_id:").concat(task.task_id, "\n        "), 'error');

              case 57:
              case "end":
                return _context9.stop();
            }
          }
        }, _callee9, this, [[0, 52]]);
      }));

      function executeTask(_x4) {
        return _executeTask.apply(this, arguments);
      }

      return executeTask;
    }()
    /**
     * @description 执行repeat任务
     */

  }, {
    key: "runRepeat",
    value: function () {
      var _runRepeat = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
        var repeatTaskList, typeId, taskList, _iterator3, _step3, task;

        return _regeneratorRuntime().wrap(function _callee10$(_context10) {
          while (1) {
            switch (_context10.prev = _context10.next) {
              case 0:
                try {
                  repeatTaskList = [];

                  for (typeId in this.repeatMap) {
                    taskList = this.repeatMap[typeId] || [];
                    _iterator3 = _createForOfIteratorHelper(taskList);

                    try {
                      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
                        task = _step3.value;
                        task.count++;

                        if (task.repeat <= _config__WEBPACK_IMPORTED_MODULE_3__[/* POLLING_TIME */ "c"] * task.count) {
                          _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("[".concat(moment__WEBPACK_IMPORTED_MODULE_0___default()().format('YYYY-MM-DD HH:mm:ss'), "]\u5F00\u59CB\u6267\u884C\u91CD\u590D\u4EFB\u52A1\uFF0Ctype_id\uFF1A").concat(task.type_id, "\uFF0Ctask_id\uFF1A").concat(task.task_id));
                          task.count = 0;
                          repeatTaskList.push(task);
                        }
                      }
                    } catch (err) {
                      _iterator3.e(err);
                    } finally {
                      _iterator3.f();
                    }
                  }

                  this.initTaskList(repeatTaskList);
                } catch (e) {
                  _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].report("\u6267\u884Crepeat\u4EFB\u52A1\u9519\u8BEF----".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(e)), 'error');
                }

              case 1:
              case "end":
                return _context10.stop();
            }
          }
        }, _callee10, this);
      }));

      function runRepeat() {
        return _runRepeat.apply(this, arguments);
      }

      return runRepeat;
    }()
    /**
     * @description 清理已完成的任务
     */

  }, {
    key: "clearTaskList",
    value: function clearTaskList() {
      var _this9 = this;

      _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('开始清理任务、恢复指针'); // 清理每个分组中的已完成任务

      var _loop3 = function _loop3() {
        var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i5], 2),
            key = _Object$entries3$_i[0],
            group = _Object$entries3$_i[1];

        var isExistMap = {};
        group.tasks = group.tasks.filter(function (task) {
          // 只留一条已执行过的覆盖任务
          if (!_this9.notCoverTypes.includes(+task.type_id) && isExistMap[task.type_id]) return false;
          isExistMap[task.type_id] = true;
          return !task.isDelete;
        });

        if (group.tasks.length === 0) {
          delete _this9.taskGroups[key];
          _this9.orderedKeys = _this9.orderedKeys.filter(function (k) {
            return k !== key;
          });
        }
      };

      for (var _i5 = 0, _Object$entries3 = Object.entries(this.taskGroups); _i5 < _Object$entries3.length; _i5++) {
        _loop3();
      } // 恢复指针


      this.fixPointersAfterCleanup();
    }
  }, {
    key: "fixPointersAfterCleanup",
    value: function fixPointersAfterCleanup() {
      this.currentGroupPointer = this.orderedKeys.length > 0 ? this.orderedKeys[0] : null;
      this.currentTaskPointer = 0;
      this.currentRunningTaskId = null;
    }
    /**
     * @description 获取/设置任务执行状态
     * @param {*} type 任务类型
     * @returns {string|boolean} 状态名称或设置结果
     */

  }, {
    key: "multiPlatformTaskStatus",
    value: function multiPlatformTaskStatus(type) {
      if (type) {
        this.taskStatus = type;
      } else {
        var _multiPlatform$taskTy2;

        return this.taskStatus === 'idle' ? false : ((_multiPlatform$taskTy2 = _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].taskTypesMap[this.taskStatus]) === null || _multiPlatform$taskTy2 === void 0 ? void 0 : _multiPlatform$taskTy2.taskName) || this.taskStatus;
      }
    }
    /**
     * @description 检查是否应该暂停
     * @returns {boolean} 是否暂停
     */

  }, {
    key: "discontinue",
    value: function () {
      var _discontinue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
        return _regeneratorRuntime().wrap(function _callee11$(_context11) {
          while (1) {
            switch (_context11.prev = _context11.next) {
              case 0:
                _context11.next = 2;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* suspend */ "J"])();

              case 2:
                if (!_context11.sent) {
                  _context11.next = 5;
                  break;
                }

                this.multiPlatformTaskStatus('idle');
                return _context11.abrupt("return", true);

              case 5:
                return _context11.abrupt("return", false);

              case 6:
              case "end":
                return _context11.stop();
            }
          }
        }, _callee11, this);
      }));

      function discontinue() {
        return _discontinue.apply(this, arguments);
      }

      return discontinue;
    }()
    /**
     * @description 销毁实例
     */

  }, {
    key: "destroyed",
    value: function destroyed() {
      this.taskGroups = {};
      this.orderedKeys = [];
      this.repeatMap = {};
      this.roundExecutionRecord = {};
      this.multiPlatformTaskStatus('idle');
      this.clearRetryTimer();
    }
  }], [{
    key: "generateStoreMonthKey",
    value:
    /**
     * @description 生成店铺+月份组合key
     * @param {string} storeId 店铺ID
     * @param {string} monthId 月份
     * @returns {string} 组合key
     */
    function generateStoreMonthKey(storeId, monthId) {
      return "".concat(storeId, "_").concat(monthId || 'default');
    }
    /**
     * @description 解析店铺+月份组合key
     * @param {string} key 组合key
     * @returns {object} {storeId, monthId}
     */

  }, {
    key: "parseStoreMonthKey",
    value: function parseStoreMonthKey(key) {
      var _key$split = key.split('_'),
          _key$split2 = _slicedToArray(_key$split, 2),
          storeId = _key$split2[0],
          monthId = _key$split2[1];

      return {
        storeId: storeId,
        monthId: monthId === 'default' ? null : monthId
      };
    }
    /**
     * @description 上传任务执行结果到服务器
     * @param {Object} params 上传参数
     * @param {Object} task 任务对象
     * @param {number} count 重试次数
     */

  }, {
    key: "uploadTask",
    value: function () {
      var _uploadTask = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(params, task) {
        var count,
            res,
            _args12 = arguments;
        return _regeneratorRuntime().wrap(function _callee12$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                count = _args12.length > 2 && _args12[2] !== undefined ? _args12[2] : 0;
                _context12.next = 3;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* gatePost */ "m"])("api/mp/reportTask", _objectSpread({
                  task_id: task.task_id,
                  type_id: task.type_id,
                  platform_store_id: task.platform_store_id,
                  taskIdList: task.taskIdList,
                  platform: _index__WEBPACK_IMPORTED_MODULE_4__[/* multiPlatform */ "a"].platformCode
                }, params), 'task').catch(function (e) {
                  _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('上传错误：', Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(e));
                });

              case 3:
                res = _context12.sent;
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog('上传结果：', JSON.stringify(res));

                if (!(res && res.code === 0)) {
                  _context12.next = 10;
                  break;
                }

                if (params.code === 0) {
                  // 上传成功，修改状态
                  task.status = 1;
                  task.uploadTime = moment__WEBPACK_IMPORTED_MODULE_0___default()().format('YYYY-MM-DD HH:mm:ss');
                }

                return _context12.abrupt("return", true);

              case 10:
                if (!(res && res.code === 3002)) {
                  _context12.next = 16;
                  break;
                }

                // 任务不存在或已删除，直接删掉任务
                _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("task_id:".concat(task.task_id, " - ").concat(res.msg));
                task.isDelete = true;
                task.msg = res.msg;
                _context12.next = 25;
                break;

              case 16:
                if (!(count < 2)) {
                  _context12.next = 24;
                  break;
                }

                _context12.next = 19;
                return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* delayed */ "h"])(5 * 1000);

              case 19:
                _context12.next = 21;
                return MultiPlatformTaskV2.uploadTask(params, task, ++count);

              case 21:
                return _context12.abrupt("return", _context12.sent);

              case 24:
                if (params.code === 0) {
                  // 上传失败，修改状态
                  task.status = 7;
                  task.error_time++;
                  task.msg = '上传失败';
                  task.resCache = params;
                }

              case 25:
              case "end":
                return _context12.stop();
            }
          }
        }, _callee12);
      }));

      function uploadTask(_x5, _x6) {
        return _uploadTask.apply(this, arguments);
      }

      return uploadTask;
    }()
  }]);

  return MultiPlatformTaskV2;
}();

/* harmony default export */ __webpack_exports__["a"] = (MultiPlatformTaskV2);

/***/ }),

/***/ "6a0a":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ generateXBogus; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ generateXGnarly; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ getSigner; });

// UNUSED EXPORTS: signParams, signUrl

// EXTERNAL MODULE: ./src/utils/util.js
var util = __webpack_require__("ca00");

// CONCATENATED MODULE: ./src/platform/tiktok/xGnarly/signer.js
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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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

/* eslint-disable */

/**
 * TikTok 签名服务（浏览器扩展版本）
 * 通过与 TikTok 页面通信来生成签名
 * 优先复用用户已打开的同源 Tab；否则在单一共享最小化窗口内按 origin 常驻多 Tab。
 */

/** 无签名活动超过此时长后关闭共享签名窗口（分钟） */

var SIGNER_IDLE_MINUTES = 10;
var SIGNER_IDLE_ALARM = 'AK_TikTok_Signer_Idle';
var SIGNER_SHARED_WINDOW_ID_KEY = 'tiktokSignerSharedWindowId';

function promisifyTabsGet(tabId) {
  return new Promise(function (resolve, reject) {
    chrome.tabs.get(tabId, function (tab) {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      resolve(tab);
    });
  });
}

function promisifyWindowsGet(windowId) {
  return new Promise(function (resolve, reject) {
    chrome.windows.get(windowId, {}, function (win) {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      resolve(win);
    });
  });
}

function promisifyTabsQuery(queryInfo) {
  return new Promise(function (resolve) {
    chrome.tabs.query(queryInfo, function (tabs) {
      return resolve(tabs || []);
    });
  });
}

function promisifyTabsCreate(createProperties) {
  return new Promise(function (resolve, reject) {
    chrome.tabs.create(createProperties, function (tab) {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      resolve(tab);
    });
  });
}

function promisifyTabsRemove(tabIds) {
  return new Promise(function (resolve, reject) {
    chrome.tabs.remove(tabIds, function () {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      resolve();
    });
  });
}

function promisifyWindowsCreate(createData) {
  return new Promise(function (resolve, reject) {
    chrome.windows.create(createData, function (win) {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      resolve(win);
    });
  });
}

function promisifyWindowsUpdate(windowId, updateInfo) {
  return new Promise(function (resolve, reject) {
    chrome.windows.update(windowId, updateInfo, function (win) {
      if (chrome.runtime.lastError) {
        reject(new Error(chrome.runtime.lastError.message));
        return;
      }

      resolve(win);
    });
  });
}

function waitMs(ms) {
  return new Promise(function (resolve) {
    var name = "signerWait_".concat(Date.now(), "_").concat(Math.random().toString(36).slice(2, 8));
    util["b" /* alarms */].setTimeout(function () {
      return resolve();
    }, name, ms);
  });
}

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

    this.sharedWindowId = null;
    this.originHosts = new Map();
    this.originWarmPromises = new Map();
    this.tabChains = new Map();
    this.skipTabIds = new Set();
    this.currentOrigin = null;
    this.tiktokTabId = null;
    this._reqSeq = 0;
    this._boundOnTabRemoved = this._onTabRemoved.bind(this);
    this._boundOnWindowRemoved = this._onWindowRemoved.bind(this);
    chrome.tabs.onRemoved.addListener(this._boundOnTabRemoved);
    chrome.windows.onRemoved.addListener(this._boundOnWindowRemoved);
  }
  /**
   * 重置空闲计时：任意签名相关活动后调用，SIGNER_IDLE_MINUTES 后关闭共享窗口
   */


  _createClass(Signer, [{
    key: "scheduleIdleCloseSharedWindow",
    value: function scheduleIdleCloseSharedWindow() {
      var _this = this;

      var delayMs = SIGNER_IDLE_MINUTES * 60 * 1000;
      chrome.alarms.clear(SIGNER_IDLE_ALARM, function () {
        util["b" /* alarms */].setTimeout(function () {
          _this.closeSharedWindowOnly().catch(function () {});
        }, SIGNER_IDLE_ALARM, delayMs);
      });
    }
  }, {
    key: "getPersistedSharedWindowId",
    value: function () {
      var _getPersistedSharedWindowId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
        var _yield$localStorage$g, windowId;

        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.next = 2;
                return util["y" /* localStorage */].getItem([SIGNER_SHARED_WINDOW_ID_KEY]);

              case 2:
                _yield$localStorage$g = _context.sent;
                windowId = _yield$localStorage$g[SIGNER_SHARED_WINDOW_ID_KEY];
                return _context.abrupt("return", typeof windowId === 'number' ? windowId : null);

              case 5:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      function getPersistedSharedWindowId() {
        return _getPersistedSharedWindowId.apply(this, arguments);
      }

      return getPersistedSharedWindowId;
    }()
  }, {
    key: "persistSharedWindowId",
    value: function () {
      var _persistSharedWindowId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(windowId) {
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (!(typeof windowId !== 'number')) {
                  _context2.next = 2;
                  break;
                }

                return _context2.abrupt("return");

              case 2:
                _context2.next = 4;
                return util["y" /* localStorage */].setItem(_defineProperty({}, SIGNER_SHARED_WINDOW_ID_KEY, windowId));

              case 4:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      function persistSharedWindowId(_x) {
        return _persistSharedWindowId.apply(this, arguments);
      }

      return persistSharedWindowId;
    }()
  }, {
    key: "clearPersistedSharedWindowId",
    value: function () {
      var _clearPersistedSharedWindowId = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return util["y" /* localStorage */].removeItem([SIGNER_SHARED_WINDOW_ID_KEY]);

              case 2:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

      function clearPersistedSharedWindowId() {
        return _clearPersistedSharedWindowId.apply(this, arguments);
      }

      return clearPersistedSharedWindowId;
    }()
    /**
     * 仅关闭扩展创建的共享签名窗口，并清理其中 origin 缓存；不影响用户自有 Tab 的复用记录
     */

  }, {
    key: "closeSharedWindowOnly",
    value: function () {
      var _closeSharedWindowOnly = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
        var wid, _i, _arr, _arr$_i, origin, h;

        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                try {
                  chrome.alarms.clear(SIGNER_IDLE_ALARM, function () {});
                } catch (e) {
                  /* ignore */
                }

                if (!(this.sharedWindowId != null)) {
                  _context4.next = 5;
                  break;
                }

                _context4.t0 = this.sharedWindowId;
                _context4.next = 8;
                break;

              case 5:
                _context4.next = 7;
                return this.getPersistedSharedWindowId();

              case 7:
                _context4.t0 = _context4.sent;

              case 8:
                wid = _context4.t0;

                if (!(wid == null)) {
                  _context4.next = 11;
                  break;
                }

                return _context4.abrupt("return");

              case 11:
                this.sharedWindowId = null;
                _context4.next = 14;
                return this.clearPersistedSharedWindowId();

              case 14:
                for (_i = 0, _arr = _toConsumableArray(this.originHosts.entries()); _i < _arr.length; _i++) {
                  _arr$_i = _slicedToArray(_arr[_i], 2), origin = _arr$_i[0], h = _arr$_i[1];

                  if (h.source === 'shared-window-tab') {
                    this.originHosts.delete(origin);
                    this.tabChains.delete(h.tabId);
                  }
                }

                _context4.prev = 15;
                _context4.next = 18;
                return new Promise(function (resolve) {
                  chrome.windows.remove(wid, function () {
                    return resolve();
                  });
                });

              case 18:
                _context4.next = 22;
                break;

              case 20:
                _context4.prev = 20;
                _context4.t1 = _context4["catch"](15);

              case 22:
                console.log('[AK-Signer] Shared signer window closed (idle or lifecycle)');

              case 23:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4, this, [[15, 20]]);
      }));

      function closeSharedWindowOnly() {
        return _closeSharedWindowOnly.apply(this, arguments);
      }

      return closeSharedWindowOnly;
    }()
  }, {
    key: "_onTabRemoved",
    value: function _onTabRemoved(tabId) {
      for (var _i2 = 0, _arr2 = _toConsumableArray(this.originHosts.entries()); _i2 < _arr2.length; _i2++) {
        var _arr2$_i = _slicedToArray(_arr2[_i2], 2),
            origin = _arr2$_i[0],
            h = _arr2$_i[1];

        if (h.tabId === tabId) {
          this.originHosts.delete(origin);
        }
      }

      this.tabChains.delete(tabId);
    }
  }, {
    key: "_onWindowRemoved",
    value: function _onWindowRemoved(windowId) {
      if (windowId !== this.sharedWindowId) return;
      this.sharedWindowId = null;

      for (var _i3 = 0, _arr3 = _toConsumableArray(this.originHosts.entries()); _i3 < _arr3.length; _i3++) {
        var _arr3$_i = _slicedToArray(_arr3[_i3], 2),
            origin = _arr3$_i[0],
            h = _arr3$_i[1];

        if (h.source === 'shared-window-tab') {
          this.originHosts.delete(origin);
        }
      }
    }
    /**
     * 解析目标 URL 的 origin；无 URL 或非法时默认 TikTok 主站
     * @param {string|null|undefined} targetUrl
     * @returns {string}
     */

  }, {
    key: "getOrigin",
    value: function getOrigin(targetUrl) {
      if (!targetUrl) {
        return 'https://www.tiktok.com';
      }

      try {
        var origin = new URL(targetUrl).origin;

        if (!this.isAllowedSigningOrigin(origin)) {
          console.warn('[AK-Signer] Origin not allowed, fallback www.tiktok.com:', origin);
          return 'https://www.tiktok.com';
        }

        return origin;
      } catch (e) {
        console.warn('[AK-Signer] Invalid URL, fallback www.tiktok.com:', targetUrl);
        return 'https://www.tiktok.com';
      }
    }
  }, {
    key: "isAllowedSigningOrigin",
    value: function isAllowedSigningOrigin(origin) {
      try {
        var _URL = new URL(origin),
            hostname = _URL.hostname;

        return hostname.includes('tiktok.com') || hostname.includes('tiktokshopglobalselling.com');
      } catch (_unused) {
        return false;
      }
    }
    /**
     * 查找用户已打开的同源 Tab（不含扩展专用共享窗口内的 Tab）
     * @param {string} origin
     */

  }, {
    key: "findReusableUserTab",
    value: function () {
      var _findReusableUserTab = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(origin) {
        var _this2 = this;

        var tabs, matches, _iterator, _step, t;

        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                _context5.next = 2;
                return promisifyTabsQuery({});

              case 2:
                tabs = _context5.sent;
                matches = tabs.filter(function (t) {
                  if (!t.url || t.url.startsWith('chrome-extension:')) return false;

                  if (_this2.sharedWindowId != null && t.windowId === _this2.sharedWindowId) {
                    return false;
                  }

                  try {
                    return new URL(t.url).origin === origin;
                  } catch (_unused2) {
                    return false;
                  }
                });

                if (!(matches.length === 0)) {
                  _context5.next = 6;
                  break;
                }

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

              case 6:
                matches.sort(function (a, b) {
                  if (a.active && !b.active) return -1;
                  if (!a.active && b.active) return 1;
                  return (b.lastAccessed || 0) - (a.lastAccessed || 0);
                });
                _iterator = _createForOfIteratorHelper(matches);
                _context5.prev = 8;

                _iterator.s();

              case 10:
                if ((_step = _iterator.n()).done) {
                  _context5.next = 16;
                  break;
                }

                t = _step.value;

                if (this.skipTabIds.has(t.id)) {
                  _context5.next = 14;
                  break;
                }

                return _context5.abrupt("return", t);

              case 14:
                _context5.next = 10;
                break;

              case 16:
                _context5.next = 21;
                break;

              case 18:
                _context5.prev = 18;
                _context5.t0 = _context5["catch"](8);

                _iterator.e(_context5.t0);

              case 21:
                _context5.prev = 21;

                _iterator.f();

                return _context5.finish(21);

              case 24:
                return _context5.abrupt("return", null);

              case 25:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5, this, [[8, 18, 21, 24]]);
      }));

      function findReusableUserTab(_x2) {
        return _findReusableUserTab.apply(this, arguments);
      }

      return findReusableUserTab;
    }()
  }, {
    key: "ensureSharedWindow",
    value: function () {
      var _ensureSharedWindow = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(originForFirstTab) {
        var _i4, _arr4, _arr4$_i, origin, h, persistedWindowId, seedOrigin, win;

        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                if (!(this.sharedWindowId != null)) {
                  _context6.next = 11;
                  break;
                }

                _context6.prev = 1;
                _context6.next = 4;
                return promisifyWindowsGet(this.sharedWindowId);

              case 4:
                return _context6.abrupt("return", this.sharedWindowId);

              case 7:
                _context6.prev = 7;
                _context6.t0 = _context6["catch"](1);
                this.sharedWindowId = null;

                for (_i4 = 0, _arr4 = _toConsumableArray(this.originHosts.entries()); _i4 < _arr4.length; _i4++) {
                  _arr4$_i = _slicedToArray(_arr4[_i4], 2), origin = _arr4$_i[0], h = _arr4$_i[1];

                  if (h.source === 'shared-window-tab') {
                    this.originHosts.delete(origin);
                  }
                }

              case 11:
                _context6.next = 13;
                return this.getPersistedSharedWindowId();

              case 13:
                persistedWindowId = _context6.sent;

                if (!(persistedWindowId != null)) {
                  _context6.next = 26;
                  break;
                }

                _context6.prev = 15;
                _context6.next = 18;
                return promisifyWindowsGet(persistedWindowId);

              case 18:
                this.sharedWindowId = persistedWindowId;
                return _context6.abrupt("return", this.sharedWindowId);

              case 22:
                _context6.prev = 22;
                _context6.t1 = _context6["catch"](15);
                _context6.next = 26;
                return this.clearPersistedSharedWindowId();

              case 26:
                seedOrigin = originForFirstTab || 'https://www.tiktok.com'; // create 时不要传离屏 bounds。
                // Chrome 要求新窗口至少有一半区域位于可视屏幕内，否则会报
                // "Invalid value for bounds. Bounds must be at least 50% within visible screen space."

                _context6.next = 29;
                return promisifyWindowsCreate({
                  url: "".concat(seedOrigin, "/"),
                  focused: false,
                  type: 'normal'
                });

              case 29:
                win = _context6.sent;
                this.sharedWindowId = win.id;
                _context6.next = 33;
                return this.persistSharedWindowId(win.id);

              case 33:
                _context6.next = 35;
                return this.tryMinimizeWindow(win.id);

              case 35:
                _context6.next = 37;
                return this.cleanupSharedWindowSeedTabs(win.id, seedOrigin);

              case 37:
                return _context6.abrupt("return", this.sharedWindowId);

              case 38:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6, this, [[1, 7], [15, 22]]);
      }));

      function ensureSharedWindow(_x3) {
        return _ensureSharedWindow.apply(this, arguments);
      }

      return ensureSharedWindow;
    }()
  }, {
    key: "tryMinimizeWindow",
    value: function () {
      var _tryMinimizeWindow = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(windowId) {
        var retryDelays, _i5, _retryDelays, delay, win, current;

        return _regeneratorRuntime().wrap(function _callee7$(_context7) {
          while (1) {
            switch (_context7.prev = _context7.next) {
              case 0:
                retryDelays = [300, 800];
                _i5 = 0, _retryDelays = retryDelays;

              case 2:
                if (!(_i5 < _retryDelays.length)) {
                  _context7.next = 29;
                  break;
                }

                delay = _retryDelays[_i5];
                _context7.next = 6;
                return waitMs(delay);

              case 6:
                _context7.prev = 6;
                _context7.next = 9;
                return promisifyWindowsUpdate(windowId, {
                  state: 'minimized'
                });

              case 9:
                win = _context7.sent;

                if (!((win === null || win === void 0 ? void 0 : win.state) === 'minimized')) {
                  _context7.next = 12;
                  break;
                }

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

              case 12:
                _context7.next = 16;
                break;

              case 14:
                _context7.prev = 14;
                _context7.t0 = _context7["catch"](6);

              case 16:
                _context7.prev = 16;
                _context7.next = 19;
                return promisifyWindowsGet(windowId);

              case 19:
                current = _context7.sent;

                if (!((current === null || current === void 0 ? void 0 : current.state) === 'minimized')) {
                  _context7.next = 22;
                  break;
                }

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

              case 22:
                _context7.next = 26;
                break;

              case 24:
                _context7.prev = 24;
                _context7.t1 = _context7["catch"](16);

              case 26:
                _i5++;
                _context7.next = 2;
                break;

              case 29:
                return _context7.abrupt("return", false);

              case 30:
              case "end":
                return _context7.stop();
            }
          }
        }, _callee7, null, [[6, 14], [16, 24]]);
      }));

      function tryMinimizeWindow(_x4) {
        return _tryMinimizeWindow.apply(this, arguments);
      }

      return tryMinimizeWindow;
    }()
  }, {
    key: "findSharedWindowTab",
    value: function () {
      var _findSharedWindowTab = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(origin, windowId) {
        var tabs, _iterator2, _step2, t, rawUrl;

        return _regeneratorRuntime().wrap(function _callee8$(_context8) {
          while (1) {
            switch (_context8.prev = _context8.next) {
              case 0:
                _context8.next = 2;
                return promisifyTabsQuery({
                  windowId: windowId
                });

              case 2:
                tabs = _context8.sent;
                _iterator2 = _createForOfIteratorHelper(tabs);
                _context8.prev = 4;

                _iterator2.s();

              case 6:
                if ((_step2 = _iterator2.n()).done) {
                  _context8.next = 20;
                  break;
                }

                t = _step2.value;
                rawUrl = t.pendingUrl || t.url;

                if (!(!rawUrl || !rawUrl.startsWith('http'))) {
                  _context8.next = 11;
                  break;
                }

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

              case 11:
                _context8.prev = 11;

                if (!(new URL(rawUrl).origin === origin)) {
                  _context8.next = 14;
                  break;
                }

                return _context8.abrupt("return", t);

              case 14:
                _context8.next = 18;
                break;

              case 16:
                _context8.prev = 16;
                _context8.t0 = _context8["catch"](11);

              case 18:
                _context8.next = 6;
                break;

              case 20:
                _context8.next = 25;
                break;

              case 22:
                _context8.prev = 22;
                _context8.t1 = _context8["catch"](4);

                _iterator2.e(_context8.t1);

              case 25:
                _context8.prev = 25;

                _iterator2.f();

                return _context8.finish(25);

              case 28:
                return _context8.abrupt("return", null);

              case 29:
              case "end":
                return _context8.stop();
            }
          }
        }, _callee8, null, [[4, 22, 25, 28], [11, 16]]);
      }));

      function findSharedWindowTab(_x5, _x6) {
        return _findSharedWindowTab.apply(this, arguments);
      }

      return findSharedWindowTab;
    }()
  }, {
    key: "cleanupSharedWindowSeedTabs",
    value: function () {
      var _cleanupSharedWindowSeedTabs = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(windowId, origin) {
        var tabs, matchedTabs, keepTab, removableTabIds;
        return _regeneratorRuntime().wrap(function _callee9$(_context9) {
          while (1) {
            switch (_context9.prev = _context9.next) {
              case 0:
                _context9.next = 2;
                return waitMs(300);

              case 2:
                _context9.next = 4;
                return promisifyTabsQuery({
                  windowId: windowId
                });

              case 4:
                tabs = _context9.sent;

                if (!(!tabs || tabs.length <= 1)) {
                  _context9.next = 7;
                  break;
                }

                return _context9.abrupt("return");

              case 7:
                matchedTabs = tabs.filter(function (t) {
                  var rawUrl = t.pendingUrl || t.url;
                  if (!rawUrl || !rawUrl.startsWith('http')) return false;

                  try {
                    return new URL(rawUrl).origin === origin;
                  } catch (_unused6) {
                    return false;
                  }
                });

                if (!(matchedTabs.length === 0)) {
                  _context9.next = 10;
                  break;
                }

                return _context9.abrupt("return");

              case 10:
                keepTab = matchedTabs[0];
                removableTabIds = tabs.filter(function (t) {
                  return t.id !== keepTab.id;
                }).map(function (t) {
                  return t.id;
                }).filter(Boolean);

                if (!(removableTabIds.length === 0)) {
                  _context9.next = 14;
                  break;
                }

                return _context9.abrupt("return");

              case 14:
                _context9.prev = 14;
                _context9.next = 17;
                return promisifyTabsRemove(removableTabIds);

              case 17:
                _context9.next = 21;
                break;

              case 19:
                _context9.prev = 19;
                _context9.t0 = _context9["catch"](14);

              case 21:
              case "end":
                return _context9.stop();
            }
          }
        }, _callee9, null, [[14, 19]]);
      }));

      function cleanupSharedWindowSeedTabs(_x7, _x8) {
        return _cleanupSharedWindowSeedTabs.apply(this, arguments);
      }

      return cleanupSharedWindowSeedTabs;
    }()
  }, {
    key: "createSharedWindowTab",
    value: function () {
      var _createSharedWindowTab = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(origin, windowId) {
        return _regeneratorRuntime().wrap(function _callee10$(_context10) {
          while (1) {
            switch (_context10.prev = _context10.next) {
              case 0:
                return _context10.abrupt("return", promisifyTabsCreate({
                  windowId: windowId,
                  url: "".concat(origin, "/"),
                  active: false
                }));

              case 1:
              case "end":
                return _context10.stop();
            }
          }
        }, _callee10);
      }));

      function createSharedWindowTab(_x9, _x10) {
        return _createSharedWindowTab.apply(this, arguments);
      }

      return createSharedWindowTab;
    }()
    /**
     * 单次 PING Content Script / 签名桥是否就绪
     */

  }, {
    key: "pingOnce",
    value: function pingOnce(tabId) {
      var _this3 = this;

      return new Promise(function (resolve) {
        var name = "signPing_".concat(++_this3._reqSeq);
        util["b" /* alarms */].setTimeout(function () {
          try {
            chrome.alarms.clear(name);
          } catch (e) {
            /* ignore */
          }

          resolve(false);
        }, name, 12000);
        chrome.tabs.sendMessage(tabId, {
          type: 'TIKTOK_SIGN_PING'
        }, function (response) {
          try {
            chrome.alarms.clear(name);
          } catch (e) {
            /* ignore */
          }

          if (chrome.runtime.lastError) {
            resolve(false);
            return;
          }

          resolve(Boolean(response && response.success));
        });
      });
    }
  }, {
    key: "probeTabReady",
    value: function () {
      var _probeTabReady = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(tabId) {
        var _this4 = this;

        var attempts,
            _loop,
            i,
            _ret,
            _args12 = arguments;

        return _regeneratorRuntime().wrap(function _callee11$(_context12) {
          while (1) {
            switch (_context12.prev = _context12.next) {
              case 0:
                attempts = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : 6;
                _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(i) {
                  return _regeneratorRuntime().wrap(function _loop$(_context11) {
                    while (1) {
                      switch (_context11.prev = _context11.next) {
                        case 0:
                          _context11.next = 2;
                          return _this4.pingOnce(tabId);

                        case 2:
                          if (!_context11.sent) {
                            _context11.next = 4;
                            break;
                          }

                          return _context11.abrupt("return", {
                            v: true
                          });

                        case 4:
                          if (!(i < attempts - 1)) {
                            _context11.next = 7;
                            break;
                          }

                          _context11.next = 7;
                          return new Promise(function (resolve) {
                            var delayName = "signProbe_".concat(tabId, "_").concat(i, "_").concat(++_this4._reqSeq);
                            util["b" /* alarms */].setTimeout(function () {
                              return resolve();
                            }, delayName, 1000);
                          });

                        case 7:
                        case "end":
                          return _context11.stop();
                      }
                    }
                  }, _loop);
                });
                i = 0;

              case 3:
                if (!(i < attempts)) {
                  _context12.next = 11;
                  break;
                }

                return _context12.delegateYield(_loop(i), "t0", 5);

              case 5:
                _ret = _context12.t0;

                if (!(_typeof(_ret) === "object")) {
                  _context12.next = 8;
                  break;
                }

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

              case 8:
                i++;
                _context12.next = 3;
                break;

              case 11:
                return _context12.abrupt("return", false);

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

      function probeTabReady(_x11) {
        return _probeTabReady.apply(this, arguments);
      }

      return probeTabReady;
    }()
  }, {
    key: "verifyAndProbeHost",
    value: function () {
      var _verifyAndProbeHost = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(tabId) {
        var tab;
        return _regeneratorRuntime().wrap(function _callee12$(_context13) {
          while (1) {
            switch (_context13.prev = _context13.next) {
              case 0:
                _context13.prev = 0;
                _context13.next = 3;
                return promisifyTabsGet(tabId);

              case 3:
                tab = _context13.sent;

                if (!(!tab || this.skipTabIds.has(tabId))) {
                  _context13.next = 6;
                  break;
                }

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

              case 6:
                if (!(tab.status === 'complete')) {
                  _context13.next = 8;
                  break;
                }

                return _context13.abrupt("return", this.probeTabReady(tabId));

              case 8:
                _context13.next = 10;
                return this.waitForTabLoad(tabId);

              case 10:
                return _context13.abrupt("return", this.probeTabReady(tabId));

              case 13:
                _context13.prev = 13;
                _context13.t0 = _context13["catch"](0);
                return _context13.abrupt("return", false);

              case 16:
              case "end":
                return _context13.stop();
            }
          }
        }, _callee12, this, [[0, 13]]);
      }));

      function verifyAndProbeHost(_x12) {
        return _verifyAndProbeHost.apply(this, arguments);
      }

      return verifyAndProbeHost;
    }()
  }, {
    key: "markHostBroken",
    value: function markHostBroken(origin, tabId) {
      var _this5 = this;

      var h = this.originHosts.get(origin);
      var wasShared = Boolean(h && h.tabId === tabId && h.source === 'shared-window-tab');

      if (h && h.tabId === tabId) {
        this.originHosts.delete(origin);
      }

      this.skipTabIds.add(tabId);
      setTimeout(function () {
        _this5.skipTabIds.delete(tabId);
      }, 120000);

      if (wasShared) {
        chrome.tabs.remove(tabId).catch(function () {});
      }
    }
  }, {
    key: "_warmOriginHost",
    value: function () {
      var _warmOriginHost2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(origin) {
        var existing, ok, userTab, windowId, tab;
        return _regeneratorRuntime().wrap(function _callee13$(_context14) {
          while (1) {
            switch (_context14.prev = _context14.next) {
              case 0:
                existing = this.originHosts.get(origin);

                if (!(existing !== null && existing !== void 0 && existing.tabId)) {
                  _context14.next = 9;
                  break;
                }

                _context14.next = 4;
                return this.verifyAndProbeHost(existing.tabId);

              case 4:
                ok = _context14.sent;

                if (!ok) {
                  _context14.next = 7;
                  break;
                }

                return _context14.abrupt("return");

              case 7:
                this.originHosts.delete(origin);

                if (existing.source === 'shared-window-tab') {
                  chrome.tabs.remove(existing.tabId).catch(function () {});
                }

              case 9:
                _context14.next = 11;
                return this.findReusableUserTab(origin);

              case 11:
                userTab = _context14.sent;

                if (!userTab) {
                  _context14.next = 21;
                  break;
                }

                _context14.next = 15;
                return this.waitForTabLoad(userTab.id);

              case 15:
                _context14.next = 17;
                return this.probeTabReady(userTab.id);

              case 17:
                if (!_context14.sent) {
                  _context14.next = 20;
                  break;
                }

                this.originHosts.set(origin, {
                  tabId: userTab.id,
                  windowId: userTab.windowId,
                  source: 'user-tab'
                });
                return _context14.abrupt("return");

              case 20:
                this.skipTabIds.add(userTab.id);

              case 21:
                _context14.next = 23;
                return this.ensureSharedWindow(origin);

              case 23:
                windowId = _context14.sent;
                _context14.next = 26;
                return this.findSharedWindowTab(origin, windowId);

              case 26:
                tab = _context14.sent;

                if (tab) {
                  _context14.next = 31;
                  break;
                }

                _context14.next = 30;
                return this.createSharedWindowTab(origin, windowId);

              case 30:
                tab = _context14.sent;

              case 31:
                _context14.next = 33;
                return this.waitForTabLoad(tab.id);

              case 33:
                _context14.next = 35;
                return this.probeTabReady(tab.id);

              case 35:
                if (_context14.sent) {
                  _context14.next = 37;
                  break;
                }

                throw new Error('TikTok signer bridge not ready');

              case 37:
                this.originHosts.set(origin, {
                  tabId: tab.id,
                  windowId: windowId,
                  source: 'shared-window-tab'
                });

              case 38:
              case "end":
                return _context14.stop();
            }
          }
        }, _callee13, this);
      }));

      function _warmOriginHost(_x13) {
        return _warmOriginHost2.apply(this, arguments);
      }

      return _warmOriginHost;
    }()
    /**
     * 确保指定 origin 的宿主页可用
     * @param {string} origin
     */

  }, {
    key: "ensureHostReady",
    value: function () {
      var _ensureHostReady = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(origin) {
        var cached, ok, _h, p, h;

        return _regeneratorRuntime().wrap(function _callee14$(_context15) {
          while (1) {
            switch (_context15.prev = _context15.next) {
              case 0:
                cached = this.originHosts.get(origin);

                if (!(cached !== null && cached !== void 0 && cached.tabId)) {
                  _context15.next = 8;
                  break;
                }

                _context15.next = 4;
                return this.verifyAndProbeHost(cached.tabId);

              case 4:
                ok = _context15.sent;

                if (!ok) {
                  _context15.next = 7;
                  break;
                }

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

              case 7:
                this.originHosts.delete(origin);

              case 8:
                if (!this.originWarmPromises.has(origin)) {
                  _context15.next = 15;
                  break;
                }

                _context15.next = 11;
                return this.originWarmPromises.get(origin);

              case 11:
                _h = this.originHosts.get(origin);

                if (_h) {
                  _context15.next = 14;
                  break;
                }

                throw new Error('Signer host unavailable after warm');

              case 14:
                return _context15.abrupt("return", _h);

              case 15:
                p = this._warmOriginHost(origin);
                this.originWarmPromises.set(origin, p);
                _context15.prev = 17;
                _context15.next = 20;
                return p;

              case 20:
                _context15.prev = 20;
                this.originWarmPromises.delete(origin);
                return _context15.finish(20);

              case 23:
                h = this.originHosts.get(origin);

                if (h) {
                  _context15.next = 26;
                  break;
                }

                throw new Error('Signer host unavailable');

              case 26:
                return _context15.abrupt("return", h);

              case 27:
              case "end":
                return _context15.stop();
            }
          }
        }, _callee14, this, [[17,, 20, 23]]);
      }));

      function ensureHostReady(_x14) {
        return _ensureHostReady.apply(this, arguments);
      }

      return ensureHostReady;
    }()
    /**
     * 初始化：解析 origin 并确保宿主页就绪（可重复调用，按 origin 复用）
     * @param {string} targetUrl - 目标 URL
     */

  }, {
    key: "init",
    value: function () {
      var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15() {
        var targetUrl,
            origin,
            host,
            _args16 = arguments;
        return _regeneratorRuntime().wrap(function _callee15$(_context16) {
          while (1) {
            switch (_context16.prev = _context16.next) {
              case 0:
                targetUrl = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : null;
                _context16.prev = 1;
                origin = this.getOrigin(targetUrl);
                _context16.next = 5;
                return this.ensureHostReady(origin);

              case 5:
                host = _context16.sent;
                this.currentOrigin = origin;
                this.tiktokTabId = host.tabId;
                this.scheduleIdleCloseSharedWindow();
                return _context16.abrupt("return", this);

              case 12:
                _context16.prev = 12;
                _context16.t0 = _context16["catch"](1);
                console.error('[AK-Signer] Init failed:', _context16.t0);
                throw _context16.t0;

              case 16:
              case "end":
                return _context16.stop();
            }
          }
        }, _callee15, this, [[1, 12]]);
      }));

      function init() {
        return _init.apply(this, arguments);
      }

      return init;
    }()
    /**
     * 等待标签页加载完成
     */

  }, {
    key: "waitForTabLoad",
    value: function () {
      var _waitForTabLoad = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee17(tabId) {
        var _this6 = this;

        var count,
            maxCount,
            _args18 = arguments;
        return _regeneratorRuntime().wrap(function _callee17$(_context18) {
          while (1) {
            switch (_context18.prev = _context18.next) {
              case 0:
                count = _args18.length > 1 && _args18[1] !== undefined ? _args18[1] : 0;
                maxCount = _args18.length > 2 && _args18[2] !== undefined ? _args18[2] : 60;

                if (!(count > maxCount)) {
                  _context18.next = 5;
                  break;
                }

                console.error('[AK-Signer] Tab load timeout after', maxCount, 'seconds');
                throw new Error('Tab load timeout');

              case 5:
                return _context18.abrupt("return", new Promise(function (resolve, reject) {
                  util["b" /* alarms */].setTimeout(function () {
                    chrome.tabs.get(tabId, /*#__PURE__*/function () {
                      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(tab) {
                        var result, settleName;
                        return _regeneratorRuntime().wrap(function _callee16$(_context17) {
                          while (1) {
                            switch (_context17.prev = _context17.next) {
                              case 0:
                                _context17.prev = 0;

                                if (tab) {
                                  _context17.next = 5;
                                  break;
                                }

                                console.error('[AK-Signer] Tab was closed during loading');
                                reject(new Error('Tab was closed'));
                                return _context17.abrupt("return");

                              case 5:
                                if (!(tab.status === 'loading')) {
                                  _context17.next = 12;
                                  break;
                                }

                                _context17.next = 8;
                                return _this6.waitForTabLoad(tabId, count + 1, maxCount);

                              case 8:
                                result = _context17.sent;
                                resolve(result);
                                _context17.next = 13;
                                break;

                              case 12:
                                if (tab.status === 'complete') {
                                  settleName = "waitForTabLoadSettle_".concat(tabId, "_").concat(++_this6._reqSeq);
                                  util["b" /* alarms */].setTimeout(function () {
                                    resolve(tab);
                                  }, settleName, 2000);
                                }

                              case 13:
                                _context17.next = 19;
                                break;

                              case 15:
                                _context17.prev = 15;
                                _context17.t0 = _context17["catch"](0);
                                console.error('[AK-Signer] Error checking tab status:', _context17.t0);
                                reject(_context17.t0);

                              case 19:
                              case "end":
                                return _context17.stop();
                            }
                          }
                        }, _callee16, null, [[0, 15]]);
                      }));

                      return function (_x16) {
                        return _ref.apply(this, arguments);
                      };
                    }());
                  }, "waitForTabLoadPoll_".concat(tabId, "_").concat(count, "_").concat(++_this6._reqSeq), 1000);
                }));

              case 6:
              case "end":
                return _context18.stop();
            }
          }
        }, _callee17);
      }));

      function waitForTabLoad(_x15) {
        return _waitForTabLoad.apply(this, arguments);
      }

      return waitForTabLoad;
    }()
  }, {
    key: "getCookies",
    value: function () {
      var _getCookies = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee18() {
        var cookies;
        return _regeneratorRuntime().wrap(function _callee18$(_context19) {
          while (1) {
            switch (_context19.prev = _context19.next) {
              case 0:
                _context19.prev = 0;
                _context19.next = 3;
                return chrome.cookies.getAll({
                  domain: '.tiktok.com'
                });

              case 3:
                cookies = _context19.sent;
                return _context19.abrupt("return", cookies);

              case 7:
                _context19.prev = 7;
                _context19.t0 = _context19["catch"](0);
                console.error('[AK-Signer] Get cookies failed:', _context19.t0);
                return _context19.abrupt("return", []);

              case 11:
              case "end":
                return _context19.stop();
            }
          }
        }, _callee18, null, [[0, 7]]);
      }));

      function getCookies() {
        return _getCookies.apply(this, arguments);
      }

      return getCookies;
    }()
  }, {
    key: "_enqueueTabRequest",
    value: function _enqueueTabRequest(tabId, fn) {
      var prev = this.tabChains.get(tabId) || Promise.resolve();
      var next = prev.then(function () {
        return fn();
      }, function () {
        return fn();
      });
      this.tabChains.set(tabId, next.catch(function () {}));
      return next;
    }
  }, {
    key: "_sendRequestToTabImpl",
    value: function () {
      var _sendRequestToTabImpl2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee21(tabId, _ref2, origin, retried) {
        var _this7 = this;

        var action, _ref2$url, url, _ref2$body, body, _ref2$splited, splited, alarmName;

        return _regeneratorRuntime().wrap(function _callee21$(_context22) {
          while (1) {
            switch (_context22.prev = _context22.next) {
              case 0:
                action = _ref2.action, _ref2$url = _ref2.url, url = _ref2$url === void 0 ? '' : _ref2$url, _ref2$body = _ref2.body, body = _ref2$body === void 0 ? '' : _ref2$body, _ref2$splited = _ref2.splited, splited = _ref2$splited === void 0 ? false : _ref2$splited;
                alarmName = "sendRequest_".concat(++this._reqSeq);
                return _context22.abrupt("return", new Promise(function (resolve, reject) {
                  util["b" /* alarms */].setTimeout( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee19() {
                    return _regeneratorRuntime().wrap(function _callee19$(_context20) {
                      while (1) {
                        switch (_context20.prev = _context20.next) {
                          case 0:
                            try {
                              chrome.alarms.clear(alarmName);
                            } catch (e) {
                              /* ignore */
                            }

                            if (origin != null) {
                              _this7.markHostBroken(origin, tabId);
                            }

                            reject(new Error('Request timeout after 30 seconds'));

                          case 3:
                          case "end":
                            return _context20.stop();
                        }
                      }
                    }, _callee19);
                  })), alarmName, 30000);
                  chrome.tabs.sendMessage(tabId, {
                    type: 'TIKTOK_SIGN_REQUEST',
                    action: action,
                    url: url,
                    body: body,
                    splited: splited
                  }, /*#__PURE__*/function () {
                    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee20(response) {
                      var _chrome$runtime$lastE, msg, host, data, errMsg, _host, _data;

                      return _regeneratorRuntime().wrap(function _callee20$(_context21) {
                        while (1) {
                          switch (_context21.prev = _context21.next) {
                            case 0:
                              try {
                                chrome.alarms.clear(alarmName);
                              } catch (e) {
                                /* ignore */
                              }

                              if (!chrome.runtime.lastError) {
                                _context21.next = 21;
                                break;
                              }

                              msg = ((_chrome$runtime$lastE = chrome.runtime.lastError) === null || _chrome$runtime$lastE === void 0 ? void 0 : _chrome$runtime$lastE.message) || 'sendMessage failed';

                              if (!(origin != null && !retried)) {
                                _context21.next = 19;
                                break;
                              }

                              _this7.markHostBroken(origin, tabId);

                              _context21.prev = 5;
                              _context21.next = 8;
                              return _this7.ensureHostReady(origin);

                            case 8:
                              host = _context21.sent;
                              _context21.next = 11;
                              return _this7._sendRequestToTabImpl(host.tabId, {
                                action: action,
                                url: url,
                                body: body,
                                splited: splited
                              }, origin, true);

                            case 11:
                              data = _context21.sent;
                              resolve(data);
                              _context21.next = 18;
                              break;

                            case 15:
                              _context21.prev = 15;
                              _context21.t0 = _context21["catch"](5);
                              reject(new Error(msg));

                            case 18:
                              return _context21.abrupt("return");

                            case 19:
                              reject(new Error(msg));
                              return _context21.abrupt("return");

                            case 21:
                              if (!(response && response.success)) {
                                _context21.next = 25;
                                break;
                              }

                              resolve(response.data);
                              _context21.next = 43;
                              break;

                            case 25:
                              errMsg = (response === null || response === void 0 ? void 0 : response.error) || "".concat(action, " failed");

                              if (!(origin != null && !retried)) {
                                _context21.next = 42;
                                break;
                              }

                              _this7.markHostBroken(origin, tabId);

                              _context21.prev = 28;
                              _context21.next = 31;
                              return _this7.ensureHostReady(origin);

                            case 31:
                              _host = _context21.sent;
                              _context21.next = 34;
                              return _this7._sendRequestToTabImpl(_host.tabId, {
                                action: action,
                                url: url,
                                body: body,
                                splited: splited
                              }, origin, true);

                            case 34:
                              _data = _context21.sent;
                              resolve(_data);
                              _context21.next = 41;
                              break;

                            case 38:
                              _context21.prev = 38;
                              _context21.t1 = _context21["catch"](28);
                              reject(new Error(errMsg));

                            case 41:
                              return _context21.abrupt("return");

                            case 42:
                              reject(new Error(errMsg));

                            case 43:
                            case "end":
                              return _context21.stop();
                          }
                        }
                      }, _callee20, null, [[5, 15], [28, 38]]);
                    }));

                    return function (_x21) {
                      return _ref4.apply(this, arguments);
                    };
                  }());
                }));

              case 3:
              case "end":
                return _context22.stop();
            }
          }
        }, _callee21, this);
      }));

      function _sendRequestToTabImpl(_x17, _x18, _x19, _x20) {
        return _sendRequestToTabImpl2.apply(this, arguments);
      }

      return _sendRequestToTabImpl;
    }()
  }, {
    key: "sendRequest",
    value: function sendRequest(_ref5) {
      var _this8 = this;

      var action = _ref5.action,
          _ref5$url = _ref5.url,
          url = _ref5$url === void 0 ? '' : _ref5$url,
          _ref5$body = _ref5.body,
          body = _ref5$body === void 0 ? '' : _ref5$body,
          _ref5$splited = _ref5.splited,
          splited = _ref5$splited === void 0 ? false : _ref5$splited,
          originOpt = _ref5.origin;
      var origin = originOpt != null ? originOpt : url ? this.getOrigin(url) : this.currentOrigin;

      if (!origin) {
        return Promise.reject(new Error('Signer origin unknown'));
      }

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee22() {
        var _yield$_this8$ensureH, tabId, result;

        return _regeneratorRuntime().wrap(function _callee22$(_context23) {
          while (1) {
            switch (_context23.prev = _context23.next) {
              case 0:
                _context23.prev = 0;
                _context23.next = 3;
                return _this8.ensureHostReady(origin);

              case 3:
                _yield$_this8$ensureH = _context23.sent;
                tabId = _yield$_this8$ensureH.tabId;
                _context23.next = 7;
                return _this8._enqueueTabRequest(tabId, function () {
                  return _this8._sendRequestToTabImpl(tabId, {
                    action: action,
                    url: url,
                    body: body,
                    splited: splited
                  }, origin, false);
                });

              case 7:
                result = _context23.sent;

                _this8.scheduleIdleCloseSharedWindow();

                return _context23.abrupt("return", result);

              case 12:
                _context23.prev = 12;
                _context23.t0 = _context23["catch"](0);

                _this8.scheduleIdleCloseSharedWindow();

                throw _context23.t0;

              case 16:
              case "end":
                return _context23.stop();
            }
          }
        }, _callee22, null, [[0, 12]]);
      }))();
    }
  }, {
    key: "closeTab",
    value: function () {
      var _closeTab = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee23() {
        return _regeneratorRuntime().wrap(function _callee23$(_context24) {
          while (1) {
            switch (_context24.prev = _context24.next) {
              case 0:
                if (!this.tiktokTabId) {
                  _context24.next = 11;
                  break;
                }

                _context24.prev = 1;
                _context24.next = 4;
                return chrome.tabs.remove(this.tiktokTabId);

              case 4:
                _context24.next = 8;
                break;

              case 6:
                _context24.prev = 6;
                _context24.t0 = _context24["catch"](1);

              case 8:
                _context24.prev = 8;
                this.tiktokTabId = null;
                return _context24.finish(8);

              case 11:
              case "end":
                return _context24.stop();
            }
          }
        }, _callee23, this, [[1, 6, 8, 11]]);
      }));

      function closeTab() {
        return _closeTab.apply(this, arguments);
      }

      return closeTab;
    }()
  }, {
    key: "navigator",
    value: function () {
      var _navigator = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee24() {
        var origin;
        return _regeneratorRuntime().wrap(function _callee24$(_context25) {
          while (1) {
            switch (_context25.prev = _context25.next) {
              case 0:
                _context25.prev = 0;
                origin = this.currentOrigin || 'https://www.tiktok.com';
                _context25.next = 4;
                return this.sendRequest({
                  action: 'navigator',
                  url: '',
                  body: '',
                  splited: false,
                  origin: origin
                });

              case 4:
                return _context25.abrupt("return", _context25.sent);

              case 7:
                _context25.prev = 7;
                _context25.t0 = _context25["catch"](0);
                console.error('[AK-Signer] Get navigator failed:', _context25.t0);
                return _context25.abrupt("return", {
                  deviceScaleFactor: 1,
                  userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                  browser_language: 'en-US',
                  browser_platform: 'Win32',
                  browser_name: 'Mozilla',
                  browser_version: '5.0'
                });

              case 11:
              case "end":
                return _context25.stop();
            }
          }
        }, _callee24, this, [[0, 7]]);
      }));

      function navigator() {
        return _navigator.apply(this, arguments);
      }

      return navigator;
    }()
  }, {
    key: "ensureTabReady",
    value: function () {
      var _ensureTabReady = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee25() {
        var targetUrl,
            _args26 = arguments;
        return _regeneratorRuntime().wrap(function _callee25$(_context26) {
          while (1) {
            switch (_context26.prev = _context26.next) {
              case 0:
                targetUrl = _args26.length > 0 && _args26[0] !== undefined ? _args26[0] : null;
                _context26.next = 3;
                return this.init(targetUrl);

              case 3:
              case "end":
                return _context26.stop();
            }
          }
        }, _callee25, this);
      }));

      function ensureTabReady() {
        return _ensureTabReady.apply(this, arguments);
      }

      return ensureTabReady;
    }()
  }, {
    key: "Sign",
    value: function () {
      var _Sign = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee26(url) {
        var body,
            splited,
            origin,
            _args27 = arguments;
        return _regeneratorRuntime().wrap(function _callee26$(_context27) {
          while (1) {
            switch (_context27.prev = _context27.next) {
              case 0:
                body = _args27.length > 1 && _args27[1] !== undefined ? _args27[1] : '';
                splited = _args27.length > 2 && _args27[2] !== undefined ? _args27[2] : false;
                _context27.prev = 2;
                origin = this.getOrigin(url);
                _context27.next = 6;
                return this.sendRequest({
                  action: 'sign',
                  url: url,
                  body: body,
                  splited: splited,
                  origin: origin
                });

              case 6:
                return _context27.abrupt("return", _context27.sent);

              case 9:
                _context27.prev = 9;
                _context27.t0 = _context27["catch"](2);
                console.error('[AK-Signer] Sign failed:', _context27.t0);
                throw _context27.t0;

              case 13:
              case "end":
                return _context27.stop();
            }
          }
        }, _callee26, this, [[2, 9]]);
      }));

      function Sign(_x22) {
        return _Sign.apply(this, arguments);
      }

      return Sign;
    }()
  }, {
    key: "generateXBogus",
    value: function () {
      var _generateXBogus = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee27(url) {
        var origin;
        return _regeneratorRuntime().wrap(function _callee27$(_context28) {
          while (1) {
            switch (_context28.prev = _context28.next) {
              case 0:
                _context28.prev = 0;
                origin = this.getOrigin(url);
                _context28.next = 4;
                return this.sendRequest({
                  action: 'xbogus',
                  url: url,
                  body: '',
                  splited: false,
                  origin: origin
                });

              case 4:
                return _context28.abrupt("return", _context28.sent);

              case 7:
                _context28.prev = 7;
                _context28.t0 = _context28["catch"](0);
                console.error('[AK-Signer] Generate X-Bogus failed:', _context28.t0);
                throw _context28.t0;

              case 11:
              case "end":
                return _context28.stop();
            }
          }
        }, _callee27, this, [[0, 7]]);
      }));

      function generateXBogus(_x23) {
        return _generateXBogus.apply(this, arguments);
      }

      return generateXBogus;
    }()
  }, {
    key: "generateXGnarly",
    value: function () {
      var _generateXGnarly = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee28(url) {
        var body,
            origin,
            bodyStr,
            _args29 = arguments;
        return _regeneratorRuntime().wrap(function _callee28$(_context29) {
          while (1) {
            switch (_context29.prev = _context29.next) {
              case 0:
                body = _args29.length > 1 && _args29[1] !== undefined ? _args29[1] : '';
                _context29.prev = 1;
                origin = this.getOrigin(url);
                bodyStr = body && _typeof(body) === 'object' ? JSON.stringify(body) : String(body || '');
                _context29.next = 6;
                return this.sendRequest({
                  action: 'xgnarly',
                  url: url,
                  body: bodyStr,
                  splited: false,
                  origin: origin
                });

              case 6:
                return _context29.abrupt("return", _context29.sent);

              case 9:
                _context29.prev = 9;
                _context29.t0 = _context29["catch"](1);
                console.error('[AK-Signer] Generate X-Gnarly failed:', _context29.t0);
                throw _context29.t0;

              case 13:
              case "end":
                return _context29.stop();
            }
          }
        }, _callee28, this, [[1, 9]]);
      }));

      function generateXGnarly(_x24) {
        return _generateXGnarly.apply(this, arguments);
      }

      return generateXGnarly;
    }()
  }, {
    key: "close",
    value: function () {
      var _close = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee29() {
        return _regeneratorRuntime().wrap(function _callee29$(_context30) {
          while (1) {
            switch (_context30.prev = _context30.next) {
              case 0:
                if (this.port) {
                  this.port.disconnect();
                  this.port = null;
                }

                try {
                  chrome.alarms.clear(SIGNER_IDLE_ALARM, function () {});
                } catch (e) {
                  /* ignore */
                }

                _context30.next = 4;
                return this.closeSharedWindowOnly();

              case 4:
                this.originHosts.clear();
                this.tabChains.clear();
                this.tiktokTabId = null;
                this.currentOrigin = null;
                console.log('[AK-Signer] Cleaned up');

              case 9:
              case "end":
                return _context30.stop();
            }
          }
        }, _callee29, this);
      }));

      function close() {
        return _close.apply(this, arguments);
      }

      return close;
    }()
  }]);

  return Signer;
}();

/* harmony default export */ var signer = (signer_Signer);
// CONCATENATED MODULE: ./src/platform/tiktok/xGnarly/inedx.js
function inedx_typeof(obj) { "@babel/helpers - typeof"; return inedx_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; }, inedx_typeof(obj); }

function inedx_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ inedx_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" == inedx_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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { inedx_defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function inedx_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function inedx_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function inedx_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { inedx_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { inedx_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }


var enableMock = false;

if (['test', 'development'].includes("production")) {
  var mockModule = __webpack_require__("245a");

  enableMock = mockModule.enableMock || false;
} // 创建全局单例


var inedx_signer = new signer();
/**
 * 签名参数
 * @param {object} data - 签名数据
 * @param {string} data.url - API URL
 * @param {object} data.params - URL 参数
 * @param {object} data.body - 请求体（可选）
 * @param {boolean} data.splited - 是否返回分离的签名值（可选）
 * @returns {Promise<object>} 签名结果
 */

function signParams(_x) {
  return _signParams.apply(this, arguments);
}
/**
 * 直接签名 URL（快捷方法）
 * @param {string} url - 完整 URL
 * @param {string|object} body - 请求体（可选）
 * @param {boolean} splited - 是否返回分离的值
 * @returns {Promise<string|object>} 签名结果
 */

function _signParams() {
  _signParams = inedx_asyncToGenerator( /*#__PURE__*/inedx_regeneratorRuntime().mark(function _callee(data) {
    var queryString, unsignedUrl, navigator, userAgent, body, signResult;
    return inedx_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            // 构建查询字符串
            queryString = new URLSearchParams(_objectSpread({}, data.params)).toString(); // 构建完整 URL

            unsignedUrl = data.url.includes('?') ? "".concat(data.url, "&").concat(queryString) : "".concat(data.url, "?").concat(queryString); // 初始化签名器（传入目标 URL 以确定打开哪个域名的标签页）

            _context.next = 5;
            return inedx_signer.init(unsignedUrl);

          case 5:
            _context.next = 7;
            return inedx_signer.navigator();

          case 7:
            navigator = _context.sent;
            userAgent = navigator.userAgent; // 处理请求体

            body = '';

            if (data.body) {
              body = typeof data.body === 'string' ? data.body : JSON.stringify(data.body);
            } // 执行签名


            _context.next = 13;
            return inedx_signer.Sign(unsignedUrl, body, data.splited || false);

          case 13:
            signResult = _context.sent;

            if (!data.splited) {
              _context.next = 16;
              break;
            }

            return _context.abrupt("return", {
              signature: signResult,
              userAgent: userAgent,
              navigator: navigator
            });

          case 16:
            return _context.abrupt("return", {
              signature: {
                signedUrl: signResult
              },
              userAgent: userAgent,
              navigator: navigator
            });

          case 19:
            _context.prev = 19;
            _context.t0 = _context["catch"](0);
            console.error('[signParams] Error:', _context.t0);
            throw _context.t0;

          case 23:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 19]]);
  }));
  return _signParams.apply(this, arguments);
}

function signUrl(_x2) {
  return _signUrl.apply(this, arguments);
}
/**
 * 生成 X-Bogus
 * @param {string} url - 完整 URL
 * @returns {Promise<string>} X-Bogus 值
 */

function _signUrl() {
  _signUrl = inedx_asyncToGenerator( /*#__PURE__*/inedx_regeneratorRuntime().mark(function _callee2(url) {
    var body,
        splited,
        _args2 = arguments;
    return inedx_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            body = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : '';
            splited = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : false;
            return _context2.abrupt("return", inedx_signer.Sign(url, body, splited));

          case 3:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _signUrl.apply(this, arguments);
}

function generateXBogus(_x3) {
  return _generateXBogus.apply(this, arguments);
}
/**
 * 生成 X-Gnarly
 * @param {string} url - 完整 URL
 * @param {string|object} body - 请求体
 * @returns {Promise<string>} X-Gnarly 值
 */

function _generateXBogus() {
  _generateXBogus = inedx_asyncToGenerator( /*#__PURE__*/inedx_regeneratorRuntime().mark(function _callee3(url) {
    return inedx_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            return _context3.abrupt("return", inedx_signer.generateXBogus(url));

          case 1:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _generateXBogus.apply(this, arguments);
}

function generateXGnarly(_x4) {
  return _generateXGnarly.apply(this, arguments);
}
/**
 * 获取签名器实例
 */

function _generateXGnarly() {
  _generateXGnarly = inedx_asyncToGenerator( /*#__PURE__*/inedx_regeneratorRuntime().mark(function _callee4(url) {
    var body,
        _args4 = arguments;
    return inedx_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            body = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : '';

            if (!enableMock) {
              _context4.next = 5;
              break;
            }

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

          case 5:
            return _context4.abrupt("return", inedx_signer.generateXGnarly(url, body));

          case 6:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));
  return _generateXGnarly.apply(this, arguments);
}

function getSigner() {
  return inedx_signer;
}
/* harmony default export */ var inedx = ({
  signParams: signParams,
  signUrl: signUrl,
  generateXBogus: generateXBogus,
  generateXGnarly: generateXGnarly,
  getSigner: getSigner
});

/***/ }),

/***/ "6b26":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"2af3f160-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/popup/App/MultiPlatform/Task.vue?vue&type=template&id=f3b451f4&scoped=true&
var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"task-contain"},[_c('div',{staticClass:"title"},[_c('div',{staticClass:"get-task"},[_c('span',{staticClass:"suspend-btn"},[_vm._v("\n        获取任务：\n        "),_c('el-radio-group',{on:{"change":_vm.handleDialogVisible},model:{value:(_vm.statusRadio),callback:function ($$v) {_vm.statusRadio=$$v},expression:"statusRadio"}},[_c('el-radio',{attrs:{"label":1,"disabled":_vm.dialogVisible}},[_vm._v("开启")]),_c('el-radio',{attrs:{"label":0,"disabled":_vm.dialogVisible}},[_vm._v("暂停")])],1)],1)]),_c('div',[_c('span',{staticClass:"refresh-btn",on:{"click":function($event){return _vm.$emit('changePage','temuCustom')}}},[_vm._v("自定义获取")])]),_c('div',{staticStyle:{"font-size":"12px","margin-left":"10px"}},[_c('span',[_vm._v("注：当前服务器下发任务时间已调整到晚上9:00至早上9:00，请保持浏览器开启。如需立即获取点击【"),_c('span',{staticClass:"refresh-btn",staticStyle:{"margin-right":"8px"},on:{"click":_vm.imfre}},[_vm._v("立即获取")]),_vm._v("】")])])]),_c('div',{staticClass:"ak-pd-left-8 ak-pd-right-8 task-wrap"},[(_vm.reportTasks && _vm.reportTasks.length)?[_c('div',{staticClass:"task-list",style:({'max-height': _vm.offlineTips ? '330px' : '360px'})},_vm._l((_vm.reportTasks),function(item){return _c('div',{key:item.task_id},[_c('transition',{attrs:{"name":"el-zoom-in-top"}},[(_vm.multiTskHandleMap[item.type_id] && _vm.multiTskHandleMap[item.type_id].component)?_c('div',{staticClass:"task-item"},[_c(_vm.multiTskHandleMap[item.type_id].component,{tag:"component",attrs:{"task":item,"reportType":_vm.multiTskHandleMap[item.type_id].name}}),(item.status == 0 && !item.isRun)?_c('span',{staticClass:"el-icon-close",on:{"click":function($event){return _vm.deleteTask(item)}}}):_vm._e()],1):_vm._e()])],1)}),0)]:_c('div',{staticClass:"seller-contain"},[_c('div',{directives:[{name:"show",rawName:"v-show",value:(_vm.showTopTip && _vm.refreshTime>0),expression:"showTopTip && refreshTime>0"}],staticClass:"top-tip"},[_vm._v("\n        "+_vm._s(Math.round(_vm.refreshTime / 1000))+"秒后再点击获取哦~\n      ")]),_c('img',{attrs:{"src":__webpack_require__("e04f")}}),_c('p',{directives:[{name:"show",rawName:"v-show",value:(!_vm.hasRefresh),expression:"!hasRefresh"}]},[_vm._v("暂无报告获取记录")]),_c('p',{directives:[{name:"show",rawName:"v-show",value:(_vm.hasRefresh),expression:"hasRefresh"}]},[_vm._v("暂时没有可以获取的报告哦~")]),_c('span',{directives:[{name:"show",rawName:"v-show",value:(!_vm.hasRefresh),expression:"!hasRefresh"}],staticClass:"text-btn",on:{"click":_vm.refresh}},[_vm._v("立即获取")])])],2),_c('el-dialog',{attrs:{"visible":_vm.dialogVisible,"show-close":false,"center":true,"width":"70%","title":"获取任务","top":"30vh","custom-class":"dialog-class","close-on-click-modal":false,"close-on-press-escape":false},on:{"update:visible":function($event){_vm.dialogVisible=$event}}},[_c('span',{staticClass:"dialog-content"},[_vm._v("确认"+_vm._s(_vm.statusRadio ? '开启' : '暂停')+"获取当前任务")]),_c('span',{staticClass:"dialog-footer",attrs:{"slot":"footer"},slot:"footer"},[_c('el-button',{attrs:{"size":"small","plain":""},on:{"click":function($event){return _vm.handleDialogFooter('cancel')}}},[_vm._v("取 消")]),_c('el-button',{attrs:{"size":"small","type":"primary"},on:{"click":function($event){return _vm.handleDialogFooter('confirm')}}},[_vm._v("确 定")])],1)])],1)}
var staticRenderFns = []


// CONCATENATED MODULE: ./src/popup/App/MultiPlatform/Task.vue?vue&type=template&id=f3b451f4&scoped=true&

// EXTERNAL MODULE: ./src/utils/util.js
var util = __webpack_require__("ca00");

// EXTERNAL MODULE: ./src/config.js
var config = __webpack_require__("db49");

// EXTERNAL MODULE: ./src/platform/common/taskType.js + 27 modules
var taskType = __webpack_require__("2f79");

// CONCATENATED MODULE: ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/thread-loader/dist/cjs.js!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??vue-loader-options!./src/popup/App/MultiPlatform/Task.vue?vue&type=script&lang=js&
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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
var timer;



/* harmony default export */ var Taskvue_type_script_lang_js_ = ({
  name: 'task',
  props: {
    offlineTips: {
      type: Boolean,
      default: false
    }
  },
  components: {
    SupplierPrice: function SupplierPrice() {
      return __webpack_require__.e(/* import() */ "chunk-42908338").then(__webpack_require__.bind(null, "4918"));
    },
    SaleVolume: function SaleVolume() {
      return __webpack_require__.e(/* import() */ "chunk-0be301f2").then(__webpack_require__.bind(null, "c042"));
    },
    ReverseReport: function ReverseReport() {
      return __webpack_require__.e(/* import() */ "chunk-41aa9416").then(__webpack_require__.bind(null, "6515"));
    }
  },
  computed: {
    reportTasks: function reportTasks() {
      return this.taskList ? this.taskList.filter(function (_ref) {
        var isDelete = _ref.isDelete;
        return !isDelete;
      }) : [];
    },
    taskList: {
      set: function set(val) {
        var multiPlatformData = this.$bg.multiPlatform;
        multiPlatformData.multiPlatformTaskInstance && (multiPlatformData.multiPlatformTaskInstance = val);
      },
      get: function get() {
        var multiPlatformTaskInstance = this.$bg.multiPlatform && this.$bg.multiPlatform.multiPlatformTaskInstance;
        return multiPlatformTaskInstance && multiPlatformTaskInstance.taskList;
      }
    }
  },
  data: function data() {
    return {
      multiTskHandleMap: taskType["b" /* multiTskHandleMap */],
      hasRefresh: false,
      refreshTime: 0,
      showTopTip: false,
      statusList: config["l" /* statusList */],
      statusRadio: 1,
      dialogVisible: false
    };
  },
  methods: {
    handleDialogVisible: function handleDialogVisible() {
      var _this = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
        return _regeneratorRuntime().wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this.dialogVisible = true;

              case 1:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }))();
    },
    deleteTask: function deleteTask(task) {
      var _this2 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
        var res;
        return _regeneratorRuntime().wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return Object(util["m" /* gatePost */])("api/mp/delTask", {
                  task_id: task.task_id
                }, 'task').catch(function () {});

              case 2:
                res = _context2.sent;

                if (res && res.code === 0) {
                  // 火狐浏览器需要将原列表状态改变
                  // if (isFirefox()) {
                  //   this.$bg.task.taskList.forEach(item => {
                  //     if (item.task_id === task.task_id) item.isDelete = true
                  //   })
                  // }
                  chrome.runtime.sendMessage({
                    type: 'deleteTask',
                    params: {
                      taskId: task.task_id,
                      platform: 'temu'
                    }
                  }, function () {});

                  _this2.$message.success({
                    showClose: true,
                    message: '删除成功',
                    duration: 1000
                  });
                } else {
                  _this2.$message.error({
                    showClose: true,
                    message: res ? res.msg : '删除失败',
                    duration: 3000
                  });
                }

              case 4:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }))();
    },
    // 立即刷新
    imfre: function imfre() {
      var _this3 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
        return _regeneratorRuntime().wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                // 停止中断
                _this3.statusRadio = 1;
                Object(util["J" /* suspend */])(1);

                _this3.getMainData();

              case 3:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }))();
    },

    /**
     * @description 立即执行主任务
     */
    getMainData: function getMainData() {
      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
        return _regeneratorRuntime().wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                chrome.runtime.sendMessage({
                  type: 'getTaskList',
                  params: {
                    platform: 'temu'
                  }
                }, function () {});

              case 1:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4);
      }))();
    },
    refresh: function refresh() {
      var _this4 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
        var type, _yield$localStorage$g, refresh;

        return _regeneratorRuntime().wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                if (!(_this4.refreshTime > 0)) {
                  _context5.next = 3;
                  break;
                }

                _this4.showTopTip = true;
                return _context5.abrupt("return");

              case 3:
                // 停止中断
                _this4.statusRadio = 1;
                Object(util["J" /* suspend */])(1);
                type = 1;
                _context5.next = 8;
                return util["y" /* localStorage */].getItem(['refresh']);

              case 8:
                _yield$localStorage$g = _context5.sent;
                refresh = _yield$localStorage$g.refresh;

                if (!refresh) {
                  type = 3;
                  util["y" /* localStorage */].setItem({
                    refresh: 1
                  });
                }

                chrome.runtime.sendMessage({
                  type: 'getTaskList',
                  params: {
                    platform: 'temu'
                  }
                }, function () {
                  _this4.hasRefresh = true;
                  _this4.refreshTime = 60 * 1000;
                  util["y" /* localStorage */].setItem({
                    refresh_time: Date.now()
                  });
                  timer = setInterval(function () {
                    _this4.refreshTime -= 200;
                    if (_this4.refreshTime < 0) clearInterval(timer);
                  }, 200);
                  setTimeout(function () {
                    _this4.hasRefresh = false;
                  }, 1000 * 3);
                });

              case 12:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5);
      }))();
    },
    // dialog按钮回调
    handleDialogFooter: function handleDialogFooter(type) {
      this.dialogVisible = false;

      if (type === 'cancel') {
        this.statusRadio = this.statusRadio ? 0 : 1;
        return;
      } // 开启执行，触发任务调度


      if (this.statusRadio) {
        var _type = {
          amazon: 'goExecute',
          temu: 'goExecuteTemu'
        }[this.$root.platform];
        chrome.runtime.sendMessage({
          type: _type
        }, function () {});
      } // 如果是中断则设置一年有效期


      Object(util["J" /* suspend */])(this.statusRadio ? 1 : 60 * 1000 * 60 * 24 * 365, '99', 'popup');
    }
  },
  created: function created() {
    var _this5 = this;

    return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
      var multiPlatform, _yield$localStorage$g2, refresh_time, ctime, suspendStatus;

      return _regeneratorRuntime().wrap(function _callee6$(_context6) {
        while (1) {
          switch (_context6.prev = _context6.next) {
            case 0:
              if (_this5.$root.platform === 'amazon') {
                if (!_this5.$bg.amazon.sellerId) {
                  _this5.$emit('changePage', 'no-seller');
                }
              } else {
                multiPlatform = _this5.$bg.multiPlatform || {};

                if (!multiPlatform.storeInfo || !multiPlatform.storeInfo.length) {
                  _this5.$emit('changePage', 'no-seller');
                }
              }

              _context6.next = 3;
              return util["y" /* localStorage */].getItem(['refresh_time']);

            case 3:
              _yield$localStorage$g2 = _context6.sent;
              refresh_time = _yield$localStorage$g2.refresh_time;

              if (refresh_time) {
                ctime = 60 * 1000 - (Date.now() - refresh_time);
                _this5.refreshTime = ctime < 0 ? 0 : ctime;
              } // 初始化中断状态


              _context6.next = 8;
              return Object(util["J" /* suspend */])();

            case 8:
              suspendStatus = _context6.sent;
              _this5.statusRadio = suspendStatus ? 0 : 1;

            case 10:
            case "end":
              return _context6.stop();
          }
        }
      }, _callee6);
    }))();
  }
});
// CONCATENATED MODULE: ./src/popup/App/MultiPlatform/Task.vue?vue&type=script&lang=js&
 /* harmony default export */ var MultiPlatform_Taskvue_type_script_lang_js_ = (Taskvue_type_script_lang_js_); 
// EXTERNAL MODULE: ./src/popup/App/MultiPlatform/Task.vue?vue&type=style&index=0&id=f3b451f4&lang=scss&scoped=true&
var Taskvue_type_style_index_0_id_f3b451f4_lang_scss_scoped_true_ = __webpack_require__("ff24");

// EXTERNAL MODULE: ./node_modules/vue-loader/lib/runtime/componentNormalizer.js
var componentNormalizer = __webpack_require__("2877");

// CONCATENATED MODULE: ./src/popup/App/MultiPlatform/Task.vue






/* normalize component */

var component = Object(componentNormalizer["a" /* default */])(
  MultiPlatform_Taskvue_type_script_lang_js_,
  render,
  staticRenderFns,
  false,
  null,
  "f3b451f4",
  null
  
)

/* harmony default export */ var Task = __webpack_exports__["default"] = (component.exports);

/***/ }),

/***/ "a1d0":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ multiPlatform; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ multiPlatformInit; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* binding */ common_multiPlatformInitTask; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* binding */ multiPlatformInitSite; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* binding */ multiPlatformOnlineSite; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ multiPlatformChangeSite; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* binding */ common_multiPlatformTaskClear; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ common_multiPlatformClear; });

// EXTERNAL MODULE: ./src/data/task.js
var data_task = __webpack_require__("cec6");

// EXTERNAL MODULE: ./src/utils/util.js
var util = __webpack_require__("ca00");

// EXTERNAL MODULE: ./src/data/log.js
var log = __webpack_require__("6b23");

// EXTERNAL MODULE: ./src/utils/event.js
var utils_event = __webpack_require__("42a5");

// EXTERNAL MODULE: ./src/utils/websocket.js
var websocket = __webpack_require__("b2eb");

// EXTERNAL MODULE: ./src/config.js
var config = __webpack_require__("db49");

// EXTERNAL MODULE: ./src/platform/common/newTask.js
var newTask = __webpack_require__("5e61");

// EXTERNAL MODULE: ./src/platform/temu/index.js
var temu = __webpack_require__("c04e");

// EXTERNAL MODULE: ./node_modules/axios/index.js
var axios = __webpack_require__("bc3a");
var axios_default = /*#__PURE__*/__webpack_require__.n(axios);

// EXTERNAL MODULE: ./src/platform/tiktok/utils/index.js
var utils = __webpack_require__("ba27");

// CONCATENATED MODULE: ./src/platform/tiktok/index.js
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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





var tiktok = {
  // 跨境账号信息 - 可能有些接口传参会用到
  cbAccountInfo: {},
  // 跨境Host - 商家中心（目前按所有跨境站点域名通用来做）
  cbShopHosts: {
    GLOBAL: 'https://seller.tiktokshopglobalselling.com',
    US: 'https://seller.us.tiktokshopglobalselling.com',
    EU: 'https://seller.eu.tiktokshopglobalselling.com'
  },
  // 跨境host - 联盟中心
  cbUsAffiliateHost: 'https://affiliate.tiktokshopglobalselling.com',
  // 站点区域映射
  siteRegionMap: {
    US: 'US',
    MX: 'US',
    CA: 'US',
    UK: 'EU',
    GB: 'EU',
    DE: 'EU',
    FR: 'EU',
    IT: 'EU',
    ES: 'EU',
    NL: 'EU',
    SE: 'EU',
    PL: 'EU',
    AE: 'EU',
    SA: 'EU',
    TR: 'EU',
    BE: 'EU',
    IE: 'EU',
    EG: 'EU',
    MY: 'GLOBAL',
    JP: 'GLOBAL',
    VN: 'GLOBAL',
    TH: 'GLOBAL',
    SG: 'GLOBAL'
  },
  // 已登录的跨境域名
  isLoginGlobalHost: {},
  // 是否是获取联盟中心数据的任务
  getAffiliateDataTask: [30001, 30002, 30003, 30004, 30005, 30006],

  /**
   * 当前所处跨境站点
   * @property {number} activate_current_todo_step - 当前激活的待办步骤
   * @property {number} business_type - 业务类型
   * @property {string} global_shop_name - 全球店铺名称
   * @property {boolean} is_activate_todo_finish - 激活待办是否完成
   * @property {object} logo - 店铺logo信息
   * @property {string} region_code - 区域代码
   * @property {number} seller_condition - 卖家状态
   * @property {string} seller_id - 卖家ID
   * @property {number} seller_type - 卖家类型
   * @property {string} shop_code - 店铺代码
   * @property {string} shop_name - 店铺名称
   * @property {string} shop_region - 店铺区域
   * @property {number} shop_status - 店铺状态
   * @property {number} status - 状态
   * @property {number} test_flag - 测试标记
   * @property {object} timezone - 时区信息
   */
  currentCbSite: {},

  /**
   * 跨境店铺信息
   * @property {string} is_new - 未知
   * @property {number} region - 站点区域code
   * @property {string} region_name - 国家英文名
   * @property {Array<number>} seller_id - 店铺id
   * @property {object} shop_status - 未知
   * 下面是插件用于展示的字段
   * @property {string} storeType - 店铺类型  跨境
   * @property {boolean} isSemiManagedMall - 是否是半托管
   * @property {string} mallId - 店铺ID
   * @property {string} mallName - 店铺名称
   */
  cbStoreInfo: [],
  // 本土账号信息
  localAccountInfo: {},
  // 本土店铺信息 - 字段与跨境一样
  localStoreInfo: [],
  // 当前所在本土店铺信息 - 字段与跨境一样
  currentLocalSite: {},
  // 本土host
  localHost: {
    US: 'https://seller-us.tiktok.com',
    MX: 'https://seller-mx.tiktok.com',
    BR: 'https://seller-br.tiktok.com',
    PH: 'https://seller-ph.tiktok.com',
    SG: 'https://seller-sg.tiktok.com',
    TH: 'https://seller-th.tiktok.com',
    VN: 'https://seller-vn.tiktok.com',
    ID: 'https://seller-id.tiktok.com',
    MY: 'https://seller-my.tiktok.com',
    JP: 'https://seller-jp.tiktok.com',
    DE: 'https://seller-de.tiktok.com',
    FR: 'https://seller-fr.tiktok.com',
    ES: 'https://seller-es.tiktok.com',
    IE: 'https://seller-ie.tiktok.com',
    IT: 'https://seller-it.tiktok.com',
    UK: 'https://seller-uk.tiktok.com',
    GB: 'https://seller-uk.tiktok.com'
  },
  // 本土联盟中心域名
  localAffiliateHost: {
    US: 'https://affiliate-us.tiktok.com',
    MX: 'https://affiliate.tiktok.com',
    BR: 'https://affiliate.tiktok.com',
    PH: 'https://affiliate.tiktok.com',
    SG: 'https://affiliate.tiktok.com',
    TH: 'https://affiliate.tiktok.com',
    VN: 'https://affiliate.tiktok.com',
    ID: 'https://affiliate.tiktok.com',
    MY: 'https://affiliate.tiktok.com',
    JP: 'https://affiliate.tiktok.com',
    DE: 'https://affiliate.tiktok.com',
    FR: 'https://affiliate.tiktok.com',
    ES: 'https://affiliate.tiktok.com',
    IE: 'https://affiliate.tiktok.com',
    IT: 'https://affiliate.tiktok.com',
    UK: 'https://affiliate.tiktok.com',
    GB: 'https://affiliate.tiktok.com'
  },
  // 已登录的本土域名
  isLoginLocalHost: {}
};
/**
 * @description 清除店铺信息
 */

var clearStoreInfo = function clearStoreInfo() {
  tiktok.cbStoreInfo = [];
  tiktok.isLoginGlobalHost = {};
  tiktok.currentCbSite = {};
  tiktok.cbAccountInfo = {};
  tiktok.localStoreInfo = [];
  tiktok.isLoginLocalHost = {};
  tiktok.currentLocalSite = {};
  tiktok.localAccountInfo = {};
};
/**
 * @description tk检测站点
*/


var tiktokCheckSite = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
    var cbStoreInfo, localStoreInfo;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            clearStoreInfo();
            _context.next = 4;
            return checkTiktokCbInfo();

          case 4:
            cbStoreInfo = _context.sent;
            _context.next = 7;
            return checkTiktokLocalInfo();

          case 7:
            localStoreInfo = _context.sent;

            if ((cbStoreInfo === null || cbStoreInfo === void 0 ? void 0 : cbStoreInfo.length) > 0) {
              tiktok.cbStoreInfo = Object(util["K" /* unique */])(cbStoreInfo, 'mallId');
            }

            if ((localStoreInfo === null || localStoreInfo === void 0 ? void 0 : localStoreInfo.length) > 0) {
              tiktok.localStoreInfo = Object(util["K" /* unique */])(localStoreInfo, 'mallId');
            }

            return _context.abrupt("return", [].concat(_toConsumableArray(tiktok.cbStoreInfo), _toConsumableArray(tiktok.localStoreInfo)).map(function (_ref2) {
              var mallId = _ref2.mallId;
              return mallId;
            }));

          case 13:
            _context.prev = 13;
            _context.t0 = _context["catch"](0);
            log["a" /* default */].report("tiktok\u68C0\u6D4B\u7AD9\u70B9\u62A5\u9519,\u89C4\u5219\u53EF\u80FD\u5DF2\u6539\u53D8---".concat(Object(util["u" /* isError */])(_context.t0)), 'error');
            return _context.abrupt("return", false);

          case 17:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 13]]);
  }));

  return function tiktokCheckSite() {
    return _ref.apply(this, arguments);
  };
}();
/**
 * @description 检测tiktok跨境信息
 */

var checkTiktokCbInfo = /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
    var _storeInfo$sellerList, accountInfo, storeInfo;

    return _regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            _context2.next = 3;
            return getCbAccountInfo();

          case 3:
            accountInfo = _context2.sent;

            if (accountInfo) {
              _context2.next = 7;
              break;
            }

            log["a" /* default */].getLog('获取tiktok跨境账号信息失败');
            return _context2.abrupt("return", false);

          case 7:
            tiktok.cbAccountInfo = accountInfo.data;
            _context2.next = 10;
            return checkTiktokCb(accountInfo.host);

          case 10:
            storeInfo = _context2.sent;

            if (storeInfo) {
              _context2.next = 14;
              break;
            }

            log["a" /* default */].getLog('检测tiktok跨境店铺信息失败');
            return _context2.abrupt("return", false);

          case 14:
            if (!((storeInfo === null || storeInfo === void 0 ? void 0 : (_storeInfo$sellerList = storeInfo.sellerList) === null || _storeInfo$sellerList === void 0 ? void 0 : _storeInfo$sellerList.length) > 0)) {
              _context2.next = 17;
              break;
            }

            tiktok.currentCbSite = storeInfo.seller;
            return _context2.abrupt("return", storeInfo.sellerList.map(function (item) {
              var _storeInfo$seller;

              return _objectSpread(_objectSpread({}, item), {}, {
                mallId: item.seller_id,
                mallName: (_storeInfo$seller = storeInfo.seller) === null || _storeInfo$seller === void 0 ? void 0 : _storeInfo$seller.shop_name,
                isSemiManagedMall: true,
                storeType: '跨境'
              });
            }));

          case 17:
            _context2.next = 23;
            break;

          case 19:
            _context2.prev = 19;
            _context2.t0 = _context2["catch"](0);
            log["a" /* default */].report("\u68C0\u6D4Btiktok\u8DE8\u5883\u5E97\u94FA\u4FE1\u606F\u62A5\u9519---".concat(Object(util["u" /* isError */])(_context2.t0)), 'error');
            return _context2.abrupt("return", false);

          case 23:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 19]]);
  }));

  return function checkTiktokCbInfo() {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * @description 检测跨境店铺是否在线，在线则返回店铺信息
 */


var checkTiktokCb = /*#__PURE__*/function () {
  var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(host) {
    var _yield$axios, data, _data$data, seller, global_seller, errorMsg;

    return _regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return axios_default()({
              url: "".concat(host, "/api/v3/seller/common/get"),
              method: 'get'
            });

          case 3:
            _yield$axios = _context3.sent;
            data = _yield$axios.data;

            if (!(data && data.code === 0)) {
              _context3.next = 8;
              break;
            }

            _data$data = data.data, seller = _data$data.seller, global_seller = _data$data.global_seller; // 暂时只支持获取一个账号店铺

            return _context3.abrupt("return", {
              sellerList: (global_seller === null || global_seller === void 0 ? void 0 : global_seller.seller_map) || [],
              seller: seller
            });

          case 8:
            _context3.next = 14;
            break;

          case 10:
            _context3.prev = 10;
            _context3.t0 = _context3["catch"](0);
            errorMsg = Object(util["u" /* isError */])(_context3.t0);

            if (errorMsg.indexOf('403') > -1) {
              log["a" /* default */].setLog("\u68C0\u6D4Btiktok\u8DE8\u5883\u7AD9\u70B9\u672A\u767B\u5F55");
            } else {
              log["a" /* default */].setLog("\u68C0\u6D4Btiktok\u8DE8\u5883\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));
            }

          case 14:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 10]]);
  }));

  return function checkTiktokCb(_x) {
    return _ref4.apply(this, arguments);
  };
}();
/**
 * @description 跨境 - 获取账号信息
 */

var getCbAccountInfo = /*#__PURE__*/function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
    var _i, _Object$entries, _Object$entries$_i, site, host, _yield$axios2, data, errorMsg;

    return _regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _i = 0, _Object$entries = Object.entries(tiktok.cbShopHosts);

          case 2:
            if (!(_i < _Object$entries.length)) {
              _context4.next = 14;
              break;
            }

            _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), site = _Object$entries$_i[0], host = _Object$entries$_i[1];
            _context4.next = 6;
            return axios_default()({
              url: "".concat(host, "/passport/account/info/v2/"),
              method: 'get'
            });

          case 6:
            _yield$axios2 = _context4.sent;
            data = _yield$axios2.data;

            if (!(data && data.message === 'success')) {
              _context4.next = 11;
              break;
            }

            // 记录已登录的域名
            tiktok.isLoginGlobalHost[site] = host;
            return _context4.abrupt("return", {
              data: data.data,
              host: host
            });

          case 11:
            _i++;
            _context4.next = 2;
            break;

          case 14:
            _context4.next = 20;
            break;

          case 16:
            _context4.prev = 16;
            _context4.t0 = _context4["catch"](0);
            errorMsg = Object(util["u" /* isError */])(_context4.t0);

            if (errorMsg.indexOf('403') > -1) {
              log["a" /* default */].setLog("\u83B7\u53D6tiktok\u8DE8\u5883\u8D26\u53F7\u4FE1\u606F\u672A\u767B\u5F55");
            } else {
              log["a" /* default */].setLog("\u83B7\u53D6tiktok\u8DE8\u5883\u8D26\u53F7\u4FE1\u606F\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));
            }

          case 20:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 16]]);
  }));

  return function getCbAccountInfo() {
    return _ref5.apply(this, arguments);
  };
}();
/**
 * @description 切换站点 - 跨境
 */


var changeCbSite = /*#__PURE__*/function () {
  var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(host, code) {
    var _yield$axios3, data;

    return _regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            _context5.prev = 0;
            _context5.next = 3;
            return axios_default()({
              url: "".concat(host, "?shop_region=").concat(code),
              method: 'get'
            });

          case 3:
            _yield$axios3 = _context5.sent;
            data = _yield$axios3.data;
            return _context5.abrupt("return", true);

          case 8:
            _context5.prev = 8;
            _context5.t0 = _context5["catch"](0);
            log["a" /* default */].setLog("\u5207\u6362tiktok\u8DE8\u5883\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----".concat(Object(util["u" /* isError */])(_context5.t0)));
            return _context5.abrupt("return", false);

          case 12:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[0, 8]]);
  }));

  return function changeCbSite(_x2, _x3) {
    return _ref6.apply(this, arguments);
  };
}();
/**
 * @description 切换语言 - 跨境商家中心
 */


var changeCbLanguage = /*#__PURE__*/function () {
  var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(host) {
    var _yield$axios4, data;

    return _regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;
            _context6.next = 3;
            return axios_default()({
              url: "".concat(host, "/homepage?lng=en"),
              method: 'get'
            });

          case 3:
            _yield$axios4 = _context6.sent;
            data = _yield$axios4.data;
            return _context6.abrupt("return", true);

          case 8:
            _context6.prev = 8;
            _context6.t0 = _context6["catch"](0);
            log["a" /* default */].setLog("\u5207\u6362tiktok\u8DE8\u5883\u8BED\u8A00\u8BF7\u6C42\u62A5\u9519-----".concat(Object(util["u" /* isError */])(_context6.t0)));
            return _context6.abrupt("return", false);

          case 12:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[0, 8]]);
  }));

  return function changeCbLanguage(_x4) {
    return _ref7.apply(this, arguments);
  };
}();
/**
 * @description 切换语言 - 跨境联盟中心
 */


var changeCbAffiliateLanguage = /*#__PURE__*/function () {
  var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(task) {
    var query, _yield$tkPost, code, message;

    return _regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            _context7.next = 2;
            return Object(utils["a" /* getQueryString */])(task);

          case 2:
            query = _context7.sent;

            if (query) {
              _context7.next = 5;
              break;
            }

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

          case 5:
            _context7.prev = 5;
            _context7.next = 8;
            return Object(utils["c" /* tkPost */])("".concat(tiktok.cbUsAffiliateHost, "/api/v1/seller/account/update"), query, {
              account: {
                default_locale: 'en'
              }
            });

          case 8:
            _yield$tkPost = _context7.sent;
            code = _yield$tkPost.code;
            message = _yield$tkPost.message;

            if (!(code === 0)) {
              _context7.next = 15;
              break;
            }

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

          case 15:
            log["a" /* default */].setLog("\u5207\u6362tiktok\u8DE8\u5883\u8054\u76DF\u4E2D\u5FC3\u8BED\u8A00\u5931\u8D25-----".concat(message));

          case 16:
            return _context7.abrupt("return", false);

          case 19:
            _context7.prev = 19;
            _context7.t0 = _context7["catch"](5);
            log["a" /* default */].setLog("\u5207\u6362tiktok\u8DE8\u5883\u8054\u76DF\u4E2D\u5FC3\u8BED\u8A00\u8BF7\u6C42\u62A5\u9519-----".concat(Object(util["u" /* isError */])(_context7.t0)));
            return _context7.abrupt("return", false);

          case 23:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7, null, [[5, 19]]);
  }));

  return function changeCbAffiliateLanguage(_x5) {
    return _ref8.apply(this, arguments);
  };
}();
/**
 * @description 本土 - 获取账号信息
 */


var getLocalAccountInfo = /*#__PURE__*/function () {
  var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
    var _i2, _Object$entries2, _Object$entries2$_i, site, host, _yield$axios5, data, errorMsg;

    return _regeneratorRuntime().wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            _context8.prev = 0;
            _i2 = 0, _Object$entries2 = Object.entries(tiktok.localHost);

          case 2:
            if (!(_i2 < _Object$entries2.length)) {
              _context8.next = 14;
              break;
            }

            _Object$entries2$_i = _slicedToArray(_Object$entries2[_i2], 2), site = _Object$entries2$_i[0], host = _Object$entries2$_i[1];
            _context8.next = 6;
            return axios_default()({
              url: "".concat(host, "/passport/account/info/v2/"),
              method: 'get'
            });

          case 6:
            _yield$axios5 = _context8.sent;
            data = _yield$axios5.data;

            if (!(data && data.message === 'success')) {
              _context8.next = 11;
              break;
            }

            // 记录已登录的域名
            tiktok.isLoginLocalHost[site] = host;
            return _context8.abrupt("return", {
              data: data.data,
              host: host
            });

          case 11:
            _i2++;
            _context8.next = 2;
            break;

          case 14:
            _context8.next = 20;
            break;

          case 16:
            _context8.prev = 16;
            _context8.t0 = _context8["catch"](0);
            errorMsg = Object(util["u" /* isError */])(_context8.t0);

            if (errorMsg.indexOf('403') > -1) {
              log["a" /* default */].setLog("\u83B7\u53D6tiktok\u672C\u571F\u8D26\u53F7\u4FE1\u606F\u672A\u767B\u5F55");
            } else {
              log["a" /* default */].setLog("\u83B7\u53D6tiktok\u672C\u571F\u8D26\u53F7\u4FE1\u606F\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));
            }

          case 20:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee8, null, [[0, 16]]);
  }));

  return function getLocalAccountInfo() {
    return _ref9.apply(this, arguments);
  };
}();
/**
 * 检测tiktok本土信息
 */


var checkTiktokLocalInfo = /*#__PURE__*/function () {
  var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
    var _storeInfo$sellerList2, accountInfo, storeInfo;

    return _regeneratorRuntime().wrap(function _callee9$(_context9) {
      while (1) {
        switch (_context9.prev = _context9.next) {
          case 0:
            _context9.prev = 0;
            _context9.next = 3;
            return getLocalAccountInfo();

          case 3:
            accountInfo = _context9.sent;

            if (accountInfo) {
              _context9.next = 7;
              break;
            }

            log["a" /* default */].getLog('获取tiktok本土账号信息失败');
            return _context9.abrupt("return", false);

          case 7:
            tiktok.localAccountInfo = accountInfo.data;
            _context9.next = 10;
            return checkTiktokLocal(accountInfo.host);

          case 10:
            storeInfo = _context9.sent;

            if (storeInfo) {
              _context9.next = 14;
              break;
            }

            log["a" /* default */].getLog('检测tiktok本土店铺信息失败');
            return _context9.abrupt("return", false);

          case 14:
            if (!((storeInfo === null || storeInfo === void 0 ? void 0 : (_storeInfo$sellerList2 = storeInfo.sellerList) === null || _storeInfo$sellerList2 === void 0 ? void 0 : _storeInfo$sellerList2.length) > 0)) {
              _context9.next = 17;
              break;
            }

            tiktok.currentLocalSite = storeInfo.seller;
            return _context9.abrupt("return", storeInfo.sellerList.map(function (item) {
              var _storeInfo$seller2;

              return _objectSpread(_objectSpread({}, item), {}, {
                mallId: item.seller_id,
                mallName: (_storeInfo$seller2 = storeInfo.seller) === null || _storeInfo$seller2 === void 0 ? void 0 : _storeInfo$seller2.shop_name,
                isSemiManagedMall: true,
                storeType: '本土'
              });
            }));

          case 17:
            _context9.next = 23;
            break;

          case 19:
            _context9.prev = 19;
            _context9.t0 = _context9["catch"](0);
            log["a" /* default */].report("\u68C0\u6D4Btiktok\u672C\u571F\u5E97\u94FA\u4FE1\u606F\u62A5\u9519---".concat(Object(util["u" /* isError */])(_context9.t0)), 'error');
            return _context9.abrupt("return", false);

          case 23:
          case "end":
            return _context9.stop();
        }
      }
    }, _callee9, null, [[0, 19]]);
  }));

  return function checkTiktokLocalInfo() {
    return _ref10.apply(this, arguments);
  };
}();
/**
 * @description 检测本土店铺是否在线，在线则返回店铺信息
 */


var checkTiktokLocal = /*#__PURE__*/function () {
  var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(host) {
    var _yield$axios6, data, _data$data2, global_seller, seller, errorMsg;

    return _regeneratorRuntime().wrap(function _callee10$(_context10) {
      while (1) {
        switch (_context10.prev = _context10.next) {
          case 0:
            _context10.prev = 0;
            _context10.next = 3;
            return axios_default()({
              url: "".concat(host, "/api/v3/seller/common/get"),
              method: 'get'
            });

          case 3:
            _yield$axios6 = _context10.sent;
            data = _yield$axios6.data;

            if (!(data && data.code === 0)) {
              _context10.next = 8;
              break;
            }

            _data$data2 = data.data, global_seller = _data$data2.global_seller, seller = _data$data2.seller; // 暂时只支持获取一个账号店铺

            return _context10.abrupt("return", {
              sellerList: (global_seller === null || global_seller === void 0 ? void 0 : global_seller.seller_map) || [],
              seller: seller
            });

          case 8:
            _context10.next = 14;
            break;

          case 10:
            _context10.prev = 10;
            _context10.t0 = _context10["catch"](0);
            errorMsg = Object(util["u" /* isError */])(_context10.t0);

            if (errorMsg.indexOf('403') > -1) {
              log["a" /* default */].setLog("\u68C0\u6D4Btiktok\u672C\u571F\u7AD9\u70B9\u672A\u767B\u5F55");
            } else {
              log["a" /* default */].setLog("\u68C0\u6D4Btiktok\u672C\u571F\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));
            }

          case 14:
          case "end":
            return _context10.stop();
        }
      }
    }, _callee10, null, [[0, 10]]);
  }));

  return function checkTiktokLocal(_x6) {
    return _ref11.apply(this, arguments);
  };
}();
/**
 * @description 本土 - 切换站点
 */

var changeLocalSite = /*#__PURE__*/function () {
  var _ref12 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(task) {
    var fp, query, _yield$tkPost2, code, message;

    return _regeneratorRuntime().wrap(function _callee11$(_context11) {
      while (1) {
        switch (_context11.prev = _context11.next) {
          case 0:
            _context11.prev = 0;

            if (!task.isAffiliate) {
              _context11.next = 5;
              break;
            }

            _context11.next = 4;
            return changeLocalAffiliateSite(task);

          case 4:
            return _context11.abrupt("return", _context11.sent);

          case 5:
            _context11.next = 7;
            return Object(util["p" /* getCookies */])({
              url: task.host,
              name: 's_v_web_id'
            });

          case 7:
            fp = _context11.sent;
            _context11.next = 10;
            return Object(utils["a" /* getQueryString */])(task, {
              fp: (fp === null || fp === void 0 ? void 0 : fp.value) || ''
            });

          case 10:
            query = _context11.sent;

            if (query) {
              _context11.next = 13;
              break;
            }

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

          case 13:
            _context11.next = 15;
            return Object(utils["c" /* tkPost */])("".concat(task.host, "/api/v1/seller/seller_map/read"), query);

          case 15:
            _yield$tkPost2 = _context11.sent;
            code = _yield$tkPost2.code;
            message = _yield$tkPost2.message;

            if (!(code === 0)) {
              _context11.next = 22;
              break;
            }

            return _context11.abrupt("return", true);

          case 22:
            log["a" /* default */].setLog("tiktok\u672C\u571F\u5207\u6362\u7AD9\u70B9\u5931\u8D25-----".concat(message));

          case 23:
            return _context11.abrupt("return", false);

          case 26:
            _context11.prev = 26;
            _context11.t0 = _context11["catch"](0);
            log["a" /* default */].setLog("\u5207\u6362tiktok\u672C\u571F\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----".concat(Object(util["u" /* isError */])(_context11.t0)));
            return _context11.abrupt("return", false);

          case 30:
          case "end":
            return _context11.stop();
        }
      }
    }, _callee11, null, [[0, 26]]);
  }));

  return function changeLocalSite(_x7) {
    return _ref12.apply(this, arguments);
  };
}();
/**
 * @description 切换本土联盟中心站点
 */


var changeLocalAffiliateSite = /*#__PURE__*/function () {
  var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(task) {
    var fp, query, _yield$tkGet, code, message;

    return _regeneratorRuntime().wrap(function _callee12$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            _context12.prev = 0;
            _context12.next = 3;
            return Object(util["p" /* getCookies */])({
              url: task.host,
              name: 's_v_web_id'
            });

          case 3:
            fp = _context12.sent;
            _context12.next = 6;
            return Object(utils["a" /* getQueryString */])(task, {
              global_seller_id: task.platform_store_id,
              seller_id: task.platform_store_id,
              version: 3,
              fp: (fp === null || fp === void 0 ? void 0 : fp.value) || ''
            });

          case 6:
            query = _context12.sent;

            if (query) {
              _context12.next = 9;
              break;
            }

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

          case 9:
            _context12.next = 11;
            return Object(utils["b" /* tkGet */])("".concat(task.host, "/api/v3/seller/common/get"), query);

          case 11:
            _yield$tkGet = _context12.sent;
            code = _yield$tkGet.code;
            message = _yield$tkGet.message;

            if (!(code === 0)) {
              _context12.next = 18;
              break;
            }

            return _context12.abrupt("return", true);

          case 18:
            log["a" /* default */].setLog("\u5207\u6362tiktok\u672C\u571F\u8054\u76DF\u4E2D\u5FC3\u7AD9\u70B9\u5931\u8D25-----".concat(message));

          case 19:
            return _context12.abrupt("return", false);

          case 22:
            _context12.prev = 22;
            _context12.t0 = _context12["catch"](0);
            log["a" /* default */].setLog("\u5207\u6362tiktok\u672C\u571F\u8054\u76DF\u4E2D\u5FC3\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----".concat(Object(util["u" /* isError */])(_context12.t0)));
            return _context12.abrupt("return", false);

          case 26:
          case "end":
            return _context12.stop();
        }
      }
    }, _callee12, null, [[0, 22]]);
  }));

  return function changeLocalAffiliateSite(_x8) {
    return _ref13.apply(this, arguments);
  };
}();
/**
 * @description 切换站点、语言 - 对外
 */


var changeCbSiteAndLanguage = /*#__PURE__*/function () {
  var _ref14 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(task) {
    var store_type, site_name, site, _checkRes$seller, _checkRes$seller$shop, changeSiteRes, checkRes, _checkRes$seller2;

    return _regeneratorRuntime().wrap(function _callee13$(_context13) {
      while (1) {
        switch (_context13.prev = _context13.next) {
          case 0:
            // store_type: GLOBAL：跨境  LOCAL：本土；
            // appType：0:非美国站；1：美国本土站（非美籍受益人）；2：美国本土站（美籍受益人）；3、美国跨境站 4 本土欧区
            // site_name: 各国code 美国: US
            // 由于还不知道tk跨境如何切换站点，所以只支持美国跨境店铺
            store_type = task.store_type, site_name = task.site_name;
            site = site_name.toLocaleUpperCase(); // task.isAffiliate = tiktok.getAffiliateDataTask.includes(+task.type_id)

            if (!(store_type === 'GLOBAL')) {
              _context13.next = 9;
              break;
            }

            // task.host = task.isAffiliate ? tiktok.cbUsAffiliateHost : tiktok.cbShopHosts[tiktok.siteRegionMap[site]]
            // if (!task.host) {
            //   task.msg = '当前不支持站点: ' + site
            //   log.setLog(task.msg)
            //   return false
            // }
            // 切换站点
            // log.setLog('开始切换站点')
            // const changeSiteRes = await changeCbSite(task.host, site)
            // if (!changeSiteRes) {
            //   task.msg = '切换tiktok跨境站点失败'
            //   log.setLog(task.msg)
            //   return false
            // }
            // log.setLog(`站点已切换至:${site}`)
            task.timezone_name = tiktok.currentCbSite && tiktok.currentCbSite.timezone.name;
            task.aid = tiktok.cbAccountInfo && tiktok.cbAccountInfo.app_id;
            task.shop_region = site; // 切换语言
            // if (task.isAffiliate) {
            //   await changeCbLanguage(task.host)
            // } else {
            //   await changeCbAffiliateLanguage(task)
            // }

            return _context13.abrupt("return", true);

          case 9:
            // 处理本土店铺
            // task.host = tiktok.isAffiliate ? tiktok.localAffiliateHost : tiktok.localHost[site]
            // if (!task.host) {
            //   task.msg = '当前不支持站点: ' + site
            //   log.setLog(task.msg)
            //   return false
            // }
            // 切换站点
            log["a" /* default */].setLog('开始切换站点');
            _context13.next = 12;
            return changeLocalSite(task);

          case 12:
            changeSiteRes = _context13.sent;

            if (changeSiteRes) {
              _context13.next = 17;
              break;
            }

            task.msg = '切换tiktok本土站点失败';
            log["a" /* default */].setLog(task.msg);
            return _context13.abrupt("return", false);

          case 17:
            log["a" /* default */].setLog("\u7AD9\u70B9\u5DF2\u5207\u6362\u81F3:".concat(site)); // 检测是否切换成功

            _context13.next = 20;
            return checkTiktokLocal(task.host);

          case 20:
            checkRes = _context13.sent;

            if (!(!checkRes || ((_checkRes$seller = checkRes.seller) === null || _checkRes$seller === void 0 ? void 0 : (_checkRes$seller$shop = _checkRes$seller.shop_region) === null || _checkRes$seller$shop === void 0 ? void 0 : _checkRes$seller$shop.toLocaleUpperCase()) !== site)) {
              _context13.next = 25;
              break;
            }

            task.msg = "tiktok\u672C\u571F\u7AD9\u70B9\u672A\u5207\u6362\u6210\u529F\uFF0C\u5F53\u524D\u7AD9\u70B9-".concat((_checkRes$seller2 = checkRes.seller) === null || _checkRes$seller2 === void 0 ? void 0 : _checkRes$seller2.shop_region, ",\u76EE\u6807\u7AD9\u70B9-").concat(site);
            log["a" /* default */].setLog(task.msg);
            return _context13.abrupt("return", false);

          case 25:
            tiktok.currentLocalSite = checkRes.seller;
            task.timezone_name = tiktok.currentLocalSite && tiktok.currentLocalSite.timezone.name;
            task.aid = tiktok.localAccountInfo && tiktok.localAccountInfo.app_id;
            task.shop_region = site;
            return _context13.abrupt("return", true);

          case 30:
          case "end":
            return _context13.stop();
        }
      }
    }, _callee13);
  }));

  return function changeCbSiteAndLanguage(_x9) {
    return _ref14.apply(this, arguments);
  };
}();
// EXTERNAL MODULE: ./src/platform/mercado/index.js
var mercado = __webpack_require__("e38f");

// CONCATENATED MODULE: ./src/platform/common/index.js
function common_typeof(obj) { "@babel/helpers - typeof"; return common_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; }, common_typeof(obj); }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = common_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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function common_toConsumableArray(arr) { return common_arrayWithoutHoles(arr) || common_iterableToArray(arr) || common_unsupportedIterableToArray(arr) || common_nonIterableSpread(); }

function common_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function common_unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return common_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 common_arrayLikeToArray(o, minLen); }

function common_iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function common_arrayWithoutHoles(arr) { if (Array.isArray(arr)) return common_arrayLikeToArray(arr); }

function common_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; }

function common_regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ common_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" == common_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 common_asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function common_asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { common_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { common_asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }












var multiPlatform = {
  refreshing: false,
  // 店铺信息
  storeInfo: [],
  // 用于显示在弹窗上的店铺信息
  storeInfoOfExhibition: [],
  // 平台code
  platformCode: '',
  // 多平台任务管理实例
  multiPlatformTaskInstance: null,
  // 离线店铺
  offlineSite: [],
  // 任务类型
  taskTypes: [],
  // 任务类型映射
  taskTypesMap: {},
  // 定时任务是否开启
  enableTimerTask: 1,
  // 店铺唯一id Map
  storeIdMap: {},
  // tk轮询定时时长（分）
  tkPollingTime: 1,
  // 其他平台轮询定时时长（分）
  otherPollingTime: 5
};

var getTaskType = /*#__PURE__*/function () {
  var _ref = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee() {
    var _yield$gatePost$catch, code, data;

    return common_regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.prev = 0;
            _context.next = 3;
            return Object(util["m" /* gatePost */])('api/mp/getTaskTypes', {
              platform_code: multiPlatform.platformCode
            }, 'task').catch(function () {});

          case 3:
            _yield$gatePost$catch = _context.sent;
            code = _yield$gatePost$catch.code;
            data = _yield$gatePost$catch.data;

            if (code === 0) {
              multiPlatform.taskTypes = data.sort(function (a, b) {
                return b.priority - a.priority;
              });
              multiPlatform.taskTypesMap = {};
              multiPlatform.taskTypes.forEach(function (item) {
                item.list = [];
                multiPlatform.taskTypesMap[item.taskTypeId] = item;
              });
            }

            _context.next = 12;
            break;

          case 9:
            _context.prev = 9;
            _context.t0 = _context["catch"](0);
            log["a" /* default */].setLog('获取任务类型失败', Object(util["u" /* isError */])(_context.t0));

          case 12:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[0, 9]]);
  }));

  return function getTaskType() {
    return _ref.apply(this, arguments);
  };
}();

var multiPlatformInit = /*#__PURE__*/function () {
  var _ref2 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee2() {
    var count,
        status,
        _args2 = arguments;
    return common_regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            count = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : 0;
            // 先取消重试定时器，防止用户点击刷新时重复调用
            chrome.alarms.clear('multiPlatformInit'); // 检测版本

            Object(util["c" /* checkVersion */])(); // 检测插件是否可用

            _context2.next = 5;
            return data_task["b" /* default */].checkEnable();

          case 5:
            status = _context2.sent;
            util["y" /* localStorage */].setItem({
              enableObj: {
                status: status
              }
            }); // 检测定时任务是否开启

            checkEnableTimerTask(); // 检测店铺

            _context2.next = 10;
            return multiPlatformInitSite();

          case 10:
            // 获取任务类型
            getTaskType();

            if (multiPlatform.storeInfo && multiPlatform.storeInfo.length) {
              common_multiPlatformInitTask();
            } else if (count < 3) {
              // 未检测到店铺时，重试三次
              util["b" /* alarms */].setTimeout(function () {
                log["a" /* default */].setLog("[\u68C0\u6D4B\u7AD9\u70B9]\u91CD\u8BD5\u7B2C".concat(count + 1, "\u6B21"));
                multiPlatformInit(++count);
              }, 'multiPlatformInit', 10 * 1000);
            }

          case 12:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));

  return function multiPlatformInit() {
    return _ref2.apply(this, arguments);
  };
}();
var common_multiPlatformInitTask = function multiPlatformInitTask() {
  if (multiPlatform.multiPlatformTaskInstance) return; // 连接websocket

  var storeIds = multiPlatform.storeInfo.map(function (item) {
    return "".concat(multiPlatform.platformCode, ":").concat(item);
  }).join(',');
  websocket["a" /* default */].init(storeIds); // 心跳检测

  checkHeartbeat(); // 初始化task实例

  multiPlatform.multiPlatformTaskInstance = new newTask["a" /* default */](); // 监听推送

  Object(utils_event["b" /* monitor */])('ReceivePush', receivePush);
  Object(utils_event["b" /* monitor */])('GoExecuteTemu', goExecuteTemu); // 设置轮询

  setTimerLoop();
};
/**
   * @description 接收推送调度
   */

function receivePush(data) {
  if (multiPlatform.multiPlatformTaskInstance && (!data || !data.content || !data.content.platform_code)) return;
  log["a" /* default */].setLog('[多平台]task.js接收到推送类型', data.type);

  switch (data.type) {
    case 6:
      multiPlatform.multiPlatformTaskInstance.initTaskList([data.content]);
      break;
    // case 8: this.handleDelete(data.content)
    // break

    case 10:
      multiPlatform.multiPlatformTaskInstance.getTaskList();
      break;
    // case 20: if (data.content == 0) task.clearAutoTaskList()
  }
}
/**
 * @description 任务恢复执行
 */


function goExecuteTemu() {
  log["a" /* default */].setLog('GoExecuteTemu');
  multiPlatform.multiPlatformTaskInstance.taskSchedule();
}

var common_getCheckSiteHandle = function getCheckSiteHandle() {
  var platform = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : multiPlatform.platformCode;
  return {
    10022: temu["i" /* temuCheckSite */],
    tiktok: tiktokCheckSite,
    mercado: mercado["d" /* mercadoCheckSite */]
  }[platform]();
};
/**
 * @description 初始化-检测平台所有店铺
 */


var multiPlatformInitSite = /*#__PURE__*/function () {
  var _ref3 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee3() {
    var _yield$localStorage$g, platform, online;

    return common_regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.next = 2;
            return util["y" /* localStorage */].getItem(['platform']);

          case 2:
            _yield$localStorage$g = _context3.sent;
            platform = _yield$localStorage$g.platform;

            if (!multiPlatform.refreshing) {
              _context3.next = 9;
              break;
            }

            log["a" /* default */].setLog('正在检测站点');
            return _context3.abrupt("return", 'refreshing');

          case 9:
            multiPlatform.refreshing = true;

          case 10:
            multiPlatform.platformCode = config["i" /* platformCodeMap */][platform];
            _context3.t0 = platform;
            _context3.next = _context3.t0 === 'temu' ? 14 : _context3.t0 === 'tiktok' ? 22 : _context3.t0 === 'mercado' ? 30 : 38;
            break;

          case 14:
            _context3.next = 16;
            return common_getCheckSiteHandle();

          case 16:
            _context3.t1 = _context3.sent;

            if (_context3.t1) {
              _context3.next = 19;
              break;
            }

            _context3.t1 = [];

          case 19:
            multiPlatform.storeInfo = _context3.t1;
            multiPlatform.storeInfoOfExhibition = [].concat(common_toConsumableArray(temu["h" /* temu */].cbStoreInfo), common_toConsumableArray(temu["h" /* temu */].localStoreInfo));
            return _context3.abrupt("break", 38);

          case 22:
            _context3.next = 24;
            return common_getCheckSiteHandle();

          case 24:
            _context3.t2 = _context3.sent;

            if (_context3.t2) {
              _context3.next = 27;
              break;
            }

            _context3.t2 = [];

          case 27:
            multiPlatform.storeInfo = _context3.t2;
            multiPlatform.storeInfoOfExhibition = [].concat(common_toConsumableArray(tiktok.cbStoreInfo), common_toConsumableArray(tiktok.localStoreInfo));
            return _context3.abrupt("break", 38);

          case 30:
            _context3.next = 32;
            return common_getCheckSiteHandle();

          case 32:
            _context3.t3 = _context3.sent;

            if (_context3.t3) {
              _context3.next = 35;
              break;
            }

            _context3.t3 = [];

          case 35:
            multiPlatform.storeInfo = _context3.t3;
            multiPlatform.storeInfoOfExhibition = [].concat(common_toConsumableArray(mercado["c" /* mercado */].cbStoreInfo), common_toConsumableArray(mercado["c" /* mercado */].localStoreInfo));
            return _context3.abrupt("break", 38);

          case 38:
            // 清除离线店铺
            multiPlatform.offlineSite = [];
            log["a" /* default */].setLog('检测到站点----', JSON.stringify(multiPlatform.storeInfo));
            multiPlatform.refreshing = false;
            online = !!multiPlatform.storeInfo.length;
            return _context3.abrupt("return", online);

          case 43:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));

  return function multiPlatformInitSite() {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * @description 执行任务时 - 检测店铺是否在线
 * @returns onlineSiteStatus: 判断店铺是否在线 1: 在线 2: 离线 3: 店铺id不一致,账号可能已被切换
 * @returns mall 当前检测到的店铺id or 店铺名
 */

var multiPlatformOnlineSite = /*#__PURE__*/function () {
  var _ref4 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee4(task) {
    var res, _storeInfo$, platform_store_id, storeInfo, find, _storeInfo$2, _storeInfo, _find, _temu$localStoreInfo$, region, taskMallInfo, checkLocalHandle, _storeInfo2, mallInfo, checked, _platform_store_id, store_type, site_name, _region, host, _yield$checkTiktokCb, sellerList, _find2, site, _host, _yield$checkTiktokLoc, _sellerList, _find3, _storeInfo3, _find4, _taskMallInfo, _region2, _storeInfo4, _checked, msg;

    return common_regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            res = {};
            _context4.t0 = +task.platform_code;
            _context4.next = _context4.t0 === 10022 ? 5 : _context4.t0 === 10024 ? 14 : _context4.t0 === 10011 ? 53 : _context4.t0 === 10032 ? 82 : _context4.t0 === 10012 ? 84 : 105;
            break;

          case 5:
            platform_store_id = task.platform_store_id;
            task.host = temu["h" /* temu */].globalHostOfTypeId.includes(+task.type_id) ? temu["h" /* temu */].cbGlobalHost : temu["h" /* temu */].cbHost;
            task.real_mall_id = Object(temu["f" /* getRealMallId */])(platform_store_id); // 跨境

            _context4.next = 10;
            return Object(temu["b" /* checkTemuCb */])();

          case 10:
            storeInfo = _context4.sent;
            // 店铺校准
            find = storeInfo && storeInfo.find(function (_ref5) {
              var mallId = _ref5.mallId,
                  uniqueId = _ref5.uniqueId;
              return mallId == platform_store_id || uniqueId == platform_store_id;
            });
            res = {
              onlineSiteStatus: storeInfo ? find ? 1 : 3 : 2,
              storeType: 'global',
              mall: find ? find.mallId : storeInfo === null || storeInfo === void 0 ? void 0 : (_storeInfo$ = storeInfo[0]) === null || _storeInfo$ === void 0 ? void 0 : _storeInfo$.mallId
            };
            return _context4.abrupt("break", 105);

          case 14:
            task.real_mall_id = Object(temu["f" /* getRealMallId */])(task.platform_store_id);

            if (!(task.store_type === 'GLOBAL')) {
              _context4.next = 24;
              break;
            }

            // 跨境
            task.host = temu["h" /* temu */].globalHostOfTypeId.includes(+task.type_id) ? temu["h" /* temu */].cbGlobalHost : temu["h" /* temu */].cbHost;
            _context4.next = 19;
            return Object(temu["b" /* checkTemuCb */])();

          case 19:
            _storeInfo = _context4.sent;
            // 店铺校准
            _find = _storeInfo && _storeInfo.find(function (_ref6) {
              var mallId = _ref6.mallId,
                  uniqueId = _ref6.uniqueId;
              return mallId == task.platform_store_id || uniqueId == task.platform_store_id;
            });
            res = {
              onlineSiteStatus: _storeInfo ? _find ? 1 : 3 : 2,
              storeType: 'global',
              mall: _find ? _find.mallId : _storeInfo === null || _storeInfo === void 0 ? void 0 : (_storeInfo$2 = _storeInfo[0]) === null || _storeInfo$2 === void 0 ? void 0 : _storeInfo$2.mallId
            };
            _context4.next = 52;
            break;

          case 24:
            region = task.area.toLowerCase();

            if (!(task.area === 'GLOBAL')) {
              _context4.next = 34;
              break;
            }

            // 全球其他本土
            taskMallInfo = temu["h" /* temu */].localStoreInfo.find(function (_ref7) {
              var mallId = _ref7.mallId;
              return mallId == task.platform_store_id;
            });

            if (taskMallInfo) {
              _context4.next = 30;
              break;
            }

            log["a" /* default */].setLog("\u672A\u627E\u5230mallId\u4E3A".concat(task.platform_store_id, "\u7684\u5E97\u94FA\u4FE1\u606F"));
            return _context4.abrupt("return", {
              msg: "\u591A\u5E73\u53F0\u68C0\u6D4B\u5E97\u94FA\u662F\u5426\u5728\u7EBF\u5931\u8D25----\u672A\u77E5\u5E97\u94FA:".concat(task.platform_store_id)
            });

          case 30:
            region = taskMallInfo.region;
            task.host = temu["h" /* temu */]["".concat(region, "Host")];
            _context4.next = 44;
            break;

          case 34:
            if (!(task.area === 'US')) {
              _context4.next = 38;
              break;
            }

            task.host = temu["h" /* temu */].usHost;
            _context4.next = 44;
            break;

          case 38:
            if (!(task.area === 'EU')) {
              _context4.next = 42;
              break;
            }

            task.host = temu["h" /* temu */].euHost;
            _context4.next = 44;
            break;

          case 42:
            log["a" /* default */].setLog("\u591A\u5E73\u53F0\u68C0\u6D4B\u5E97\u94FA\u662F\u5426\u5728\u7EBF\u5931\u8D25----\u4E0D\u652F\u6301\u7684temu\u672C\u571Farea:".concat(task.area));
            return _context4.abrupt("return", {
              msg: "\u591A\u5E73\u53F0\u68C0\u6D4B\u5E97\u94FA\u662F\u5426\u5728\u7EBF\u5931\u8D25----\u4E0D\u652F\u6301\u7684temu\u672C\u571Farea:".concat(task.area)
            });

          case 44:
            checkLocalHandle = {
              US: temu["e" /* checkTemuUsLocal */],
              EU: temu["c" /* checkTemuEuLocal */],
              GLOBAL: function GLOBAL() {
                return Object(temu["d" /* checkTemuGlobalLocal */])(region);
              }
            }[task.area];
            _context4.next = 47;
            return checkLocalHandle();

          case 47:
            _storeInfo2 = _context4.sent;
            mallInfo = _storeInfo2 && _storeInfo2.layoutData.mallData && _storeInfo2.layoutData.mallData.mallInfo; // 店铺校准

            checked = temu["h" /* temu */].localStoreInfo.find(function (_ref8) {
              var mallId = _ref8.mallId;
              return mallId == (mallInfo === null || mallInfo === void 0 ? void 0 : mallInfo.mallId);
            });
            task.siteId = (_temu$localStoreInfo$ = temu["h" /* temu */].localStoreInfo.find(function (_ref9) {
              var mallId = _ref9.mallId;
              return mallId == task.platform_store_id;
            })) === null || _temu$localStoreInfo$ === void 0 ? void 0 : _temu$localStoreInfo$.siteId;
            res = {
              onlineSiteStatus: mallInfo ? checked ? 1 : 3 : 2,
              storeType: 'local',
              area: region,
              mall: checked ? checked.mallId : mallInfo === null || mallInfo === void 0 ? void 0 : mallInfo.mallId
            };

          case 52:
            return _context4.abrupt("break", 105);

          case 53:
            _platform_store_id = task.platform_store_id, store_type = task.store_type, site_name = task.site_name;

            if (!(store_type === 'GLOBAL')) {
              _context4.next = 69;
              break;
            }

            // 跨境店铺
            _region = tiktok.siteRegionMap[site_name === null || site_name === void 0 ? void 0 : site_name.toLocaleUpperCase()];
            host = tiktok.cbShopHosts[_region];

            if (host) {
              _context4.next = 59;
              break;
            }

            return _context4.abrupt("return", {
              msg: 'tiktok当前不支持跨境站点: ' + site_name
            });

          case 59:
            task.isAffiliate = tiktok.getAffiliateDataTask.includes(+task.type_id);
            task.host = task.isAffiliate ? tiktok.cbUsAffiliateHost : host;
            _context4.next = 63;
            return checkTiktokCb(host);

          case 63:
            _yield$checkTiktokCb = _context4.sent;
            sellerList = _yield$checkTiktokCb.sellerList;
            // 店铺校准
            _find2 = sellerList === null || sellerList === void 0 ? void 0 : sellerList.find(function (_ref10) {
              var seller_id = _ref10.seller_id;
              return seller_id == _platform_store_id;
            });
            res = {
              onlineSiteStatus: (sellerList === null || sellerList === void 0 ? void 0 : sellerList.length) > 0 ? _find2 ? 1 : 3 : 2,
              storeType: 'global'
            };
            _context4.next = 81;
            break;

          case 69:
            // 本土店铺
            site = site_name === null || site_name === void 0 ? void 0 : site_name.toLocaleUpperCase();
            _host = tiktok.localHost[site];

            if (_host) {
              _context4.next = 73;
              break;
            }

            return _context4.abrupt("return", {
              msg: 'tiktok当前不支持本土站点: ' + site_name
            });

          case 73:
            task.isAffiliate = tiktok.getAffiliateDataTask.includes(+task.type_id);
            task.host = task.isAffiliate ? tiktok.localAffiliateHost[site] : _host;
            _context4.next = 77;
            return checkTiktokLocal(_host);

          case 77:
            _yield$checkTiktokLoc = _context4.sent;
            _sellerList = _yield$checkTiktokLoc.sellerList;
            _find3 = _sellerList === null || _sellerList === void 0 ? void 0 : _sellerList.find(function (_ref11) {
              var seller_id = _ref11.seller_id;
              return seller_id == _platform_store_id;
            });
            res = {
              onlineSiteStatus: (_sellerList === null || _sellerList === void 0 ? void 0 : _sellerList.length) > 0 ? _find3 ? 1 : 3 : 2,
              storeType: 'local'
            };

          case 81:
            return _context4.abrupt("break", 105);

          case 82:
            res = {
              msg: 'tiktok插件目前还不支持全托店铺'
            };
            return _context4.abrupt("break", 105);

          case 84:
            if (!(task.store_type === 'GLOBAL')) {
              _context4.next = 93;
              break;
            }

            _context4.next = 87;
            return Object(mercado["a" /* checkMercadoCb */])();

          case 87:
            _storeInfo3 = _context4.sent;
            // 店铺校准
            _find4 = _storeInfo3 && _storeInfo3.find(function (_ref12) {
              var userId = _ref12.userId;
              return userId == task.platform_store_id;
            });
            res = {
              onlineSiteStatus: _storeInfo3 ? _find4 ? 1 : 3 : 2,
              storeType: 'global'
            };
            task.host = mercado["c" /* mercado */].getPagoTask.includes(+task.type_id) ? mercado["c" /* mercado */].cbPagoHost : mercado["c" /* mercado */].cbHost;
            _context4.next = 104;
            break;

          case 93:
            // 本土
            _taskMallInfo = mercado["c" /* mercado */].localStoreInfo.find(function (_ref13) {
              var mallId = _ref13.mallId;
              return mallId == task.platform_store_id;
            });

            if (_taskMallInfo) {
              _context4.next = 97;
              break;
            }

            log["a" /* default */].setLog("\u672A\u627E\u5230mallId\u4E3A".concat(task.platform_store_id, "\u7684\u5E97\u94FA\u4FE1\u606F"));
            return _context4.abrupt("return", {
              msg: "\u591A\u5E73\u53F0\u68C0\u6D4B\u5E97\u94FA\u662F\u5426\u5728\u7EBF\u5931\u8D25----\u672A\u77E5\u5E97\u94FA:".concat(task.platform_store_id)
            });

          case 97:
            _region2 = _taskMallInfo.region;
            task.host = mercado["c" /* mercado */].getPagoTask.includes(+task.type_id) ? mercado["c" /* mercado */].localPagoHost.find(function (_ref14) {
              var value = _ref14.value;
              return value === _region2;
            }).host : mercado["c" /* mercado */].localHost.find(function (_ref15) {
              var value = _ref15.value;
              return value === _region2;
            }).host;
            _context4.next = 101;
            return Object(mercado["b" /* checkMercadoLocal */])(_region2);

          case 101:
            _storeInfo4 = _context4.sent;
            // 店铺校准
            _checked = mercado["c" /* mercado */].localStoreInfo.find(function (_ref16) {
              var mallId = _ref16.mallId;
              return mallId == _storeInfo4.mallId;
            });
            res = {
              onlineSiteStatus: _storeInfo4 ? _checked ? 1 : 3 : 2,
              storeType: 'local',
              area: _region2
            };

          case 104:
            return _context4.abrupt("break", 105);

          case 105:
            // 记录离线店铺
            recordOfflineSite(res);
            return _context4.abrupt("return", res);

          case 109:
            _context4.prev = 109;
            _context4.t1 = _context4["catch"](0);
            msg = '多平台检测店铺是否在线失败----' + Object(util["u" /* isError */])(_context4.t1);
            log["a" /* default */].setLog(msg);
            return _context4.abrupt("return", {
              msg: msg
            });

          case 114:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 109]]);
  }));

  return function multiPlatformOnlineSite(_x) {
    return _ref4.apply(this, arguments);
  };
}();
/**
 * @description 记录离线店铺
 */

var recordOfflineSite = /*#__PURE__*/function () {
  var _ref18 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee5(_ref17) {
    var onlineSiteStatus, storeType, area, _yield$localStorage$g2, platform, mallIds;

    return common_regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            onlineSiteStatus = _ref17.onlineSiteStatus, storeType = _ref17.storeType, area = _ref17.area;
            _context5.next = 3;
            return util["y" /* localStorage */].getItem(['platform']);

          case 3:
            _yield$localStorage$g2 = _context5.sent;
            platform = _yield$localStorage$g2.platform;
            mallIds = [];
            _context5.t0 = platform;
            _context5.next = _context5.t0 === 'temu' ? 9 : _context5.t0 === 'tiktok' ? 11 : _context5.t0 === 'mercado' ? 13 : 15;
            break;

          case 9:
            mallIds = storeType === 'global' ? temu["h" /* temu */].cbStoreInfo.map(function (_ref19) {
              var mallId = _ref19.mallId;
              return mallId;
            }) : temu["h" /* temu */].localStoreInfo.filter(function (_ref20) {
              var region = _ref20.region;
              return region === area;
            }).map(function (_ref21) {
              var mallId = _ref21.mallId;
              return mallId;
            });
            return _context5.abrupt("break", 15);

          case 11:
            mallIds = tiktok.cbStoreInfo.map(function (_ref22) {
              var global_seller_id = _ref22.global_seller_id;
              return global_seller_id;
            });
            return _context5.abrupt("break", 15);

          case 13:
            mallIds = storeType === 'global' ? mercado["c" /* mercado */].cbStoreInfo.map(function (_ref23) {
              var mallId = _ref23.mallId;
              return mallId;
            }) : mercado["c" /* mercado */].localStoreInfo.filter(function (_ref24) {
              var region = _ref24.region;
              return region === area;
            }).map(function (_ref25) {
              var mallId = _ref25.mallId;
              return mallId;
            });
            return _context5.abrupt("break", 15);

          case 15:
            // 如果离线，则添加到离线店铺中，如果在线，则从离线店铺中移除
            multiPlatform.offlineSite = onlineSiteStatus === 1 ? multiPlatform.offlineSite.filter(function (mallId) {
              return !mallIds.includes(mallId);
            }) : common_toConsumableArray(new Set([].concat(common_toConsumableArray(multiPlatform.offlineSite), common_toConsumableArray(mallIds))));

          case 16:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5);
  }));

  return function recordOfflineSite(_x2) {
    return _ref18.apply(this, arguments);
  };
}();
/**
 * @description 切换站点店铺
 */


var multiPlatformChangeSite = /*#__PURE__*/function () {
  var _ref26 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee6(task) {
    return common_regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.t0 = +task.platform_code;
            _context6.next = _context6.t0 === 10022 ? 3 : _context6.t0 === 10024 ? 3 : _context6.t0 === 10011 ? 6 : _context6.t0 === 10032 ? 7 : _context6.t0 === 10012 ? 10 : 11;
            break;

          case 3:
            _context6.next = 5;
            return Object(temu["a" /* changeLocalMallId */])(task);

          case 5:
            return _context6.abrupt("return", _context6.sent);

          case 6:
            return _context6.abrupt("return", changeCbSiteAndLanguage(task));

          case 7:
            task.msg = 'tiktok插件目前还不支持全托店铺';
            log["a" /* default */].setLog(task.msg);
            return _context6.abrupt("return", false);

          case 10:
            return _context6.abrupt("return", true);

          case 11:
            return _context6.abrupt("return", false);

          case 12:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6);
  }));

  return function multiPlatformChangeSite(_x3) {
    return _ref26.apply(this, arguments);
  };
}();
/**
 * @description 心跳检测
 */

var checkHeartbeat = /*#__PURE__*/function () {
  var _ref27 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee7() {
    var platform_store_id;
    return common_regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            log["a" /* default */].setLog('多平台心跳检测----', JSON.stringify(multiPlatform.storeInfo)); // const is_pause = await suspend()

            platform_store_id = multiPlatform.storeInfo.filter(function (mallId) {
              return !multiPlatform.offlineSite.includes(mallId);
            });
            _context7.next = 4;
            return Object(util["m" /* gatePost */])('api/mp/reportHeartBeat', {
              // is_pause: !!is_pause,
              platform_code: multiPlatform.platformCode,
              platform_store_id: platform_store_id
            }, 'task').catch(function () {});

          case 4:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7);
  }));

  return function checkHeartbeat() {
    return _ref27.apply(this, arguments);
  };
}();
/**
 * @description 轮询
 */


var setTimerLoop = /*#__PURE__*/function () {
  var _ref28 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee11() {
    var count;
    return common_regeneratorRuntime().wrap(function _callee11$(_context11) {
      while (1) {
        switch (_context11.prev = _context11.next) {
          case 0:
            count = 0; // 如果是tk平台，单独设置个定时器来查询任务

            if (multiPlatform.platformCode === 'tiktok') {
              util["b" /* alarms */].setInterval( /*#__PURE__*/common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee8() {
                return common_regeneratorRuntime().wrap(function _callee8$(_context8) {
                  while (1) {
                    switch (_context8.prev = _context8.next) {
                      case 0:
                        multiPlatform.multiPlatformTaskInstance.getTaskList();

                      case 1:
                      case "end":
                        return _context8.stop();
                    }
                  }
                }, _callee8);
              })), 'getTiktokTask', multiPlatform.tkPollingTime);
            }

            util["b" /* alarms */].setInterval( /*#__PURE__*/common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee9() {
              var status;
              return common_regeneratorRuntime().wrap(function _callee9$(_context9) {
                while (1) {
                  switch (_context9.prev = _context9.next) {
                    case 0:
                      count++;
                      handlePolling(); // 处理暂停状态（防止非手动暂停后关闭插件使插件永久暂停）

                      handleRestoreSuspend(); // 十分钟执行一次

                      if (!(count === 2)) {
                        _context9.next = 10;
                        break;
                      }

                      // 检测版本
                      Object(util["c" /* checkVersion */])(); // 检测插件是否可用

                      _context9.next = 7;
                      return data_task["b" /* default */].checkEnable();

                    case 7:
                      status = _context9.sent;
                      util["y" /* localStorage */].setItem({
                        enableObj: {
                          status: status
                        }
                      }); // 插件当前是否维护中 status为0：维护中，1：可运行

                      count = 0;

                    case 10:
                      // 执行重复任务
                      multiPlatform.multiPlatformTaskInstance.runRepeat();

                    case 11:
                    case "end":
                      return _context9.stop();
                  }
                }
              }, _callee9);
            })), 'multiPlatformBgLoop', multiPlatform.otherPollingTime); // 站点离线时检测轮询

            util["b" /* alarms */].setInterval( /*#__PURE__*/common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee10() {
              return common_regeneratorRuntime().wrap(function _callee10$(_context10) {
                while (1) {
                  switch (_context10.prev = _context10.next) {
                    case 0:
                      checkSiteOfOfflineTask();

                    case 1:
                    case "end":
                      return _context10.stop();
                  }
                }
              }, _callee10);
            })), 'checkSiteOfOfflineTask', 1);

          case 4:
          case "end":
            return _context11.stop();
        }
      }
    }, _callee11);
  }));

  return function setTimerLoop() {
    return _ref28.apply(this, arguments);
  };
}();
/**
 * @description 定时函数
 */


function handlePolling() {
  return _handlePolling.apply(this, arguments);
}
/**
 * @description 当任务存在站点离线状态，则检测店铺
 */


function _handlePolling() {
  _handlePolling = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee14() {
    var _task;

    return common_regeneratorRuntime().wrap(function _callee14$(_context14) {
      while (1) {
        switch (_context14.prev = _context14.next) {
          case 0:
            if (!(multiPlatform.storeInfo && multiPlatform.storeInfo.length)) {
              _context14.next = 8;
              break;
            }

            _task = multiPlatform.multiPlatformTaskInstance; // 心跳检测

            checkHeartbeat(); // 五分钟请求一次获取任务接口

            if (['tiktok'].includes(multiPlatform.platformCode)) {
              _context14.next = 6;
              break;
            }

            _context14.next = 6;
            return _task.getTaskList();

          case 6:
            // 没有任务类型，则获取任务类型
            if (multiPlatform.taskTypes.length === 0) _task.getTaskType(); // 检测定时任务是否开启

            checkEnableTimerTask();

          case 8:
          case "end":
            return _context14.stop();
        }
      }
    }, _callee14);
  }));
  return _handlePolling.apply(this, arguments);
}

function checkSiteOfOfflineTask() {
  return _checkSiteOfOfflineTask.apply(this, arguments);
}
/**
 * @description 检测定时任务是否开启
 */


function _checkSiteOfOfflineTask() {
  _checkSiteOfOfflineTask = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee15() {
    var multiPlatformTaskInstance, taskGroups, taskList, hasOfflineTask, arr, _iterator, _step, _task2;

    return common_regeneratorRuntime().wrap(function _callee15$(_context15) {
      while (1) {
        switch (_context15.prev = _context15.next) {
          case 0:
            multiPlatformTaskInstance = multiPlatform.multiPlatformTaskInstance;
            taskGroups = multiPlatformTaskInstance && multiPlatformTaskInstance.taskGroups;

            if (!(taskGroups && Object.keys(taskGroups).length)) {
              _context15.next = 36;
              break;
            }

            taskList = Object.values(taskGroups).flatMap(function (group) {
              return group.tasks;
            });
            hasOfflineTask = taskList.find(function (task) {
              return task.status === 11;
            });

            if (!hasOfflineTask) {
              _context15.next = 36;
              break;
            }

            log["a" /* default */].setLog('有离线任务，准备检测站点'); // 有离线任务，准备检测
            // 检测到有店铺，将对应店铺状态为离线的任务错误次数重置成0

            arr = [];
            _iterator = _createForOfIteratorHelper(taskList);
            _context15.prev = 9;

            _iterator.s();

          case 11:
            if ((_step = _iterator.n()).done) {
              _context15.next = 25;
              break;
            }

            _task2 = _step.value;
            _context15.t0 = _task2.status === 11;

            if (!_context15.t0) {
              _context15.next = 19;
              break;
            }

            _context15.next = 17;
            return multiPlatformOnlineSite(_task2);

          case 17:
            _context15.t1 = _context15.sent.onlineSiteStatus;
            _context15.t0 = _context15.t1 === 1;

          case 19:
            if (!_context15.t0) {
              _context15.next = 23;
              break;
            }

            arr.push(_task2.task_id);
            _task2.error_time = 0;
            _task2.status = 0;

          case 23:
            _context15.next = 11;
            break;

          case 25:
            _context15.next = 30;
            break;

          case 27:
            _context15.prev = 27;
            _context15.t2 = _context15["catch"](9);

            _iterator.e(_context15.t2);

          case 30:
            _context15.prev = 30;

            _iterator.f();

            return _context15.finish(30);

          case 33:
            log["a" /* default */].setLog('已重置离线任务', JSON.stringify(arr), '---准备重新调度任务');
            if (arr.length > 0) multiPlatformTaskInstance.taskSchedule(); // 检测一次就可以退出了

            return _context15.abrupt("return");

          case 36:
          case "end":
            return _context15.stop();
        }
      }
    }, _callee15, null, [[9, 27, 30, 33]]);
  }));
  return _checkSiteOfOfflineTask.apply(this, arguments);
}

var checkEnableTimerTask = /*#__PURE__*/function () {
  var _ref32 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee12() {
    var _yield$gateGet, code, data;

    return common_regeneratorRuntime().wrap(function _callee12$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            _context12.prev = 0;
            _context12.next = 3;
            return Object(util["l" /* gateGet */])('api/v1/checkSysJobStatus');

          case 3:
            _yield$gateGet = _context12.sent;
            code = _yield$gateGet.code;
            data = _yield$gateGet.data;

            if (code === 0) {
              multiPlatform.enableTimerTask = data.status;
            }

            _context12.next = 12;
            break;

          case 9:
            _context12.prev = 9;
            _context12.t0 = _context12["catch"](0);
            log["a" /* default */].setLog('检测定时任务是否开启失败----' + Object(util["u" /* isError */])(_context12.t0));

          case 12:
          case "end":
            return _context12.stop();
        }
      }
    }, _callee12, null, [[0, 9]]);
  }));

  return function checkEnableTimerTask() {
    return _ref32.apply(this, arguments);
  };
}();
/**
 * 恢复暂停状态
 * @returns 
 */


var handleRestoreSuspend = /*#__PURE__*/function () {
  var _ref33 = common_asyncToGenerator( /*#__PURE__*/common_regeneratorRuntime().mark(function _callee13() {
    var _yield$localStorage$g3, suspend;

    return common_regeneratorRuntime().wrap(function _callee13$(_context13) {
      while (1) {
        switch (_context13.prev = _context13.next) {
          case 0:
            _context13.next = 2;
            return util["y" /* localStorage */].getItem(['suspend']);

          case 2:
            _yield$localStorage$g3 = _context13.sent;
            suspend = _yield$localStorage$g3.suspend;

            if (suspend) {
              _context13.next = 6;
              break;
            }

            return _context13.abrupt("return");

          case 6:
            if (!(suspend == '99')) {
              _context13.next = 8;
              break;
            }

            return _context13.abrupt("return");

          case 8:
            if (suspend == '1' || Number(suspend) < Date.now()) {
              log["a" /* default */].report("\u3010sellerID:".concat(JSON.stringify(multiPlatform.storeInfo), "\u3011\u4EFB\u52A1\u6062\u590D\u6267\u884C\u3002"), 'info');
              util["y" /* localStorage */].removeItem(['suspend']); // 恢复运行（触发src\platform\common\task.js taskSchedule方法）

              Object(utils_event["a" /* distribute */])('GoExecuteTemu');
            }

          case 9:
          case "end":
            return _context13.stop();
        }
      }
    }, _callee13);
  }));

  return function handleRestoreSuspend() {
    return _ref33.apply(this, arguments);
  };
}();

var common_multiPlatformTaskClear = function multiPlatformTaskClear() {
  multiPlatform.multiPlatformTaskInstance && multiPlatform.multiPlatformTaskInstance.destroyed();
  multiPlatform.multiPlatformTaskInstance = null;
  websocket["a" /* default */] && websocket["a" /* default */].webSocketClose();
  Object(utils_event["c" /* removeMonitor */])('ReceivePush', receivePush);
  Object(utils_event["c" /* removeMonitor */])('GoExecuteTemu', goExecuteTemu); // 清除任务请求轮询定时器

  chrome.alarms.clear('multiPlatformBgLoop');
  chrome.alarms.clear('checkSiteOfOfflineTask');
  chrome.alarms.clear('getTiktokTask');
};
var common_multiPlatformClear = function multiPlatformClear() {
  log["a" /* default */].setLog('----清除多平台登录信息----');
  multiPlatform.storeInfo = [];
  multiPlatform.platformCode = '';
  common_multiPlatformTaskClear();
  Object(util["d" /* clearKeepServiceWorker */])();
  util["y" /* localStorage */].removeItem(['token', 'refresh_token', 'company_id', 'uid', 'username', 'env_key', 'domain', 'platform']);
};

/***/ }),

/***/ "b2eb":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _data_log_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("6b23");
/* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("ca00");
/* harmony import */ var _utils_event__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("42a5");
/* harmony import */ var _data_amazon_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("ef13");
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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





var ws;
var num = 0;
var disconnection = false;
var time = 10000;
var env = '';
var wsToken;
var reconnecting = false;
var lost = 0; // 丢失心跳包次数

var storeIds;
var urlMap = {
  dev: 'wss://notice-t.umaicloud.com?token=',
  test: 'wss://notice-t.lingxingerp.com?token=',
  pro: 'wss://notice-plug.lingxingerp.com?token='
};

function reconnect(token) {
  if (reconnecting) return;
  reconnecting = true; // 没连接上会一直重连，设置延迟避免请求过多

  chrome.alarms.clear('websocketReconnect');
  _utils_util__WEBPACK_IMPORTED_MODULE_1__[/* alarms */ "b"].setTimeout(function () {
    // console.log('执行断线重连...')
    num += 1;
    webSocket.init(token);
    reconnecting = false;

    if (num == 60) {
      // 10分钟后修改为1分钟重连一次
      time = 60000;
    } else if (num == 80) {
      time = 300000; // 30分钟后修改为5分钟重连一次
    }
  }, 'websocketReconnect', time);
} // 心跳检测


var heartCheck = {
  timeout: 1,
  start: function start() {
    chrome.alarms.clear('websocketHeartCheck');
    _utils_util__WEBPACK_IMPORTED_MODULE_1__[/* alarms */ "b"].setInterval(function () {
      ws.send(heartBeatEncode());
      lost++; // 120秒未收到心跳，主动断开，15s后重连

      if (lost >= 2) {
        lost = 0;
        webSocket.webSocketClose(false, 15000);
        _data_log_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].report('心跳包丢失，断开连接', 'except');
        return;
      }
    }, 'websocketHeartCheck', this.timeout);
  },
  reset: function reset() {
    chrome.alarms.clear('websocketHeartCheck');
  }
}; // 生成0-255十进制

var toRandomByte = function toRandomByte() {
  var byte = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0xff;
  return Math.floor(Math.random() * byte);
}; // 十进制转十六进制


var toDechex = function toDechex(num) {
  return num.toString(16).padStart(2, '0');
};
/**
 * @description 
 * 加密规则：随机生成四个字节data01-data02-data03-data04，start01取data02&11的结果，start02取data02，end01取start01^start02
 * data01-data04做简单加密处理，每个值^118
 * @returns start01-start02-data01-data02-data03-data04-end01
 */


function heartBeatEncode() {
  // 随机生成头部一个字节
  var tempDataByte = [];
  var start01 = toRandomByte();
  var start02 = toRandomByte();
  tempDataByte[0] = toDechex(start01 & 11);
  tempDataByte[1] = toDechex(start02); // data数据区

  tempDataByte[2] = toDechex(toRandomByte() ^ 118);
  tempDataByte[3] = toDechex(start01 ^ 118);
  tempDataByte[4] = toDechex(start02 ^ 118);
  tempDataByte[5] = toDechex(toRandomByte() ^ 118); // 最后一位校验位

  tempDataByte[6] = toDechex(start01 & 11 ^ start02);
  return tempDataByte.join('');
} // 判断接收到消息是否是心跳


function isHeartCheck(data) {
  if (data == 1) {
    lost = 0;
  }
}

var webSocket = {
  init: function () {
    var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
      var seller_ids,
          _yield$localStorage$g,
          token,
          res,
          _args = arguments;

      return _regeneratorRuntime().wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              seller_ids = _args.length > 0 && _args[0] !== undefined ? _args[0] : storeIds;
              _context.next = 3;
              return _utils_util__WEBPACK_IMPORTED_MODULE_1__[/* localStorage */ "y"].getItem(['token']);

            case 3:
              _yield$localStorage$g = _context.sent;
              token = _yield$localStorage$g.token;

              if (!(!token || !seller_ids)) {
                _context.next = 7;
                break;
              }

              return _context.abrupt("return");

            case 7:
              storeIds = seller_ids;
              _context.next = 10;
              return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* gateGet */ "l"])('v1/app/getWebAuth', {
                channel_type: 'store_plug',
                seller_ids: seller_ids
              }, 'notice').catch(function (e) {
                _data_log_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("getWebAuth error----".concat(JSON.stringify(e)));
              });

            case 10:
              res = _context.sent;

              if (!(res && res.code === 1)) {
                _context.next = 17;
                break;
              }

              wsToken = res.data.token;
              env = res.data.app_env; // 销毁之前的ws实例

              ws && ws.webSocketClose();
              _context.next = 19;
              break;

            case 17:
              // token获取失败,重连
              reconnect();
              return _context.abrupt("return");

            case 19:
              // if ('WebSocket' in window) {
              ws = new WebSocket(urlMap[env] + wsToken); // } else {
              //   log.setLog('您的浏览器不支持 WebSocket!')
              //   return
              // }

              ws.onmessage = function (e) {
                if (e && e.data) {
                  try {
                    var data = JSON.parse(e.data); // log.setLog(`[websocket]接收数据----${JSON.stringify(data)}`)

                    isHeartCheck(data);
                    Object(_utils_event__WEBPACK_IMPORTED_MODULE_2__[/* distribute */ "a"])('ReceivePush', data.data);
                  } catch (error) {
                    var _data = e.data; // log.setLog(`[websocket]接收数据----${e.data}`)

                    isHeartCheck(_data);
                    Object(_utils_event__WEBPACK_IMPORTED_MODULE_2__[/* distribute */ "a"])('ReceivePush', _data.data); // log.setLog(`[websocket]处理接收数据错误----${JSON.stringify(error)}`)
                  }
                }
              };

              ws.onerror = function (e) {
                ws = null;
                _data_log_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("[websocket]\u6570\u636E\u4F20\u8F93\u53D1\u751F\u9519\u8BEF----".concat(JSON.stringify(e)));
                heartCheck.reset();
                reconnect();
              };

              ws.onclose = function () {
                ws = null;
                _data_log_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].report('[websocket]连接已关闭', 'except');

                if (!disconnection) {
                  heartCheck.reset();
                  reconnect();
                }
              };

              ws.onopen = function () {
                _data_log_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog('[websocket]连接成功');
                num = 0;
                time = 10000;
                disconnection = false;
                heartCheck.start();
              };

            case 24:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    function init() {
      return _init.apply(this, arguments);
    }

    return init;
  }(),
  webSocketClose: function webSocketClose() {
    var disConn = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
    var t = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
    disconnection = disConn;
    heartCheck.reset();
    chrome.alarms.clear('websocketReconnect');
    num = 0;
    time = t;
    ws && ws.close();
  },
  getWebSocket: function getWebSocket() {
    return ws;
  },
  getStatus: function getStatus() {
    if (ws.readyState == 0) {
      return '未连接';
    } else if (ws.readyState == 1) {
      return '已连接';
    } else if (ws.readyState == 2) {
      return '连接正在关闭';
    } else if (ws.readyState == 3) {
      return '连接已关闭';
    }
  }
};
/* harmony default export */ __webpack_exports__["a"] = (webSocket);

/***/ }),

/***/ "ba27":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getQueryString; });
/* unused harmony export tkNativeRequest */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return tkGet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return tkPost; });
/* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("ca00");
/* harmony import */ var _platform_tiktok_xGnarly_inedx__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("6a0a");
/* harmony import */ var _data_log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("6b23");
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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }




/**
 * 构建查询字符串（不编码）
 * @param {object} params - 参数对象
 * @returns {string} 查询字符串
 */

var buildQueryString = function buildQueryString(params) {
  return Object.entries(params).filter(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        value = _ref2[1];

    return value !== undefined && value !== null;
  }).map(function (_ref3) {
    var _ref4 = _slicedToArray(_ref3, 2),
        key = _ref4[0],
        value = _ref4[1];

    return "".concat(key, "=").concat(value);
  }).join('&');
};
/**
 * 获取query
 */


var getQueryString = /*#__PURE__*/function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(task) {
    var ortherQuery,
        host,
        timezone_name,
        platform_store_id,
        shop_region,
        aid,
        _yield$Promise$all,
        _yield$Promise$all2,
        msTokenCookie,
        i18nextCookie,
        msg,
        _args = arguments;

    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            ortherQuery = _args.length > 1 && _args[1] !== undefined ? _args[1] : {};
            host = task.host, timezone_name = task.timezone_name, platform_store_id = task.platform_store_id, shop_region = task.shop_region, aid = task.aid;
            _context.prev = 2;
            _context.t0 = Promise;
            _context.t1 = Object(_utils_util__WEBPACK_IMPORTED_MODULE_0__[/* getCookies */ "p"])({
              url: host,
              name: 'msToken'
            });
            _context.next = 7;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_0__[/* getCookies */ "p"])({
              url: host,
              name: 'i18next'
            });

          case 7:
            _context.t2 = _context.sent;
            _context.t3 = [_context.t1, _context.t2];
            _context.next = 11;
            return _context.t0.all.call(_context.t0, _context.t3);

          case 11:
            _yield$Promise$all = _context.sent;
            _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
            msTokenCookie = _yield$Promise$all2[0];
            i18nextCookie = _yield$Promise$all2[1];
            return _context.abrupt("return", _objectSpread(_objectSpread({}, ortherQuery), {}, {
              user_language: i18nextCookie === null || i18nextCookie === void 0 ? void 0 : i18nextCookie.value,
              aid: aid,
              // 应用标识，i18n_ecom_alliance:联盟中心，i18n_ecom_shop:商家中心，默认联盟中心
              app_name: task.isAffiliate ? 'i18n_ecom_alliance' : 'i18n_ecom_shop',
              // 下面这些写死
              device_id: '0',
              device_platform: 'web',
              cookie_enabled: 'true',
              screen_width: '1920',
              screen_height: '1080',
              browser_language: 'en-US',
              browser_platform: 'Win32',
              browser_name: 'Mozilla',
              browser_version: '5.0+(Windows+NT+6.2%3B+Win32%3B+x86)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F109.0.0.0+Safari%2F537.36',
              browser_online: 'true',
              timezone_name: timezone_name,
              oec_seller_id: platform_store_id,
              shop_region: shop_region,
              msToken: msTokenCookie === null || msTokenCookie === void 0 ? void 0 : msTokenCookie.value
            }));

          case 18:
            _context.prev = 18;
            _context.t4 = _context["catch"](2);
            msg = "[getQueryString] \u83B7\u53D6\u67E5\u8BE2\u5B57\u7B26\u4E32\u5931\u8D25: ".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_0__[/* isError */ "u"])(_context.t4));
            _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog(msg);
            task.msg = msg;

          case 23:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[2, 18]]);
  }));

  return function getQueryString(_x) {
    return _ref5.apply(this, arguments);
  };
}();
/**
 * TikTok 原生请求（自动添加 X-Gnarly 签名）
 * @param {object} options - 请求选项
 * @param {string} options.url - 请求 URL（基础路径，不含查询参数）
 * @param {string} options.method - 请求方法：'get' | 'post'
 * @param {object} options.params - URL 查询参数
 * @param {object} options.data - 请求体数据（POST 时使用）
 * @param {string} options.referer - Referer 头（可选，默认使用 url 的 origin）
 * @param {string} options.origin - Origin 头（可选，默认使用 url 的 origin）
 * @param {string} options.responseType - 响应类型
 * @param {boolean} options.addBogus - 是否额外添加 X-Bogus
 * @returns {Promise<object>} 响应数据
 */

var tkNativeRequest = /*#__PURE__*/function () {
  var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(config) {
    var url, _config$params, params, _config$data, data, method, headers, responseType, _config$referer, referer, _config$origin, origin, _config$addBogus, addBogus, urlOrigin, finalReferer, finalOrigin, queryString, unsignedUrl, _headers, signedUrl, bogus, gnarly, response;

    return _regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            url = config.url, _config$params = config.params, params = _config$params === void 0 ? {} : _config$params, _config$data = config.data, data = _config$data === void 0 ? null : _config$data, method = config.method, headers = config.headers, responseType = config.responseType, _config$referer = config.referer, referer = _config$referer === void 0 ? '' : _config$referer, _config$origin = config.origin, origin = _config$origin === void 0 ? '' : _config$origin, _config$addBogus = config.addBogus, addBogus = _config$addBogus === void 0 ? false : _config$addBogus; // 从 URL 提取默认 host

            urlOrigin = new URL(url).origin;
            finalReferer = referer || urlOrigin;
            finalOrigin = origin || urlOrigin; // 1.构建完整 URL（不编码）

            queryString = buildQueryString(params);
            unsignedUrl = queryString ? url.includes('?') ? "".concat(url, "&").concat(queryString) : "".concat(url, "?").concat(queryString) : url; // 2. 设置请求头

            _headers = [{
              name: 'Referer',
              value: finalReferer
            }, {
              name: 'Origin',
              value: finalOrigin
            }];
            _context2.next = 10;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_0__[/* setRequestHearder */ "I"])(_headers, "".concat(urlOrigin, "/*"));

          case 10:
            // 3. 获取签名
            signedUrl = unsignedUrl;

            if (!addBogus) {
              _context2.next = 16;
              break;
            }

            _context2.next = 14;
            return Object(_platform_tiktok_xGnarly_inedx__WEBPACK_IMPORTED_MODULE_1__[/* generateXBogus */ "a"])(unsignedUrl);

          case 14:
            bogus = _context2.sent;
            signedUrl += "&X-Bogus=".concat(bogus);

          case 16:
            _context2.next = 18;
            return Object(_platform_tiktok_xGnarly_inedx__WEBPACK_IMPORTED_MODULE_1__[/* generateXGnarly */ "b"])(unsignedUrl, data);

          case 18:
            gnarly = _context2.sent;
            signedUrl += "&X-Gnarly=".concat(gnarly); // 3. 发送请求（签名已包含在 signedUrl 中）

            _context2.next = 22;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_0__[/* nativeRequest */ "z"])(signedUrl, method, data, headers, responseType);

          case 22:
            response = _context2.sent;
            return _context2.abrupt("return", response);

          case 26:
            _context2.prev = 26;
            _context2.t0 = _context2["catch"](0);
            _data_log__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"].setLog("[tkNativeRequest] \u8BF7\u6C42\u5931\u8D25: ".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_0__[/* isError */ "u"])(_context2.t0)));
            throw _context2.t0;

          case 30:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 26]]);
  }));

  return function tkNativeRequest(_x2) {
    return _ref6.apply(this, arguments);
  };
}();
/**
 * TikTok GET 请求（快捷方法）
 * @param {string} url - 请求 URL
 * @param {object} params - URL 查询参数
 * @param {object} options - 其他选项 { referer, origin, responseType, addBogus }
 */

var tkGet = function tkGet(url) {
  var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  return tkNativeRequest(_objectSpread({
    url: url,
    method: 'get',
    params: params
  }, options));
};
/**
 * TikTok POST 请求（快捷方法）
 * @param {string} url - 请求 URL
 * @param {object} params - URL 查询参数
 * @param {object} data - 请求体数据
 * @param {object} options - 其他选项 { referer, origin, responseType, headers, addBogus }
 */

var tkPost = function tkPost(url) {
  var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  return tkNativeRequest(_objectSpread({
    url: url,
    method: 'post',
    params: params,
    data: data
  }, options));
};
/* unused harmony default export */ var _unused_webpack_default_export = ({
  tkNativeRequest: tkNativeRequest,
  tkGet: tkGet,
  tkPost: tkPost
});

/***/ }),

/***/ "c04e":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return temu; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return changeLocalMallId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return temuCheckSite; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkTemuCb; });
/* unused harmony export checkTemuCbUS */
/* unused harmony export checkTemuCbTask */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return checkTemuUsLocal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return checkTemuEuLocal; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return checkTemuGlobalLocal; });
/* unused harmony export changeTemuEuSite */
/* unused harmony export getTemuLocalAccount */
/* unused harmony export changeLanguage */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return loginCb; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getRealMallId; });
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("bc3a");
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _data_log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("6b23");
/* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("ca00");
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("a1d0");
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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }





var temu = {
  // 跨境host
  cbHost: 'https://seller.kuajingmaihuo.com',
  // 跨境全球host
  cbGlobalHost: 'https://agentseller.temu.com',
  // 跨境美区host
  cbUsHost: 'https://agentseller-us.temu.com',
  // 跨境欧区host
  cbEuHost: 'https://agentseller-eu.temu.com',
  // 本土美区host
  usHost: 'https://seller.temu.com',
  // 本土欧区host
  euHost: 'https://seller-eu.temu.com',
  // 本土墨西哥host
  mxHost: 'https://mx.seller.temu.com',
  // 本土韩国host
  krHost: 'https://kr.seller.temu.com',
  // 本土巴西host
  brHost: 'https://br.seller.temu.com',
  // 本土日本host
  jpHost: 'https://jp.seller.temu.com',
  // 本土加拿大host
  caHost: 'https://ca.seller.temu.com',
  // 本土店铺所有国家sitaid，目前为全平台固定值
  siteIds: [],
  // declarativeNetRequest规则集id
  requestHearderIds: [],
  // 需要在cbGlobalHost域名下执行的任务
  globalHostOfTypeId: [22002, 22008, 22001, 22010, 22016, 22011, 22017],

  /**
   * 跨境店铺的信息
   * @param mallId // 店铺id
   * @param mallName // 店铺名
   * @param mallStatus // 店铺状态（目前还不知作用）
   * @param logo
   * @param isSemiManagedMall // 是否是半托管
   * @param storeType // 店铺类型  跨境
   * @param uniqueId // 店铺唯一id
   */
  cbStoreInfo: [],

  /**
   * 本土店铺信息
   * @param mallId // 店铺id
   * @param siteId // 站点id
   * @param mallName // 店铺名
   * @param marketPlaceName // 国家名
   * @param region // 区域
   * @param storeType // 店铺类型  本土
   * @param isSemiManagedMall // 是否是半托管 本土默认全半托管
   */
  localStoreInfo: []
};
var localHostMap = {
  us: temu.usHost,
  eu: temu.euHost,
  mx: temu.mxHost,
  kr: temu.krHost,
  br: temu.brHost,
  jp: temu.jpHost,
  ca: temu.caHost
}; // 为temu所有接口带上Referer、Origin

var initTemuUrlObserve = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
    var hostKeys;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            // await removeDeclarativeNetRequestRules(temu.requestHearderIds)
            hostKeys = ['cbHost', 'cbUsHost', 'cbEuHost', 'cbGlobalHost', 'usHost', 'euHost', 'mxHost', 'krHost', 'brHost', 'jpHost', 'caHost'];
            _context.next = 3;
            return Promise.all(hostKeys.map(function (hostKey) {
              var host = temu[hostKey];
              return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* setRequestHearder */ "I"])([{
                name: 'Referer',
                value: host
              }, {
                name: 'Origin',
                value: host
              }], host + '/*');
            }));

          case 3:
            temu.requestHearderIds = _context.sent;

          case 4:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function initTemuUrlObserve() {
    return _ref.apply(this, arguments);
  };
}(); // 监听请求，店铺cookie带上mailid（切换站点）


var changeLocalMallId = /*#__PURE__*/function () {
  var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
    var platform_store_id, siteId, host, store_type, _cookie, arr, newCookies, msg;

    return _regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            platform_store_id = _ref2.platform_store_id, siteId = _ref2.siteId, host = _ref2.host, store_type = _ref2.store_type;

            if (!(store_type === 'GLOBAL')) {
              _context2.next = 3;
              break;
            }

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

          case 3:
            _context2.prev = 3;

            if (host) {
              _context2.next = 6;
              break;
            }

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

          case 6:
            _context2.next = 8;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* getAllCookies */ "o"])({
              url: host
            });

          case 8:
            _cookie = _context2.sent;
            arr = _cookie.map(function (_ref4) {
              var name = _ref4.name,
                  value = _ref4.value;
              if (name === 'MALL_ID') return "MALL_ID=".concat(platform_store_id);
              if (name === 'seller_site') return "seller_site=".concat(siteId);
              return "".concat(name, "=").concat(value);
            });
            newCookies = arr.join(';'); // console.log('changeLocalMallId', `url:${host}---`, 'arr:', arr, '---', '_cookie:', _cookie)
            // 判断是否有修改cookie，有才拦截

            if (!(newCookies === _cookie.map(function (_ref5) {
              var name = _ref5.name,
                  value = _ref5.value;
              return "".concat(name, "=").concat(value);
            }).join(';'))) {
              _context2.next = 14;
              break;
            }

            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("cookie\u672A\u4FEE\u6539\uFF0C\u4E0D\u9700\u8981\u76D1\u542C");
            return _context2.abrupt("return", true);

          case 14:
            return _context2.abrupt("return", Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* setRequestHearder */ "I"])([{
              name: 'Cookie',
              value: newCookies
            }], "".concat(host, "*")));

          case 17:
            _context2.prev = 17;
            _context2.t0 = _context2["catch"](3);
            msg = "\u76D1\u542Ctemu\u8BF7\u6C42\u5E76\u4FEE\u6539cookie\u5931\u8D25,\u5931\u8D25\u539F\u56E0\uFF1A".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context2.t0));
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].report(msg, 'error', platform_store_id);
            return _context2.abrupt("return", false);

          case 22:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[3, 17]]);
  }));

  return function changeLocalMallId(_x) {
    return _ref3.apply(this, arguments);
  };
}();
/**
 * @description 清除店铺信息
 */

var clearStoreInfo = function clearStoreInfo() {
  temu.cbStoreInfo = [];
  temu.localStoreInfo = [];
  _common__WEBPACK_IMPORTED_MODULE_3__[/* multiPlatform */ "a"].storeIdMap = {};
};
/**
 * @description temu检测站点
 */


var temuCheckSite = /*#__PURE__*/function () {
  var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
    var globalLocalRegions, res, storeInfo, _res, cbInfo, usInfo, euInfo, globalLocalInfos, globalLocalRegionMap, localStoreInfos, _iterator, _step, _loop, _ret;

    return _regeneratorRuntime().wrap(function _callee4$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            _context6.prev = 0;
            clearStoreInfo();
            _context6.next = 4;
            return initTemuUrlObserve();

          case 4:
            // 全球其他本土站点列表
            globalLocalRegions = ['mx', 'kr', 'br', 'jp', 'ca'];
            _context6.next = 7;
            return Promise.all([checkTemuCb(), checkTemuUsLocal(), checkTemuEuLocal()].concat(_toConsumableArray(globalLocalRegions.map(function (region) {
              return checkTemuGlobalLocal(region);
            }))));

          case 7:
            res = _context6.sent;
            storeInfo = [];
            _res = _toArray(res), cbInfo = _res[0], usInfo = _res[1], euInfo = _res[2], globalLocalInfos = _res.slice(3); // 整理跨境店铺信息

            if (cbInfo) {
              temu.cbStoreInfo = cbInfo.map(function (item) {
                return _objectSpread(_objectSpread({}, item), {}, {
                  mallId: item.mallId || item.uniqueId,
                  storeType: '跨境'
                });
              });
              cbInfo.forEach(function (_ref7) {
                var mallId = _ref7.mallId,
                    uniqueId = _ref7.uniqueId;
                var primaryId = mallId || uniqueId;
                if (!primaryId) return;
                storeInfo.push(primaryId);

                if (mallId) {
                  _common__WEBPACK_IMPORTED_MODULE_3__[/* multiPlatform */ "a"].storeIdMap[mallId] = uniqueId || mallId;
                } else {
                  // 只有 uniqueid 的情况
                  _common__WEBPACK_IMPORTED_MODULE_3__[/* multiPlatform */ "a"].storeIdMap[uniqueId] = '';
                }
              });
            } // 整理us|mx|kr|br|jp|ca本土店铺信息


            globalLocalRegionMap = {
              'mx': '墨西哥',
              'kr': '韩国',
              'br': '巴西',
              'jp': '日本',
              'ca': '加拿大'
            };
            localStoreInfos = [usInfo && _objectSpread(_objectSpread({}, usInfo), {}, {
              _region: 'us',
              marketPlaceName: '美国'
            })].concat(_toConsumableArray(globalLocalRegions.map(function (region, index) {
              var info = globalLocalInfos[index];
              return info && _objectSpread(_objectSpread({}, info), {}, {
                _region: region,
                marketPlaceName: globalLocalRegionMap[region]
              });
            }))).filter(Boolean);

            if (!(localStoreInfos.length > 0)) {
              _context6.next = 33;
              break;
            }

            _iterator = _createForOfIteratorHelper(localStoreInfos);
            _context6.prev = 15;
            _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
              var _temu$localStoreInfo;

              var info, allAccounts, localStoreInfo, _info$layoutData$mall, mallId, mallName;

              return _regeneratorRuntime().wrap(function _loop$(_context3) {
                while (1) {
                  switch (_context3.prev = _context3.next) {
                    case 0:
                      info = _step.value;

                      if (!(!info || !info.layoutData || !info.localInfo)) {
                        _context3.next = 3;
                        break;
                      }

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

                    case 3:
                      _context3.next = 5;
                      return getTemuLocalAccount(localHostMap[info._region]);

                    case 5:
                      allAccounts = _context3.sent;
                      // 获取当前店铺下所有账号信息
                      localStoreInfo = [];

                      if (allAccounts.length > 0) {
                        localStoreInfo.push.apply(localStoreInfo, _toConsumableArray(allAccounts.map(function (_ref8) {
                          var mall_id = _ref8.mall_id,
                              mall_name = _ref8.mall_name;
                          return {
                            mallId: mall_id,
                            mallName: mall_name,
                            siteId: info.localInfo.site,
                            marketPlaceName: info.marketPlaceName,
                            region: info._region,
                            storeType: '本土',
                            isSemiManagedMall: true
                          };
                        })));
                      } else {
                        // 没有获取到账号信息，则用检测到的店铺信息
                        _info$layoutData$mall = info.layoutData.mallData.mallInfo, mallId = _info$layoutData$mall.mallId, mallName = _info$layoutData$mall.mallName;
                        localStoreInfo.push({
                          mallId: mallId,
                          mallName: mallName,
                          siteId: info.localInfo.site,
                          marketPlaceName: info.marketPlaceName,
                          region: info._region,
                          storeType: '本土',
                          isSemiManagedMall: true
                        });
                      }

                      (_temu$localStoreInfo = temu.localStoreInfo).push.apply(_temu$localStoreInfo, localStoreInfo);

                      storeInfo.push.apply(storeInfo, _toConsumableArray(localStoreInfo.map(function (item) {
                        return item.mallId;
                      })));

                    case 10:
                    case "end":
                      return _context3.stop();
                  }
                }
              }, _loop);
            });

            _iterator.s();

          case 18:
            if ((_step = _iterator.n()).done) {
              _context6.next = 25;
              break;
            }

            return _context6.delegateYield(_loop(), "t0", 20);

          case 20:
            _ret = _context6.t0;

            if (!(_ret === "continue")) {
              _context6.next = 23;
              break;
            }

            return _context6.abrupt("continue", 23);

          case 23:
            _context6.next = 18;
            break;

          case 25:
            _context6.next = 30;
            break;

          case 27:
            _context6.prev = 27;
            _context6.t1 = _context6["catch"](15);

            _iterator.e(_context6.t1);

          case 30:
            _context6.prev = 30;

            _iterator.f();

            return _context6.finish(30);

          case 33:
            if (!euInfo) {
              _context6.next = 35;
              break;
            }

            return _context6.delegateYield( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
              var curMallId, curMallName, curSiteId, curMarketPlaceName, marketPlaceList, allAccounts, infoMap, _iterator2, _step2, _loop2, _ret2, backRes;

              return _regeneratorRuntime().wrap(function _callee3$(_context5) {
                while (1) {
                  switch (_context5.prev = _context5.next) {
                    case 0:
                      curMallId = euInfo.layoutData.mallData.mallInfo.mallId;
                      curMallName = euInfo.layoutData.mallData.mallInfo.mallName;
                      curSiteId = euInfo.layoutData.marketplaceData.currentMarketPlace.siteId;
                      curMarketPlaceName = euInfo.layoutData.marketplaceData.currentMarketPlace.marketPlaceName;
                      marketPlaceList = euInfo.layoutData.marketplaceData.marketPlaceList; // 获取当前店铺下所有账号信息

                      _context5.next = 7;
                      return getTemuLocalAccount(temu.euHost);

                    case 7:
                      allAccounts = _context5.sent;
                      // 站点id映射，key: 店铺id  value: 站点id&店铺名
                      infoMap = {};

                      if (allAccounts.length > 0) {
                        allAccounts.forEach(function (_ref9) {
                          var mall_id = _ref9.mall_id,
                              mall_name = _ref9.mall_name;
                          infoMap[mall_id] = {
                            siteId: curSiteId,
                            marketPlaceName: curMarketPlaceName,
                            mallName: mall_name
                          };
                        });
                      } else infoMap[curMallId] = {
                        siteId: curSiteId,
                        marketPlaceName: curMarketPlaceName,
                        mallName: curMallName
                      }; // 遍历所有站点，获取全部店铺信息


                      _iterator2 = _createForOfIteratorHelper(marketPlaceList);
                      _context5.prev = 11;
                      _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2() {
                        var marketPlace, siteId, _res2, _allAccounts, _euInfo, _euInfo$layoutData$ma, _siteId, marketPlaceName, mallName;

                        return _regeneratorRuntime().wrap(function _loop2$(_context4) {
                          while (1) {
                            switch (_context4.prev = _context4.next) {
                              case 0:
                                marketPlace = _step2.value;
                                siteId = marketPlace.siteId;

                                if (!(siteId && siteId !== curSiteId)) {
                                  _context4.next = 23;
                                  break;
                                }

                                _context4.next = 5;
                                return changeTemuEuSite(siteId);

                              case 5:
                                _res2 = _context4.sent;

                                if (_res2) {
                                  _context4.next = 8;
                                  break;
                                }

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

                              case 8:
                                _context4.next = 10;
                                return getTemuLocalAccount(temu.euHost);

                              case 10:
                                _allAccounts = _context4.sent;

                                if (!((_allAccounts === null || _allAccounts === void 0 ? void 0 : _allAccounts.length) > 0)) {
                                  _context4.next = 15;
                                  break;
                                }

                                _allAccounts.forEach(function (_ref10) {
                                  var mall_id = _ref10.mall_id,
                                      mall_name = _ref10.mall_name;
                                  infoMap[mall_id] = {
                                    siteId: siteId,
                                    marketPlaceName: marketPlace.marketPlaceName,
                                    mallName: mall_name
                                  };
                                });

                                _context4.next = 23;
                                break;

                              case 15:
                                _context4.next = 17;
                                return checkTemuEuLocal();

                              case 17:
                                _euInfo = _context4.sent;

                                if (_euInfo) {
                                  _context4.next = 20;
                                  break;
                                }

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

                              case 20:
                                _euInfo$layoutData$ma = _euInfo.layoutData.marketplaceData.currentMarketPlace, _siteId = _euInfo$layoutData$ma.siteId, marketPlaceName = _euInfo$layoutData$ma.marketPlaceName;
                                mallName = _euInfo.layoutData.mallData.mallInfo.mallName;
                                infoMap[_euInfo.layoutData.mallData.mallInfo.mallId] = {
                                  siteId: _siteId,
                                  marketPlaceName: marketPlaceName,
                                  mallName: mallName
                                };

                              case 23:
                              case "end":
                                return _context4.stop();
                            }
                          }
                        }, _loop2);
                      });

                      _iterator2.s();

                    case 14:
                      if ((_step2 = _iterator2.n()).done) {
                        _context5.next = 21;
                        break;
                      }

                      return _context5.delegateYield(_loop2(), "t0", 16);

                    case 16:
                      _ret2 = _context5.t0;

                      if (!(_ret2 === "continue")) {
                        _context5.next = 19;
                        break;
                      }

                      return _context5.abrupt("continue", 19);

                    case 19:
                      _context5.next = 14;
                      break;

                    case 21:
                      _context5.next = 26;
                      break;

                    case 23:
                      _context5.prev = 23;
                      _context5.t1 = _context5["catch"](11);

                      _iterator2.e(_context5.t1);

                    case 26:
                      _context5.prev = 26;

                      _iterator2.f();

                      return _context5.finish(26);

                    case 29:
                      _context5.next = 31;
                      return changeTemuEuSite(curSiteId);

                    case 31:
                      backRes = _context5.sent;

                      // 没切换回去？看要不要在页面弹窗一下
                      if (!backRes) {// do something
                      }

                      Object.keys(infoMap).forEach(function (key) {
                        var _infoMap$key = infoMap[key],
                            siteId = _infoMap$key.siteId,
                            marketPlaceName = _infoMap$key.marketPlaceName,
                            mallName = _infoMap$key.mallName;
                        storeInfo.push(key);
                        temu.localStoreInfo.push({
                          mallId: key,
                          mallName: mallName,
                          siteId: siteId,
                          marketPlaceName: marketPlaceName,
                          region: 'eu',
                          storeType: '本土',
                          isSemiManagedMall: true
                        });
                      });

                    case 34:
                    case "end":
                      return _context5.stop();
                  }
                }
              }, _callee3, null, [[11, 23, 26, 29]]);
            })(), "t2", 35);

          case 35:
            return _context6.abrupt("return", storeInfo);

          case 38:
            _context6.prev = 38;
            _context6.t3 = _context6["catch"](0);
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].report("temu\u68C0\u6D4B\u7AD9\u70B9\u62A5\u9519,\u89C4\u5219\u53EF\u80FD\u5DF2\u6539\u53D8---".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context6.t3)), 'error');
            return _context6.abrupt("return", false);

          case 42:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee4, null, [[0, 38], [15, 27, 30, 33]]);
  }));

  return function temuCheckSite() {
    return _ref6.apply(this, arguments);
  };
}();
/**
 * @description 检测跨境店铺是否在线，在线则返回店铺信息
 */

var checkTemuCb = /*#__PURE__*/function () {
  var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
    var _yield$axios, data, companyList, storeList, errorMsg;

    return _regeneratorRuntime().wrap(function _callee5$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            _context7.prev = 0;
            _context7.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: "".concat(temu.cbHost, "/bg/quiet/api/mms/userInfo"),
              method: 'post'
            });

          case 3:
            _yield$axios = _context7.sent;
            data = _yield$axios.data;
            companyList = data && data.result && data.result.companyList;

            if (!companyList) {
              _context7.next = 9;
              break;
            }

            storeList = companyList.reduce(function (arr, i) {
              if (i.malInfoList && i.malInfoList.length) {
                arr = arr.concat(i.malInfoList);
              }

              return arr;
            }, []);
            return _context7.abrupt("return", storeList.length > 0 && storeList);

          case 9:
            _context7.next = 15;
            break;

          case 11:
            _context7.prev = 11;
            _context7.t0 = _context7["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context7.t0);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u8DE8\u5883\u7AD9\u70B9\u672A\u767B\u5F55");
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u8DE8\u5883\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));
            }

          case 15:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee5, null, [[0, 11]]);
  }));

  return function checkTemuCb() {
    return _ref11.apply(this, arguments);
  };
}();
/**
 * @description 检测跨境美区/欧区店铺是否在线
 */

var checkTemuCbUS = /*#__PURE__*/function () {
  var _ref13 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref12) {
    var host, Mallid, _yield$axios2, data, mallList, errorMsg;

    return _regeneratorRuntime().wrap(function _callee6$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            host = _ref12.host, Mallid = _ref12.Mallid;
            _context8.prev = 1;
            _context8.next = 4;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: "".concat(host, "/api/seller/auth/userInfo"),
              method: 'post',
              headers: {
                Mallid: Mallid
              }
            });

          case 4:
            _yield$axios2 = _context8.sent;
            data = _yield$axios2.data;
            mallList = data && data.result && data.result.mallList;
            return _context8.abrupt("return", mallList.length > 0 && mallList);

          case 10:
            _context8.prev = 10;
            _context8.t0 = _context8["catch"](1);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context8.t0);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu".concat(host, "\u8DE8\u5883\u7AD9\u70B9\u672A\u767B\u5F55"));
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu".concat(host, "\u8DE8\u5883\u7AD9\u70B9\u8BF7\u6C42\u62A5\u9519-----").concat(errorMsg));
            }

          case 14:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee6, null, [[1, 10]]);
  }));

  return function checkTemuCbUS(_x2) {
    return _ref13.apply(this, arguments);
  };
}();
var checkTemuCbTask = /*#__PURE__*/function () {
  var _ref14 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(id, task, count) {
    return _regeneratorRuntime().wrap(function _callee9$(_context11) {
      while (1) {
        switch (_context11.prev = _context11.next) {
          case 0:
            if (!(count > 40)) {
              _context11.next = 3;
              break;
            }

            chrome.tabs.remove(id);
            return _context11.abrupt("return", {
              code: 13
            });

          case 3:
            return _context11.abrupt("return", new Promise(function (resolve) {
              setTimeout(function () {
                chrome.tabs.get(id, /*#__PURE__*/function () {
                  var _ref15 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(tab) {
                    var r, _yield$getCookies, value, executeFunc;

                    return _regeneratorRuntime().wrap(function _callee8$(_context10) {
                      while (1) {
                        switch (_context10.prev = _context10.next) {
                          case 0:
                            _context10.prev = 0;

                            if (tab) {
                              _context10.next = 7;
                              break;
                            }

                            chrome.tabs.remove(id);
                            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog('切换分区站点页面可能已被关闭2');
                            resolve({
                              code: 16
                            });
                            _context10.next = 23;
                            break;

                          case 7:
                            if (!(tab.status == 'loading')) {
                              _context10.next = 14;
                              break;
                            }

                            _context10.next = 10;
                            return checkTemuCbTask(id, task, ++count);

                          case 10:
                            r = _context10.sent;
                            resolve(r);
                            _context10.next = 23;
                            break;

                          case 14:
                            if (!(tab.status == 'complete')) {
                              _context10.next = 23;
                              break;
                            }

                            _context10.next = 17;
                            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* getCookies */ "p"])({
                              url: task.host,
                              name: 'mallid'
                            });

                          case 17:
                            _yield$getCookies = _context10.sent;
                            value = _yield$getCookies.value;
                            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u5F53\u524D\u5E97\u94FAid\uFF1A".concat(value, "\uFF0C\u9700\u8981\u5207\u6362\u5E97\u94FA\uFF1A").concat(task.Mallid));
                            _context10.next = 22;
                            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* delayed */ "h"])(1000);

                          case 22:
                            if (value === task.Mallid) {
                              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog('当前店铺id与需要切换店铺id一致，不需要切换店铺'); // chrome.tabs.remove(id)

                              resolve(true);
                            } else {
                              executeFunc = function executeFunc() {
                                try {
                                  // 优化选择器，提高兼容性
                                  var button = document.querySelector('div[data-testid="beast-core-modal-body"] button'); // 如果第一个选择器没找到，尝试备用选择器

                                  if (!button) {
                                    button = document.querySelector('div[data-testid="beast-core-modal-body"] div button');
                                  }

                                  console.log('buttonbuttonbutton', button);

                                  if (button) {
                                    button.click();
                                    return true;
                                  }

                                  return false; // const res = await fetch(`${taskData.host}/api/seller/auth/loginByCode`, {
                                  //   method: 'POST',
                                  //   headers: {
                                  //     'Content-Type': 'application/json'
                                  //   },
                                  //   body: JSON.stringify({
                                  //     code: taskData.code,
                                  //     confirm: true,
                                  //     targetMallId: taskData.Mallid
                                  //   })
                                  // })
                                  // const { success } = await res.json()
                                  // return success
                                } catch (error) {
                                  return false;
                                }
                              }; // 注入脚本


                              chrome.scripting.executeScript({
                                target: {
                                  tabId: id
                                },
                                func: executeFunc
                              }).then( /*#__PURE__*/function () {
                                var _ref16 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(results) {
                                  var result, retryResult;
                                  return _regeneratorRuntime().wrap(function _callee7$(_context9) {
                                    while (1) {
                                      switch (_context9.prev = _context9.next) {
                                        case 0:
                                          if (!(!results || !results[0])) {
                                            _context9.next = 4;
                                            break;
                                          }

                                          _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog('脚本执行失败：无返回结果'); // chrome.tabs.remove(id)

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

                                        case 4:
                                          result = results[0].result;

                                          if (!(result === true)) {
                                            _context9.next = 13;
                                            break;
                                          }

                                          _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog('切换店铺成功');
                                          _context9.next = 9;
                                          return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* delayed */ "h"])(1000);

                                        case 9:
                                          chrome.tabs.remove(id);
                                          resolve(true);
                                          _context9.next = 18;
                                          break;

                                        case 13:
                                          _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u7B2C".concat(count + 1, "\u6B21\u67E5\u627E\u6309\u94AE\u5931\u8D25\uFF0C\u7B49\u5F85\u91CD\u8BD5..."));
                                          _context9.next = 16;
                                          return checkTemuCbTask(id, task, ++count);

                                        case 16:
                                          retryResult = _context9.sent;
                                          resolve(retryResult);

                                        case 18:
                                        case "end":
                                          return _context9.stop();
                                      }
                                    }
                                  }, _callee7);
                                }));

                                return function (_x7) {
                                  return _ref16.apply(this, arguments);
                                };
                              }()).catch(function (error) {
                                _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u811A\u672C\u6267\u884C\u5931\u8D25\uFF1A".concat(error.message));
                                chrome.tabs.remove(id);
                                resolve(false);
                              });
                            }
                            /** 页面加载完成 */
                            // const list = await checkTemuCbUS(task)
                            // if(list) {
                            // }else{
                            //   let r = await checkTemuCbTask(id, task, ++count)
                            //   resolve(r)
                            // }


                          case 23:
                            _context10.next = 30;
                            break;

                          case 25:
                            _context10.prev = 25;
                            _context10.t0 = _context10["catch"](0);

                            if (tab) {
                              chrome.tabs.remove(tab.id);
                            }

                            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("checkTemuCbTask error\uFF1A".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context10.t0)));
                            resolve({
                              code: 17,
                              msg: "checkTemuCbTask error".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context10.t0))
                            });

                          case 30:
                          case "end":
                            return _context10.stop();
                        }
                      }
                    }, _callee8, null, [[0, 25]]);
                  }));

                  return function (_x6) {
                    return _ref15.apply(this, arguments);
                  };
                }());
              }, 1000);
            }));

          case 4:
          case "end":
            return _context11.stop();
        }
      }
    }, _callee9);
  }));

  return function checkTemuCbTask(_x3, _x4, _x5) {
    return _ref14.apply(this, arguments);
  };
}();
/**
 * @description 检测美国本土店铺是否在线，在线则返回店铺信息
 */

var checkTemuUsLocal = /*#__PURE__*/function () {
  var _ref17 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
    var _yield$axios3, data, str, _JSON$parse, store, region, errorMsg;

    return _regeneratorRuntime().wrap(function _callee10$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            _context12.prev = 0;
            _context12.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: temu.usHost + '/home.html',
              method: 'get'
            });

          case 3:
            _yield$axios3 = _context12.sent;
            data = _yield$axios3.data;

            if (!data) {
              _context12.next = 18;
              break;
            }

            _context12.prev = 6;
            str = data.replace(/[\r\n\s]+/g, '');
            _JSON$parse = JSON.parse(str.split('window.rawData=')[1].split(';document')[0]), store = _JSON$parse.store;
            region = JSON.parse(str.split('window.__REGION_CONFIG__=')[1].split(';window.__DOC_SOURCE__="ssr"')[0]); // 记录本土店铺所有国家siteid

            temu.siteIds = region;

            if (!(store.layoutData && store.layoutData.marketplaceData)) {
              _context12.next = 13;
              break;
            }

            return _context12.abrupt("return", store);

          case 13:
            _context12.next = 18;
            break;

          case 15:
            _context12.prev = 15;
            _context12.t0 = _context12["catch"](6);
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].report("temu\u68C0\u6D4B\u7F8E\u533A\u672C\u571F\u5E97\u62A5\u9519\uFF0C\u53EF\u80FD\u89C4\u5219\u5DF2\u6539\u53D8-----".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context12.t0)), 'error');

          case 18:
            _context12.next = 24;
            break;

          case 20:
            _context12.prev = 20;
            _context12.t1 = _context12["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context12.t1);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u7F8E\u533A\u672C\u571F\u7AD9\u70B9\u672A\u767B\u5F55");
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u7F8E\u533A\u672C\u571F\u7AD9\u70B9\u62A5\u9519-----".concat(errorMsg));
            }

          case 24:
          case "end":
            return _context12.stop();
        }
      }
    }, _callee10, null, [[0, 20], [6, 15]]);
  }));

  return function checkTemuUsLocal() {
    return _ref17.apply(this, arguments);
  };
}();
/**
 * @description 检测欧洲本土店铺是否在线，在线则返回店铺信息
 */

var checkTemuEuLocal = /*#__PURE__*/function () {
  var _ref18 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
    var _yield$axios4, data, str, _JSON$parse2, store, errorMsg;

    return _regeneratorRuntime().wrap(function _callee11$(_context13) {
      while (1) {
        switch (_context13.prev = _context13.next) {
          case 0:
            _context13.prev = 0;
            _context13.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: temu.euHost + '/home.html',
              method: 'get'
            });

          case 3:
            _yield$axios4 = _context13.sent;
            data = _yield$axios4.data;

            if (!data) {
              _context13.next = 16;
              break;
            }

            _context13.prev = 6;
            str = data.replace(/[\r\n\s]+/g, '');
            _JSON$parse2 = JSON.parse(str.split('window.rawData=')[1].split(';document')[0]), store = _JSON$parse2.store;

            if (!(store.layoutData && store.layoutData.marketplaceData)) {
              _context13.next = 11;
              break;
            }

            return _context13.abrupt("return", store);

          case 11:
            _context13.next = 16;
            break;

          case 13:
            _context13.prev = 13;
            _context13.t0 = _context13["catch"](6);
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].report("temu\u68C0\u6D4B\u6B27\u533A\u672C\u571F\u5E97\u62A5\u9519\uFF0C\u53EF\u80FD\u89C4\u5219\u5DF2\u6539\u53D8-----".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context13.t0)), 'error');

          case 16:
            _context13.next = 22;
            break;

          case 18:
            _context13.prev = 18;
            _context13.t1 = _context13["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context13.t1);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u6B27\u533A\u672C\u571F\u7AD9\u70B9\u672A\u767B\u5F55");
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u6B27\u533A\u672C\u571F\u7AD9\u70B9\u62A5\u9519-----".concat(errorMsg));
            }

          case 22:
          case "end":
            return _context13.stop();
        }
      }
    }, _callee11, null, [[0, 18], [6, 13]]);
  }));

  return function checkTemuEuLocal() {
    return _ref18.apply(this, arguments);
  };
}();
/**
 * @description 检测全球其他本土店铺是否在线，在线则返回店铺信息
 */

var checkTemuGlobalLocal = /*#__PURE__*/function () {
  var _ref19 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(region) {
    var HostMap, _yield$axios5, data, str, _JSON$parse3, store, errorMsg;

    return _regeneratorRuntime().wrap(function _callee12$(_context14) {
      while (1) {
        switch (_context14.prev = _context14.next) {
          case 0:
            HostMap = {
              'mx': {
                host: temu.mxHost,
                marketPlaceName: '墨西哥'
              },
              'kr': {
                host: temu.krHost,
                marketPlaceName: '韩国'
              },
              'br': {
                host: temu.brHost,
                marketPlaceName: '巴西'
              },
              'jp': {
                host: temu.jpHost,
                marketPlaceName: '日本'
              },
              'ca': {
                host: temu.caHost,
                marketPlaceName: '加拿大'
              }
            }; // 检查region参数是否有效

            if (HostMap[region]) {
              _context14.next = 4;
              break;
            }

            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u5168\u7403\u5176\u4ED6\u672C\u571F\u5E97\u94FA\u5931\u8D25----\u4F20\u5165\u4E0D\u652F\u6301\u7684region\u53C2\u6570: ".concat(region));
            return _context14.abrupt("return", false);

          case 4:
            _context14.prev = 4;
            _context14.next = 7;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: HostMap[region].host + '/home.html',
              method: 'get'
            });

          case 7:
            _yield$axios5 = _context14.sent;
            data = _yield$axios5.data;

            if (!data) {
              _context14.next = 20;
              break;
            }

            _context14.prev = 10;
            str = data.replace(/[\r\n\s]+/g, '');
            _JSON$parse3 = JSON.parse(str.split('window.rawData=')[1].split(';document')[0]), store = _JSON$parse3.store;

            if (!(store.layoutData && store.layoutData.marketplaceData)) {
              _context14.next = 15;
              break;
            }

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

          case 15:
            _context14.next = 20;
            break;

          case 17:
            _context14.prev = 17;
            _context14.t0 = _context14["catch"](10);
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].report("temu\u68C0\u6D4B".concat(HostMap[region].marketPlaceName, "\u672C\u571F\u5E97\u62A5\u9519\uFF0C\u53EF\u80FD\u89C4\u5219\u5DF2\u6539\u53D8-----").concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context14.t0)), 'error');

          case 20:
            _context14.next = 26;
            break;

          case 22:
            _context14.prev = 22;
            _context14.t1 = _context14["catch"](4);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context14.t1);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu".concat(HostMap[region].marketPlaceName, "\u672C\u571F\u7AD9\u70B9\u672A\u767B\u5F55"));
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu".concat(HostMap[region].marketPlaceName, "\u672C\u571F\u7AD9\u70B9\u62A5\u9519-----").concat(errorMsg));
            }

          case 26:
          case "end":
            return _context14.stop();
        }
      }
    }, _callee12, null, [[4, 22], [10, 17]]);
  }));

  return function checkTemuGlobalLocal(_x8) {
    return _ref19.apply(this, arguments);
  };
}();
/**
 * @description 欧区切换站点
 */

var changeTemuEuSite = /*#__PURE__*/function () {
  var _ref20 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(siteId) {
    var _yield$axios6, data, errorMsg;

    return _regeneratorRuntime().wrap(function _callee13$(_context15) {
      while (1) {
        switch (_context15.prev = _context15.next) {
          case 0:
            _context15.prev = 0;
            _context15.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: "".concat(temu.euHost, "/mms/floyd/marketplace/switch"),
              method: 'post',
              data: {
                target_site_id: siteId,
                biz_scene: 0
              }
            });

          case 3:
            _yield$axios6 = _context15.sent;
            data = _yield$axios6.data;

            if (!data.success) {
              _context15.next = 7;
              break;
            }

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

          case 7:
            _context15.next = 14;
            break;

          case 9:
            _context15.prev = 9;
            _context15.t0 = _context15["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context15.t0);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u6B27\u533A\u672C\u571F\u7AD9\u70B9\u672A\u767B\u5F55");
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u68C0\u6D4Btemu\u6B27\u533A\u672C\u571F\u7AD9\u70B9\u62A5\u9519-----".concat(errorMsg));
            }

            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u5207\u6362temu\u6B27\u533A\u7AD9\u70B9\u62A5\u9519-----".concat(errorMsg));

          case 14:
          case "end":
            return _context15.stop();
        }
      }
    }, _callee13, null, [[0, 9]]);
  }));

  return function changeTemuEuSite(_x9) {
    return _ref20.apply(this, arguments);
  };
}();
/**
 * @description 本土获取当前店铺所有账号
 */

var getTemuLocalAccount = /*#__PURE__*/function () {
  var _ref21 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(host) {
    var _data$result, _data$result$malls, _yield$axios7, data, errorMsg;

    return _regeneratorRuntime().wrap(function _callee14$(_context16) {
      while (1) {
        switch (_context16.prev = _context16.next) {
          case 0:
            _context16.prev = 0;
            _context16.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: host + '/mms/holly/mall/manage/list',
              method: 'post',
              data: {}
            });

          case 3:
            _yield$axios7 = _context16.sent;
            data = _yield$axios7.data;

            if (!(data !== null && data !== void 0 && data.success && ((_data$result = data.result) === null || _data$result === void 0 ? void 0 : (_data$result$malls = _data$result.malls) === null || _data$result$malls === void 0 ? void 0 : _data$result$malls.length) > 0)) {
              _context16.next = 9;
              break;
            }

            return _context16.abrupt("return", data.result.malls);

          case 9:
            return _context16.abrupt("return", []);

          case 10:
            _context16.next = 16;
            break;

          case 12:
            _context16.prev = 12;
            _context16.t0 = _context16["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context16.t0);

            if (errorMsg.indexOf('403') > -1) {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u83B7\u53D6temu\u672C\u571F\u5E97\u94FA\u6240\u6709\u8D26\u53F7\u5931\u8D25");
            } else {
              _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u83B7\u53D6temu\u672C\u571F\u5E97\u94FA\u6240\u6709\u8D26\u53F7\u5931\u8D25-----".concat(errorMsg));
            }

          case 16:
          case "end":
            return _context16.stop();
        }
      }
    }, _callee14, null, [[0, 12]]);
  }));

  return function getTemuLocalAccount(_x10) {
    return _ref21.apply(this, arguments);
  };
}();
/**
 * 本土店铺切换语言
 */

var changeLanguage = /*#__PURE__*/function () {
  var _ref22 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee15(type) {
    var host, _yield$Promise$all, _yield$Promise$all2, siteCookie, languageCookie, site_id, lang, store, _yield$axios8, data, setCookieRes;

    return _regeneratorRuntime().wrap(function _callee15$(_context17) {
      while (1) {
        switch (_context17.prev = _context17.next) {
          case 0:
            if (type) {
              _context17.next = 2;
              break;
            }

            return _context17.abrupt("return");

          case 2:
            _context17.prev = 2;
            host = {
              us: temu.usHost,
              eu: temu.euHost
            }[type]; // 通过cookie获取当前站点和语言

            _context17.t0 = Promise;
            _context17.t1 = Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* getCookies */ "p"])({
              url: host,
              name: 'seller_site'
            });
            _context17.next = 8;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* getCookies */ "p"])({
              url: host,
              name: 'seller_language'
            });

          case 8:
            _context17.t2 = _context17.sent;
            _context17.t3 = [_context17.t1, _context17.t2];
            _context17.next = 12;
            return _context17.t0.all.call(_context17.t0, _context17.t3);

          case 12:
            _yield$Promise$all = _context17.sent;
            _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
            siteCookie = _yield$Promise$all2[0];
            languageCookie = _yield$Promise$all2[1];
            site_id = siteCookie.value;
            lang = languageCookie.value; // 如果通过cookie获取siteid和当前语言失败，则通过接口拿

            if (!(!site_id || !lang)) {
              _context17.next = 26;
              break;
            }

            _context17.next = 21;
            return checkTemuEuLocal();

          case 21:
            store = _context17.sent;

            if (store) {
              _context17.next = 24;
              break;
            }

            return _context17.abrupt("return");

          case 24:
            site_id = store.localInfo.site;
            lang = store.localInfo.language;

          case 26:
            if (!(lang === 'en')) {
              _context17.next = 29;
              break;
            }

            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("[".concat(type, "]\u5F53\u524D\u8BED\u8A00\u4E3Aen\uFF0C\u4E0D\u9700\u8981\u5207\u6362"));
            return _context17.abrupt("return");

          case 29:
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("[".concat(type, "]\u5F53\u524D\u8BED\u8A00").concat(site_id, "\uFF0C\u51C6\u5907\u5207\u6362\u81F3en")); // 此接口作用不知道是啥，但是temu有调，那我们也要调

            _context17.next = 32;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: "".concat(host, "/api/bg/christiaan/change/site/lang/report"),
              method: 'post',
              data: {
                before: {
                  site_id: site_id,
                  lang: lang
                },
                after: {
                  site_id: site_id,
                  lang: "en"
                },
                scene: 10000,
                path: "/home.html"
              }
            });

          case 32:
            _yield$axios8 = _context17.sent;
            data = _yield$axios8.data;

            if (data) {
              _context17.next = 37;
              break;
            }

            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("[".concat(type, "]\u8BF7\u6C42\u5207\u6362\u8BED\u8A00\u63A5\u53E3\u5931\u8D25"));
            return _context17.abrupt("return");

          case 37:
            _context17.next = 39;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* setCookies */ "H"])({
              url: host,
              name: 'seller_language',
              value: 'en'
            });

          case 39:
            setCookieRes = _context17.sent;

            if (!(setCookieRes && setCookieRes.value === 'en')) {
              _context17.next = 42;
              break;
            }

            return _context17.abrupt("return", true);

          case 42:
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("[".concat(type, "]\u8BED\u8A00\u5207\u6362\u5931\u8D25"));
            _context17.next = 48;
            break;

          case 45:
            _context17.prev = 45;
            _context17.t4 = _context17["catch"](2);
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("[".concat(type, "]\u5207\u6362temu ").concat(type, "\u7AD9\u70B9\u8BED\u8A00\u62A5\u9519-----").concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context17.t4)));

          case 48:
          case "end":
            return _context17.stop();
        }
      }
    }, _callee15, null, [[2, 45]]);
  }));

  return function changeLanguage(_x11) {
    return _ref22.apply(this, arguments);
  };
}();
var loginCb = /*#__PURE__*/function () {
  var _ref23 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee16(task) {
    var Mallid, redirectUrl, _yield$axios9, data, loginParams, _yield$nativeRequest, errorMsg, success;

    return _regeneratorRuntime().wrap(function _callee16$(_context18) {
      while (1) {
        switch (_context18.prev = _context18.next) {
          case 0:
            _context18.prev = 0;
            Mallid = task.platform_store_id, redirectUrl = task.host;
            _context18.next = 4;
            return axios__WEBPACK_IMPORTED_MODULE_0___default()({
              url: "https://seller.kuajingmaihuo.com/bg/quiet/api/auth/obtainCode",
              method: 'post',
              data: {
                redirectUrl: redirectUrl + '/main/authentication'
              },
              headers: {
                Mallid: Mallid
              }
            });

          case 4:
            _yield$axios9 = _context18.sent;
            data = _yield$axios9.data;

            if (!(data && data.success)) {
              _context18.next = 25;
              break;
            }

            loginParams = {
              code: data.result.code,
              confirm: true
            };

            if (isUniqueId(Mallid)) {
              loginParams.targetUniqueId = Mallid;
            } else {
              loginParams.targetMallId = Mallid;
            }

            _context18.next = 11;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* nativeRequest */ "z"])("".concat(redirectUrl, "/api/seller/auth/loginByCode"), 'post', loginParams);

          case 11:
            _yield$nativeRequest = _context18.sent;
            errorMsg = _yield$nativeRequest.errorMsg;
            success = _yield$nativeRequest.success;

            if (!success) {
              _context18.next = 21;
              break;
            }

            _context18.next = 17;
            return Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* setCookies */ "H"])({
              url: redirectUrl,
              name: 'mallid',
              value: String(Mallid)
            });

          case 17:
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog('切换temu分区站点成功');
            return _context18.abrupt("return", true);

          case 21:
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].report("\u5207\u6362temu\u5206\u533A\u7AD9\u70B9\u62A5\u9519\uFF0CloginByCode\u8BF7\u6C42\u5931\u8D25-----".concat(errorMsg));
            return _context18.abrupt("return", false);

          case 23:
            _context18.next = 27;
            break;

          case 25:
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u5207\u6362temu\u5206\u533A\u7AD9\u70B9\u62A5\u9519-----errorMsg: ".concat(data ? data.errorMsg : '', "----errorCode:").concat(data ? data.errorCode : ''));
            return _context18.abrupt("return", false);

          case 27:
            _context18.next = 33;
            break;

          case 29:
            _context18.prev = 29;
            _context18.t0 = _context18["catch"](0);
            _data_log__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].setLog("\u5207\u6362temu\u5206\u533A\u7AD9\u70B9\u62A5\u9519-----".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_2__[/* isError */ "u"])(_context18.t0, task)));
            return _context18.abrupt("return", false);

          case 33:
          case "end":
            return _context18.stop();
        }
      }
    }, _callee16, null, [[0, 29]]);
  }));

  return function loginCb(_x12) {
    return _ref23.apply(this, arguments);
  };
}(); // window.testUs = async () => {
//   const res = await loginCb(634418215364437, temu.cbEuHost)
//   log.setLog('testUs', res)
// }

/**
 * @description 优先返回 mallId（为了兼容mallid与uniqueid同时存在时，后端下发uniqueid，但temu接口仍需要传mallid的场景）
 * @param {string} id 店铺ID
 * @returns {string} 真正的 mallId
 */

var getRealMallId = function getRealMallId(id) {
  var storeIdMap = _common__WEBPACK_IMPORTED_MODULE_3__[/* multiPlatform */ "a"].storeIdMap || {}; // 1. 如果 id 本身就是 mallId (存在于 map 的 key 中)，且对应的 value 有值，说明它确实是 mallId

  if (Object.prototype.hasOwnProperty.call(storeIdMap, id) && storeIdMap[id] !== '') {
    return id;
  } // 2. 如果 id 是 uniqueId (存在于 map 的 value 中)，则反向查找其对应的 mallId (key)


  var foundEntry = Object.entries(storeIdMap).find(function (_ref24) {
    var _ref25 = _slicedToArray(_ref24, 2),
        mId = _ref25[0],
        uId = _ref25[1];

    return uId == id;
  });

  if (foundEntry) {
    return foundEntry[0]; // 返回 key，即 mallId
  } // 3. 如果在 map 中完全找不到（可能是只有 uniqueId 或未关联上），则保留原始 ID


  return id;
};
/**
 * @description 判断是否是 uniqueId
 * @param {string} Mallid 店铺ID
 * @returns {boolean} 是否是 uniqueId
 */

var isUniqueId = function isUniqueId(Mallid) {
  var id = String(Mallid);
  var map = _common__WEBPACK_IMPORTED_MODULE_3__[/* multiPlatform */ "a"].storeIdMap || {}; // 1.存在于values中，是uniqueid

  var isInValues = Object.values(map).some(function (v) {
    return String(v) === id;
  }); // 2. 存在于 keys 中且对应的 value 为 ""，也为uniqueid

  var isKeyWithEmptyValue = Object.prototype.hasOwnProperty.call(map, id) && map[id] === "";
  return isInValues || isKeyWithEmptyValue;
};

/***/ }),

/***/ "e38f":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return mercado; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return mercadoCheckSite; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return checkMercadoCb; });
/* unused harmony export getCbSiteInfo */
/* unused harmony export checkAllMercadoLocal */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return checkMercadoLocal; });
/* harmony import */ var _data_log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("6b23");
/* harmony import */ var _utils_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("ca00");
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__("bc3a");
/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var cheerio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__("02cc");
/* harmony import */ var cheerio__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(cheerio__WEBPACK_IMPORTED_MODULE_3__);
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 _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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

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 _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }





var mercado = {
  // 跨境Host - 商家中心
  cbHost: 'https://global-selling.mercadolibre.com',
  // 跨境host - 支付中心(数字银行)
  cbPagoHost: 'https://global-selling.mercadopago.com',
  // 本土host - 商家中心
  localHost: [{
    name: '阿根廷',
    host: 'https://www.mercadolibre.com.ar',
    value: 'AR'
  }, {
    name: '墨西哥',
    host: 'https://www.mercadolibre.com.mx',
    value: 'MX'
  }, {
    name: '哥伦比亚',
    host: 'https://www.mercadolibre.com.co',
    value: 'CO'
  }, {
    name: '秘鲁',
    host: 'https://www.mercadolibre.com.pe',
    value: 'PE'
  }, {
    name: '乌拉圭',
    host: 'https://www.mercadolibre.com.uy',
    value: 'UY'
  }, {
    name: '委内瑞拉',
    host: 'https://www.mercadolibre.com.ve',
    value: 'VE'
  }, {
    name: '厄瓜多尔',
    host: 'https://www.mercadolibre.com.ec',
    value: 'EC'
  }, {
    name: '巴拿马',
    host: 'https://www.mercadolibre.com.pa',
    value: 'PA'
  }, {
    name: '巴拉圭',
    host: 'https://www.mercadolibre.com.py',
    value: 'PY'
  }, {
    name: '洪都拉斯',
    host: 'https://www.mercadolibre.com.hn',
    value: 'HN'
  }, {
    name: '尼加拉瓜',
    host: 'https://www.mercadolibre.com.ni',
    value: 'NI'
  }, {
    name: '萨尔瓦多',
    host: 'https://www.mercadolibre.com.sv',
    value: 'SV'
  }, {
    name: '危地马拉',
    host: 'https://www.mercadolibre.com.gt',
    value: 'GT'
  }, {
    name: '多米尼加',
    host: 'https://www.mercadolibre.com.do',
    value: 'DO'
  }, {
    name: '玻利维亚',
    host: 'https://www.mercadolibre.com.bo',
    value: 'BO'
  }, {
    name: '巴西',
    host: 'https://www.mercadolivre.com.br',
    value: 'BR'
  }, {
    name: '智利',
    host: 'https://www.mercadolibre.cl',
    value: 'CL'
  }, {
    name: '哥斯达黎加',
    host: 'https://www.mercadolibre.co.cr',
    value: 'CR'
  }],

  // 本土host - 支付中心
  get localPagoHost() {
    return this.localHost.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        host: item.host.replace(/mercadolibre|mercadolivre/, 'mercadopago')
      });
    });
  },

  // 是否是获取支付中心数据的任务
  getPagoTask: [40001, 40002],

  /**
   * 跨境店铺下的所有站点的信息
   * @property {number} site_key - 站点key
   * @property {number} site_name - 站点名称
   * @property {string} site_user_id - 站点User_ID
   * @property {string} store_name - 店铺名称
  * 
   */
  cbSiteInfo: [],

  /**
   * 跨境店铺信息
   * @property {string} isCBT - 是否跨境店铺
   * @property {boolean} userId - 店铺 user_id
   * @property {string} mallId - 店铺ID(user_id)
   * @property {string} mallName - 店铺名称
   * @property {string} storeType - 店铺类型
  * 
   */
  cbStoreInfo: [],

  /**
   * 本土店铺信息
   * @property {string} siteId - 站点id
   * @property {string} userId - 店铺 user_id
   * @property {string} mallId - 店铺ID(user_id)
   * @property {string} mallName - 店铺名称
   * @property {string} region - 区域站点
   * @property {string} storeType - 本土
   */
  localStoreInfo: [],
  // declarativeNetRequest规则集id
  requestHearderIds: []
};
var siteKeyMap = {
  'MLM-remote': 'Mexico',
  'MLB-remote': 'Brazil',
  'MLC-remote': 'Chile',
  'MCO-remote': 'Colombia',
  'MLA-remote': 'Argentina',
  'MLU-remote': 'Uruguay',
  'MLM-fulfillment': 'Mexico (Full)',
  'MLC-fulfillment': 'Chile (Full)'
};
/**
 * @description 清除店铺信息
 */

var clearStoreInfo = function clearStoreInfo() {
  mercado.cbSiteInfo = [];
  mercado.cbStoreInfo = [];
  mercado.localStoreInfo = [];
}; // 为mercado所有接口带上Referer、Origin


var initMercadoUrlObserve = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
    var hosts;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            hosts = [mercado.cbHost, mercado.cbPagoHost].concat(_toConsumableArray(mercado.localHost.map(function (i) {
              return i.host;
            })), _toConsumableArray(mercado.localPagoHost.map(function (i) {
              return i.host;
            }))).filter(Boolean).map(function (h) {
              return h.trim();
            }); // 去重并执行设置

            _context.next = 3;
            return Promise.all(_toConsumableArray(new Set(hosts)).map(function (url) {
              return Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* setRequestHearder */ "I"])([{
                name: 'Referer',
                value: url
              }, {
                name: 'Origin',
                value: url
              }], "".concat(url, "/*"));
            }));

          case 3:
            mercado.requestHearderIds = _context.sent;

          case 4:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function initMercadoUrlObserve() {
    return _ref.apply(this, arguments);
  };
}();
/**
 * @description mercado检测站点
*/


var mercadoCheckSite = /*#__PURE__*/function () {
  var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
    var res, storeInfo, _res, cbInfo, localInfo;

    return _regeneratorRuntime().wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            clearStoreInfo();
            _context2.next = 4;
            return initMercadoUrlObserve();

          case 4:
            _context2.next = 6;
            return Promise.all([checkMercadoCb(), checkAllMercadoLocal()]);

          case 6:
            res = _context2.sent;
            storeInfo = [];
            _res = _slicedToArray(res, 2), cbInfo = _res[0], localInfo = _res[1]; // 整理跨境店铺信息

            if (!cbInfo) {
              _context2.next = 14;
              break;
            }

            // 获取站点信息
            // const siteUserId = await getCbSiteInfo()
            mercado.cbStoreInfo = cbInfo.map(function (item) {
              return _objectSpread(_objectSpread({}, item), {}, {
                mallId: item.userId,
                mallName: item.storeName,
                storeType: '跨境',
                isMercado: true
              });
            });
            storeInfo.push.apply(storeInfo, _toConsumableArray(mercado.cbStoreInfo.map(function (_ref3) {
              var userId = _ref3.userId;
              return userId;
            })));
            _context2.next = 14;
            return getCbSiteInfo();

          case 14:
            // 整理本土店铺信息
            if (localInfo && localInfo.length > 0) {
              _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog('本地站点信息', JSON.stringify(localInfo));
              mercado.localStoreInfo = localInfo;
              storeInfo.push.apply(storeInfo, _toConsumableArray(localInfo.map(function (_ref4) {
                var userId = _ref4.userId;
                return userId;
              })));
            }

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

          case 18:
            _context2.prev = 18;
            _context2.t0 = _context2["catch"](0);
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].report("mercado\u68C0\u6D4B\u7AD9\u70B9\u62A5\u9519,\u89C4\u5219\u53EF\u80FD\u5DF2\u6539\u53D8---".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context2.t0)), 'error');
            return _context2.abrupt("return", false);

          case 22:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2, null, [[0, 18]]);
  }));

  return function mercadoCheckSite() {
    return _ref2.apply(this, arguments);
  };
}();
/**
 * @description 检测跨境店铺是否在线，在线则返回店铺信息
 */

var checkMercadoCb = /*#__PURE__*/function () {
  var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
    var _yield$axios, html, _renderingCtxText$mat, $, storeName, renderingCtxText, userId, errorMsg, _errorMsg;

    return _regeneratorRuntime().wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.prev = 0;
            _context3.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_2___default()({
              url: "".concat(mercado.cbHost, "/sales-summary"),
              method: 'get'
            });

          case 3:
            _yield$axios = _context3.sent;
            html = _yield$axios.data;

            if (!html) {
              _context3.next = 13;
              break;
            }

            $ = cheerio__WEBPACK_IMPORTED_MODULE_3___default.a.load(html);
            storeName = $('#nav-header-cbt__logged-options .nav-header-cbt__profile-name').text().trim() || '';
            renderingCtxText = $('#__NORDIC_RENDERING_CTX__').html() || '';
            userId = ((_renderingCtxText$mat = renderingCtxText.match(/"userId"\s*:\s*(\d+)/)) === null || _renderingCtxText$mat === void 0 ? void 0 : _renderingCtxText$mat[1]) || '';
            return _context3.abrupt("return", [{
              userId: userId,
              storeName: storeName,
              isCBT: true
            }]);

          case 13:
            errorMsg = "\u5E97\u94FA\u767B\u5F55\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u9646\uFF0C\u539F\u62A5\u9519\u4FE1\u606F";
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog(errorMsg);

          case 15:
            _context3.next = 21;
            break;

          case 17:
            _context3.prev = 17;
            _context3.t0 = _context3["catch"](0);
            _errorMsg = "\u68C0\u6D4B\u8DE8\u5883\u5E97\u94FA\u662F\u5426\u5728\u7EBF\u5931\u8D25\uFF0C\u53EF\u80FD\u662F\u7F8E\u5BA2\u591A\u89C4\u5219\u5DF2\u6539\uFF0C\u539F\u62A5\u9519\u4FE1\u606F\uFF1A".concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context3.t0));
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog(_errorMsg);

          case 21:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3, null, [[0, 17]]);
  }));

  return function checkMercadoCb() {
    return _ref5.apply(this, arguments);
  };
}();
/**
 * @description 获取站点信息 - 跨境
 */

var getCbSiteInfo = /*#__PURE__*/function () {
  var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
    var _yield$axios2, data, sites, errorMsg;

    return _regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.prev = 0;
            _context4.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_2___default()({
              url: "".concat(mercado.cbHost, "/cbt-site-selector/modules/__resolve_props?module=site-selector&consumer=sso-seller-home-frontend"),
              method: 'get'
            });

          case 3:
            _yield$axios2 = _context4.sent;
            data = _yield$axios2.data;

            if (data && data.cbtUser && data.cbtUser.siteUsers) {
              // const siteUserId = data.cbtUser.siteUsers[0].parent_id || ''
              sites = data.cbtUser.siteUsers.map(function (item) {
                var siteKey = "".concat(item.site_id).concat(item.logistic_type === 'fulfillment' ? '-fulfillment' : '-remote');
                return {
                  site_key: siteKey,
                  site_user_id: item.user_id,
                  site_name: siteKeyMap[siteKey] || ''
                };
              });
              mercado.cbSiteInfo = sites;
              _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u8DE8\u5883\u7AD9\u70B9\u4FE1\u606F\u6210\u529F\uFF0C\u5171".concat(sites.length, "\u4E2A\u7AD9\u70B9")); // return siteUserId
            }

            _context4.next = 12;
            break;

          case 8:
            _context4.prev = 8;
            _context4.t0 = _context4["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context4.t0);
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u8DE8\u5883\u7AD9\u70B9\u4FE1\u606F\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));

          case 12:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4, null, [[0, 8]]);
  }));

  return function getCbSiteInfo() {
    return _ref6.apply(this, arguments);
  };
}();
/**
 * @description 检测本土店铺所有站点是否在线
 */

var checkAllMercadoLocal = /*#__PURE__*/function () {
  var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
    var loggedInSites, _iterator, _step, site, res;

    return _regeneratorRuntime().wrap(function _callee5$(_context5) {
      while (1) {
        switch (_context5.prev = _context5.next) {
          case 0:
            loggedInSites = [];
            _iterator = _createForOfIteratorHelper(mercado.localHost);
            _context5.prev = 2;

            _iterator.s();

          case 4:
            if ((_step = _iterator.n()).done) {
              _context5.next = 12;
              break;
            }

            site = _step.value;
            _context5.next = 8;
            return checkMercadoLocal(site.value);

          case 8:
            res = _context5.sent;

            if (res) {
              loggedInSites.push(res);
            }

          case 10:
            _context5.next = 4;
            break;

          case 12:
            _context5.next = 17;
            break;

          case 14:
            _context5.prev = 14;
            _context5.t0 = _context5["catch"](2);

            _iterator.e(_context5.t0);

          case 17:
            _context5.prev = 17;

            _iterator.f();

            return _context5.finish(17);

          case 20:
            return _context5.abrupt("return", loggedInSites);

          case 21:
          case "end":
            return _context5.stop();
        }
      }
    }, _callee5, null, [[2, 14, 17, 20]]);
  }));

  return function checkAllMercadoLocal() {
    return _ref7.apply(this, arguments);
  };
}();
/**
 * @description 检测本土店铺指定站点是否在线
 */

var checkMercadoLocal = /*#__PURE__*/function () {
  var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(region) {
    var site, _response$data, response, preStoreName, $, res, errorMsg;

    return _regeneratorRuntime().wrap(function _callee6$(_context6) {
      while (1) {
        switch (_context6.prev = _context6.next) {
          case 0:
            site = mercado.localHost.find(function (_ref9) {
              var value = _ref9.value;
              return value === region;
            });

            if (site) {
              _context6.next = 4;
              break;
            }

            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u672A\u627E\u5230region\u4E3A".concat(region, "\u7684\u5E97\u94FA\u4FE1\u606F"));
            return _context6.abrupt("return", false);

          case 4:
            _context6.prev = 4;
            _context6.next = 7;
            return axios__WEBPACK_IMPORTED_MODULE_2___default()({
              url: "".concat(site.host, "/pampa/profile"),
              method: 'GET',
              timeout: 10000 // 设置超时避免卡死

            });

          case 7:
            response = _context6.sent;

            if (!(response && (_response$data = response.data) !== null && _response$data !== void 0 && _response$data.includes('<html'))) {
              _context6.next = 22;
              break;
            }

            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u68C0\u6D4B\u5230 Mercado \u672C\u571F\u7AD9\u70B9\u5DF2\u767B\u5F55\uFF1A".concat(site.name)); // 本土站点优先从 /pampa/profile 的 html 里解析 storeName，解析不到再走后续兜底请求

            preStoreName = '';

            try {
              $ = cheerio__WEBPACK_IMPORTED_MODULE_3___default.a.load(response.data);
              preStoreName = $('.andes-typography--type-title').first().text().trim() || '';
              _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("Mercado\u672C\u571F\u7AD9\u70B9".concat(site.name, "\u89E3\u6790\u5230\u5E97\u94FA\u540D\u79F0\uFF1A").concat(preStoreName));
            } catch (err) {
              _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("Mercado\u672C\u571F\u7AD9\u70B9".concat(site.name, "\u89E3\u6790\u5E97\u94FA\u540D\u79F0\u5931\u8D25-----").concat(Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(err)));
            }

            _context6.next = 14;
            return getLocalSiteInfo(site.host, preStoreName);

          case 14:
            res = _context6.sent;

            if (!res) {
              _context6.next = 19;
              break;
            }

            return _context6.abrupt("return", {
              userId: res.userId,
              mallId: res.userId,
              siteId: res.siteId,
              region: site.value,
              // 区域
              mallName: res.storeName,
              storeType: '本土',
              isMercado: true
            });

          case 19:
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9".concat(site.name, "\u4FE1\u606F\u672A\u767B\u5F55"));

          case 20:
            _context6.next = 23;
            break;

          case 22:
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9".concat(site.name, "\u4FE1\u606F\u672A\u767B\u5F55"));

          case 23:
            _context6.next = 29;
            break;

          case 25:
            _context6.prev = 25;
            _context6.t0 = _context6["catch"](4);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context6.t0);
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9".concat(site.name, "\u4FE1\u606F\u8BF7\u6C42\u62A5\u9519-----").concat(errorMsg));

          case 29:
          case "end":
            return _context6.stop();
        }
      }
    }, _callee6, null, [[4, 25]]);
  }));

  return function checkMercadoLocal(_x) {
    return _ref8.apply(this, arguments);
  };
}();
/**
 * @description 获取本土站点信息
 * @param {string} host 站点host
 * @param {string} [preStoreName] 已从 /pampa/profile 解析得到的店铺名称，传入则跳过额外请求
 */

var getLocalSiteInfo = /*#__PURE__*/function () {
  var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(host) {
    var preStoreName,
        _yield$axios3,
        data,
        storeName,
        _data$userInfo,
        userId,
        isCBT,
        siteId,
        errorMsg,
        _args7 = arguments;

    return _regeneratorRuntime().wrap(function _callee7$(_context7) {
      while (1) {
        switch (_context7.prev = _context7.next) {
          case 0:
            preStoreName = _args7.length > 1 && _args7[1] !== undefined ? _args7[1] : '';
            _context7.prev = 1;
            _context7.next = 4;
            return axios__WEBPACK_IMPORTED_MODULE_2___default()({
              url: "".concat(host, "/seller-journey-microfrontend/modules/__resolve_props?module=firststeps"),
              method: 'GET'
            });

          case 4:
            _yield$axios3 = _context7.sent;
            data = _yield$axios3.data;

            if (!(data && data.userInfo && data.userInfo.userId)) {
              _context7.next = 17;
              break;
            }

            _context7.t0 = preStoreName;

            if (_context7.t0) {
              _context7.next = 12;
              break;
            }

            _context7.next = 11;
            return getLocalStoreNameInfo(host);

          case 11:
            _context7.t0 = _context7.sent;

          case 12:
            storeName = _context7.t0;
            _data$userInfo = data.userInfo, userId = _data$userInfo.userId, isCBT = _data$userInfo.isCBT, siteId = _data$userInfo.siteId;
            return _context7.abrupt("return", {
              userId: userId,
              isCBT: isCBT,
              siteId: siteId,
              storeName: storeName
            });

          case 17:
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9".concat(host, "\u4FE1\u606F\u672A\u767B\u5F55"));
            return _context7.abrupt("return", false);

          case 19:
            _context7.next = 26;
            break;

          case 21:
            _context7.prev = 21;
            _context7.t1 = _context7["catch"](1);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context7.t1);
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9".concat(host, "\u4FE1\u606F\u8BF7\u6C42\u62A5\u9519-----").concat(errorMsg));
            return _context7.abrupt("return", false);

          case 26:
          case "end":
            return _context7.stop();
        }
      }
    }, _callee7, null, [[1, 21]]);
  }));

  return function getLocalSiteInfo(_x2) {
    return _ref10.apply(this, arguments);
  };
}();
/**
 * @description 获取本土站点店铺名称信息
 */


var getLocalStoreNameInfo = /*#__PURE__*/function () {
  var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(host) {
    var _yield$axios4, html, $, storeName, errorMsg;

    return _regeneratorRuntime().wrap(function _callee8$(_context8) {
      while (1) {
        switch (_context8.prev = _context8.next) {
          case 0:
            _context8.prev = 0;
            _context8.next = 3;
            return axios__WEBPACK_IMPORTED_MODULE_2___default()({
              url: "".concat(host, "/resumen"),
              method: 'get'
            });

          case 3:
            _yield$axios4 = _context8.sent;
            html = _yield$axios4.data;

            if (!html) {
              _context8.next = 10;
              break;
            }

            $ = cheerio__WEBPACK_IMPORTED_MODULE_3___default.a.load(html);
            storeName = $('.nav-header-usermenu-wrapper .nav-header-username').text().trim() || '';
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9\u5E97\u94FA\u540D\u79F0\u4FE1\u606F\u6210\u529F\uFF0C\u5E97\u94FA\u540D\u79F0\uFF1A".concat(storeName));
            return _context8.abrupt("return", storeName);

          case 10:
            _context8.next = 16;
            break;

          case 12:
            _context8.prev = 12;
            _context8.t0 = _context8["catch"](0);
            errorMsg = Object(_utils_util__WEBPACK_IMPORTED_MODULE_1__[/* isError */ "u"])(_context8.t0);
            _data_log__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setLog("\u83B7\u53D6mercado\u672C\u571F\u7AD9\u70B9\u5E97\u94FA\u540D\u79F0\u8BF7\u6C42\u62A5\u9519-----".concat(errorMsg));

          case 16:
          case "end":
            return _context8.stop();
        }
      }
    }, _callee8, null, [[0, 12]]);
  }));

  return function getLocalStoreNameInfo(_x3) {
    return _ref11.apply(this, arguments);
  };
}();

/***/ }),

/***/ "ff24":
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Task_vue_vue_type_style_index_0_id_f3b451f4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("2317");
/* harmony import */ var _node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Task_vue_vue_type_style_index_0_id_f3b451f4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_mini_css_extract_plugin_dist_loader_js_ref_8_oneOf_1_0_node_modules_css_loader_index_js_ref_8_oneOf_1_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_8_oneOf_1_2_node_modules_sass_loader_dist_cjs_js_ref_8_oneOf_1_3_node_modules_cache_loader_dist_cjs_js_ref_0_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Task_vue_vue_type_style_index_0_id_f3b451f4_lang_scss_scoped_true___WEBPACK_IMPORTED_MODULE_0__);
/* unused harmony reexport * */


/***/ })

}]);