'use strict';

var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var index = require('./index-7d6992d6.js');
var DivaUtils = require('@crystaldesign/diva-utils');
require('@babel/runtime/helpers/slicedToArray');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/regenerator');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@babel/runtime/helpers/toConsumableArray');
require('axios');
require('@crystaldesign/basket-model');
require('@crystaldesign/basket-handler');
require('socket.io-client');
require('@babel/runtime/helpers/typeof');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var DivaUtils__default = /*#__PURE__*/_interopDefaultLegacy(DivaUtils);

//Der in einem Set gemergte Optionsbaum
var MAIN_COLOR_OPTIONCODEX = 'OPTBE_BOX'; // this field indicates the the main Color. This main color is used in the PDF
var StandardWWSHandler = /*#__PURE__*/function () {
  function StandardWWSHandler() {
    _classCallCheck__default["default"](this, StandardWWSHandler);
    _defineProperty__default["default"](this, "mainColorFound", false);
  }
  return _createClass__default["default"](StandardWWSHandler, [{
    key: "repairWWSFlags",
    value: function repairWWSFlags(articles, orderLines) {
      return orderLines;
    }
  }, {
    key: "getWWSData",
    value: function getWWSData(basket, set, orderSet, orderlines) {
      var _this = this;
      this.mainColorFound = false;
      var pos = set.CatalogData.summaryTabGroupPosition;
      var isIDM = set.CatalogData.isIDMFormat;
      var partListOrderLines = [];
      var partListGroups = [];
      var firstItem = undefined;
      for (var i = 0; i < orderlines.length; i++) {
        var orderLineItem = orderlines[i];
        if (orderLineItem.DontAddToFinalOrderLine) {
          orderlines.splice(i, 1);
          i--;
        }
      }
      var articles = set.getDivaArticles();
      var groupedPartlistArticles = [];
      var usedOptionCodexes = [];
      var posNr = 1;
      for (var iKey in articles) {
        var article = articles[iKey];
        var partlistArticles = articles[iKey].partlistArticles;
        var partlistArticlesWithTabGroup = [];
        groupedPartlistArticles.push({
          article: article,
          posNr: posNr,
          partlistArticles: [],
          letOthesMatch: true
        });
        var _loop = function _loop() {
          var _partlistArticle$cata, _article$getArticleOp, _article$getArticleOp2;
          var partlistArticle = partlistArticles[key];
          var preDefinedPosNr = (_partlistArticle$cata = partlistArticle.catalogArticle.orderPosNr) !== null && _partlistArticle$cata !== void 0 ? _partlistArticle$cata : null;
          var tabGroup = (_article$getArticleOp = (_article$getArticleOp2 = article.getArticleOptionState((!isIDM ? 'OPT' : '') + partlistArticle.tabGroup)) === null || _article$getArticleOp2 === void 0 ? void 0 : _article$getArticleOp2.optionTabGroup) !== null && _article$getArticleOp !== void 0 ? _article$getArticleOp : partlistArticle.tabGroup;
          if (preDefinedPosNr !== null) {
            var existingentry = !preDefinedPosNr.endsWith(';') && groupedPartlistArticles.find(function (group) {
              return (group.posNr == Number(preDefinedPosNr) || group.groupKey == preDefinedPosNr) && group.letOthesMatch;
            });
            if (existingentry) {
              existingentry.partlistArticles.push({
                article: partlistArticle,
                tabGroup: tabGroup
              });
            } else {
              var letOthesMatch = true;
              var newPosNr = Number(preDefinedPosNr);
              if (isNaN(newPosNr)) {
                newPosNr = posNr;
                letOthesMatch = false;
                do {
                  newPosNr++;
                } while (groupedPartlistArticles.find(function (group) {
                  return group.posNr == newPosNr;
                }));
              }
              groupedPartlistArticles.push({
                article: article,
                posNr: newPosNr,
                letOthesMatch: letOthesMatch,
                partlistArticles: [{
                  article: partlistArticle,
                  tabGroup: tabGroup
                }],
                groupKey: preDefinedPosNr
              });
            }
          } else {
            partlistArticlesWithTabGroup.push({
              article: partlistArticle,
              tabGroup: tabGroup
            });
          }
        };
        for (var key in partlistArticles) {
          _loop();
        }
        groupedPartlistArticles.find(function (group) {
          return group.posNr === posNr;
        }).partlistArticles = partlistArticlesWithTabGroup;
        do {
          posNr++;
        } while (groupedPartlistArticles.find(function (group) {
          return group.posNr == posNr;
        }));
      }
      if (pos) this.sort(pos, groupedPartlistArticles);
      var _loop2 = function _loop2() {
        var group = groupedPartlistArticles[_i];
        var article = group.article;
        var posNrCount = 1;

        //get count of tabgroupOption - articles within each tabgroup
        var _loop4 = function _loop4() {
          var _article$getArticleOp3, _article$getArticleOp4;
          var partListArticle = group.partlistArticles[j].article;
          var tabGroup = (_article$getArticleOp3 = (_article$getArticleOp4 = article.getArticleOptionState((!isIDM ? 'OPT' : '') + partListArticle.tabGroup)) === null || _article$getArticleOp4 === void 0 ? void 0 : _article$getArticleOp4.optionTabGroup) !== null && _article$getArticleOp3 !== void 0 ? _article$getArticleOp3 : partListArticle.tabGroup;
          var fountEntry = partListOrderLines.find(function (item) {
            var _item$FormattedOption, _item$FormattedOption2, _this$getFormattedOpt;
            return item.Name == partListArticle.name && item.ArticleNr == partListArticle.configArticleCodex && ((_item$FormattedOption = item.FormattedOptions) === null || _item$FormattedOption === void 0 ? void 0 : _item$FormattedOption[0]) && ((_item$FormattedOption2 = item.FormattedOptions) === null || _item$FormattedOption2 === void 0 ? void 0 : _item$FormattedOption2[0].Title) == ((_this$getFormattedOpt = _this.getFormattedOptions(partListArticle, article, [], '', usedOptionCodexes)) === null || _this$getFormattedOpt === void 0 ? void 0 : _this$getFormattedOpt[0].Title);
          });
          if (fountEntry) {
            fountEntry.Quantity = fountEntry.Quantity + partListArticle.quantity;
            fountEntry.FormattedPrice = DivaUtils__default["default"].formatPrice(partListArticle.price * fountEntry.Quantity);
          } else {
            var colorCodices = [];
            if (tabGroup && tabGroup !== 'Aktion' /* Aktion delete in 2024 */ && tabGroup !== 'BOX_AF_PARIS' || firstItem) {
              var _partListArticle$conf, _partListArticle$conf2;
              var _this$getFinalPosNr = _this.getFinalPosNr(group, posNrCount, partListArticle, firstItem),
                finalPosNr = _this$getFinalPosNr.finalPosNr,
                newPosNrCount = _this$getFinalPosNr.newPosNrCount;
              posNrCount = newPosNrCount;
              var formattedOptions = _this.getFormattedOptions(partListArticle, article, colorCodices, finalPosNr, usedOptionCodexes);
              partListOrderLines.push({
                ArticleNr: (_partListArticle$conf = partListArticle.configArticleCodex) !== null && _partListArticle$conf !== void 0 && _partListArticle$conf.startsWith('HIDE_CODEX') ? '' : (_partListArticle$conf2 = partListArticle.configArticleCodex) !== null && _partListArticle$conf2 !== void 0 ? _partListArticle$conf2 : partListArticle.articleCodex,
                ColorCodices: colorCodices,
                FormattedOptions: formattedOptions,
                FormattedPrice: DivaUtils__default["default"].formatPrice(partListArticle.price * partListArticle.quantity),
                PosNr: finalPosNr,
                Price: typeof partListArticle.price === 'number' ? partListArticle.price : parseFloat(partListArticle.price),
                Quantity: partListArticle.quantity,
                TabGroup: tabGroup !== null && tabGroup !== void 0 ? tabGroup : ' ',
                Name: partListArticle.name,
                Size: partListArticle.actSizeText
              });
            } else {
              var _partListArticle$conf3, _basket$SetName;
              firstItem = {
                formattedOptions: [],
                ArticleNr: (_partListArticle$conf3 = partListArticle.configArticleCodex) !== null && _partListArticle$conf3 !== void 0 ? _partListArticle$conf3 : partListArticle.articleCodex,
                ColorCodices: [],
                FormattedPrice: DivaUtils__default["default"].formatPrice(partListArticle.price * partListArticle.quantity),
                PosNr: group.posNr + '.00',
                Price: partListArticle.price,
                Quantity: partListArticle.quantity,
                TabGroup: 'SetArtikel',
                Name: (_basket$SetName = basket.SetName) !== null && _basket$SetName !== void 0 ? _basket$SetName : partListArticle.name
              };
            }
          }
        };
        for (var j = 0; j < group.partlistArticles.length; j++) {
          _loop4();
        }
      };
      for (var _i = 0; _i < groupedPartlistArticles.length; _i++) {
        _loop2();
      }
      for (var _i2 = 0; _i2 < partListOrderLines.length; _i2++) {
        if (partListOrderLines[_i2].TabGroup && !partListGroups.includes(partListOrderLines[_i2].TabGroup)) {
          partListGroups.push(partListOrderLines[_i2].TabGroup);
        }
      }
      if (pos) {
        var partListOrderLinesSorted = [];
        var _loop3 = function _loop3() {
          var _DivaSummaryHandler$g;
          var p = (_DivaSummaryHandler$g = index.summaryHandlerInstance.getTabgroupByOptionCodex(pos[_i3], Object.values(articles))) !== null && _DivaSummaryHandler$g !== void 0 ? _DivaSummaryHandler$g : pos[_i3];
          while (partListOrderLines.find(function (orderline) {
            return orderline.TabGroup === p;
          })) {
            var index$1 = partListOrderLines.findIndex(function (orderline) {
              return orderline.TabGroup === p;
            });
            if (index$1 >= 0) {
              partListOrderLinesSorted.push(partListOrderLines[index$1]);
              partListOrderLines.splice(index$1, 1);
            }
          }
        };
        for (var _i3 = 0; _i3 < pos.length; _i3++) {
          _loop3();
        }
        for (var _i4 = 0; _i4 < partListOrderLines.length; _i4++) {
          partListOrderLinesSorted.push(partListOrderLines[_i4]);
        }
        partListOrderLines = partListOrderLinesSorted;
      }
      partListOrderLines.sort(function (a, b) {
        var posA = parseFloat(a.PosNr);
        var posB = parseFloat(b.PosNr);
        return posA - posB;
      });
      if (firstItem) partListOrderLines.unshift(firstItem);
      return {
        PartListOrderLines: partListOrderLines,
        PartListGroups: partListGroups
      };
    }
  }, {
    key: "getFinalPosNr",
    value: function getFinalPosNr(group, posNrCount, partListArticle, firstItem) {
      var finalPosNr = '';
      if (firstItem && group.posNr == 1 && !partListArticle.tabGroup) {
        //betriebsanleitung soll diese PosNr haben
        finalPosNr = '1.99';
      } else if (group.partlistArticles.length > 1) {
        finalPosNr = (group.posNr + Number((posNrCount / 100).toFixed(2))).toString();
        posNrCount++;
      } else {
        finalPosNr = (group.posNr + '.00').toString();
      }
      return {
        finalPosNr: finalPosNr,
        newPosNrCount: posNrCount
      };
    }
  }, {
    key: "sort",
    value: function sort(pos, groupedPartlistArticles) {
      //sort to specific catalog pos

      for (var i = 0; i < groupedPartlistArticles.length; i++) {
        var partlistArticlesSorted = [];
        var article = groupedPartlistArticles[i];
        for (var j = 0; j < pos.length; j++) {
          var _DivaSummaryHandler$g2;
          var indexesOf = [];
          var p = (_DivaSummaryHandler$g2 = index.summaryHandlerInstance.getTabgroupByOptionCodex(pos[j], [article.article])) !== null && _DivaSummaryHandler$g2 !== void 0 ? _DivaSummaryHandler$g2 : pos[j];
          for (var m = 0; m < article.partlistArticles.length; m++) {
            var _article$article$getA, _article$article$getA2;
            var partListArticle = article.partlistArticles[m];
            var tabGroup = (_article$article$getA = (_article$article$getA2 = article.article.getArticleOptionState((!partListArticle.article.CatalogData.isIDMFormat ? 'OPT' : '') + partListArticle.tabGroup)) === null || _article$article$getA2 === void 0 ? void 0 : _article$article$getA2.optionTabGroup) !== null && _article$article$getA !== void 0 ? _article$article$getA : partListArticle.tabGroup;
            if (tabGroup == p) {
              indexesOf.push(m);
            }
          }
          for (var _m = 0; _m < indexesOf.length; _m++) {
            partlistArticlesSorted.push(article.partlistArticles[indexesOf[_m] - _m]);
            article.partlistArticles.splice(indexesOf[_m] - _m, 1);
          }
        }
        for (var h = 0; h < article.partlistArticles.length; h++) {
          partlistArticlesSorted.push(article.partlistArticles[h]);
        }
        article.partlistArticles = partlistArticlesSorted;
      }
    }
  }, {
    key: "getFormattedOptions",
    value: function getFormattedOptions(partListArticle, article, colorCodices, finalPosNr, usedOptionCodexes) {
      var formattedOptions = [];
      if (partListArticle.tabGroup && partListArticle.tabGroupOption) {
        var optionStates = index.summaryHandlerInstance.getOptionCodexesOfTabGroupForSummary(article, partListArticle, usedOptionCodexes, finalPosNr == '');
        for (var i = 0; i < optionStates.length; i++) {
          var optionState = optionStates[i];
          if (optionState.optionCodex.startsWith('OPTBE_') || optionState.optionCodex.startsWith('OPTAB_') || optionState.option.addToWWS) {
            var _optionState$vCodex;
            var coloCodex = (_optionState$vCodex = optionState.vCodex) !== null && _optionState$vCodex !== void 0 ? _optionState$vCodex : optionState.valCodex;
            if (coloCodex) {
              var _optionState$val;
              colorCodices.push(coloCodex);
              var isMainColor = false;
              if (!this.mainColorFound && optionState.optionCodex == MAIN_COLOR_OPTIONCODEX) {
                isMainColor = true;
                this.mainColorFound = true;
              }
              formattedOptions.push({
                PosNr: finalPosNr,
                Text: ((_optionState$val = optionState.val) !== null && _optionState$val !== void 0 && _optionState$val.groupName ? optionState.val.groupName + ' ' : '') + optionState.valName,
                Title: optionState.optionOrigName,
                Codex: optionState.vCodex && optionState.vCodex !== optionState.valName ? optionState.vCodex : '',
                IsMainColor: isMainColor
              });
            }
          }
        }
      }
      return formattedOptions;
    }
  }, {
    key: "getCustomIdsForProductsMatch",
    value: function getCustomIdsForProductsMatch(set) {}
  }]);
}();

exports["default"] = StandardWWSHandler;
