"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = exports.getSelectedProperties = exports.getSelectedPropValues = exports.filterDisabledSkuTree = exports.isSkuChoosable = exports.getSelectedSkuValues = exports.getSkuComb = exports.isAllSelected = exports.normalizePropList = exports.normalizeSkuTree = void 0;

var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _constants = require("../constants");

/*
  normalize sku tree

  [
    {
      count: 2,
      k: "品种", // 规格名称 skuKeyName
      k_id: "1200", // skuKeyId
      k_s: "s1" // skuKeyStr
      v: [ // skuValues
        { // skuValue
          id: "1201", // skuValueId
          name: "萌" // 具体的规格值 skuValueName
        }, {
          id: "973",
          name: "帅"
        }
      ]
    },
    ...
  ]
                |
                v
  {
    s1: [{
      id: "1201",
      name: "萌"
    }, {
      id: "973",
      name: "帅"
    }],
    ...
  }
 */
var normalizeSkuTree = function normalizeSkuTree(skuTree) {
  var normalizedTree = {};
  skuTree.forEach(function (treeItem) {
    normalizedTree[treeItem.k_s] = treeItem.v;
  });
  return normalizedTree;
};

exports.normalizeSkuTree = normalizeSkuTree;

var normalizePropList = function normalizePropList(propList) {
  var normalizedProp = {};
  propList.forEach(function (item) {
    var itemObj = {};
    item.v.forEach(function (it) {
      itemObj[it.id] = it;
    });
    normalizedProp[item.k_id] = itemObj;
  });
  return normalizedProp;
}; // 判断是否所有的sku都已经选中


exports.normalizePropList = normalizePropList;

var isAllSelected = function isAllSelected(skuTree, selectedSku) {
  // 筛选selectedSku对象中key值不为空的值
  var selected = Object.keys(selectedSku).filter(function (skuKeyStr) {
    return selectedSku[skuKeyStr] !== _constants.UNSELECTED_SKU_VALUE_ID;
  });
  return skuTree.length === selected.length;
}; // 根据已选择的 sku 获取 skuComb


exports.isAllSelected = isAllSelected;

var getSkuComb = function getSkuComb(skuList, selectedSku) {
  var skuComb = skuList.filter(function (item) {
    return Object.keys(selectedSku).every(function (skuKeyStr) {
      return String(item[skuKeyStr]) === String(selectedSku[skuKeyStr]);
    });
  });
  return skuComb[0];
}; // 获取已选择的sku名称


exports.getSkuComb = getSkuComb;

var getSelectedSkuValues = function getSelectedSkuValues(skuTree, selectedSku) {
  var normalizedTree = normalizeSkuTree(skuTree);
  return Object.keys(selectedSku).reduce(function (selectedValues, skuKeyStr) {
    var skuValues = normalizedTree[skuKeyStr] || [];
    var skuValueId = selectedSku[skuKeyStr];

    if (skuValueId !== _constants.UNSELECTED_SKU_VALUE_ID && skuValues.length > 0) {
      var skuValue = skuValues.filter(function (value) {
        return value.id === skuValueId;
      })[0];
      skuValue && selectedValues.push(skuValue);
    }

    return selectedValues;
  }, []);
}; // 判断sku是否可选


exports.getSelectedSkuValues = getSelectedSkuValues;

var isSkuChoosable = function isSkuChoosable(skuList, selectedSku, skuToChoose) {
  var _extends2;

  var key = skuToChoose.key,
      valueId = skuToChoose.valueId; // 先假设sku已选中，拼入已选中sku对象中

  var matchedSku = (0, _extends3.default)({}, selectedSku, (_extends2 = {}, _extends2[key] = valueId, _extends2)); // 再判断剩余sku是否全部不可选，若不可选则当前sku不可选中

  var skusToCheck = Object.keys(matchedSku).filter(function (skuKey) {
    return matchedSku[skuKey] !== _constants.UNSELECTED_SKU_VALUE_ID;
  });
  var filteredSku = skuList.filter(function (sku) {
    return skusToCheck.every(function (skuKey) {
      return String(matchedSku[skuKey]) === String(sku[skuKey]);
    });
  }); // 检查是否有非禁用的SKU可选

  var availableSku = filteredSku.filter(function (sku) {
    return sku.disable_status !== 1;
  });
  var stock = availableSku.reduce(function (total, sku) {
    total += sku.stock_num;
    return total;
  }, 0);
  return stock > 0;
}; // 根据disable_status字段过滤skuTree


exports.isSkuChoosable = isSkuChoosable;

var filterDisabledSkuTree = function filterDisabledSkuTree(skuTree, skuList, selectedSku) {
  if (selectedSku === void 0) {
    selectedSku = {};
  }

  if (!(skuList == null ? void 0 : skuList.length)) {
    return skuTree;
  } // 创建规格树的深拷贝，避免修改原始数据


  var treeClone = JSON.parse(JSON.stringify(skuTree)); // 对每个规格值，收集所有包含它的SKU

  var specValueToSkus = {}; // 初始化规格值到SKU的映射

  treeClone.forEach(function (treeItem) {
    var key = treeItem.k_s;
    treeItem.v.forEach(function (value) {
      var valueId = value.id;
      specValueToSkus[key + "-" + valueId] = [];
    });
  }); // 收集每个规格值对应的所有SKU

  skuList.forEach(function (item) {
    for (var i = 1; i <= 5; i++) {
      var key = "s" + i;
      var value = item[key];

      if (value && value !== '0') {
        var mapKey = key + "-" + value;

        if (specValueToSkus[mapKey]) {
          specValueToSkus[mapKey].push(item);
        }
      }
    }
  }); // 过滤规格树

  return treeClone.filter(function (treeItem) {
    var key = treeItem.k_s;
    var isSelectedSpec = selectedSku[key] && selectedSku[key] !== _constants.UNSELECTED_SKU_VALUE_ID; // 过滤规格值

    treeItem.v = treeItem.v.filter(function (value) {
      var valueId = value.id;
      var mapKey = key + "-" + valueId;
      var relatedSkus = specValueToSkus[mapKey] || []; // 1. 如果所有包含该规格值的SKU都被明确禁用，则过滤掉该规格值

      if (relatedSkus.length > 0) {
        var allExplicitlyDisabled = relatedSkus.every(function (sku) {
          return sku.disable_status === 1;
        });

        if (allExplicitlyDisabled) {
          return false;
        }
      } // 2. 如果是已选中的值，保留它


      if (isSelectedSpec && String(valueId) === String(selectedSku[key])) {
        return true;
      } // 3. 如果用户已经选择了其他规格，检查组合


      var validSelectedEntries = Object.entries(selectedSku).filter(function (_ref) {
        var selectedKey = _ref[0],
            val = _ref[1];
        return val !== _constants.UNSELECTED_SKU_VALUE_ID && selectedKey !== key;
      } // 排除当前规格
      );

      if (validSelectedEntries.length > 0) {
        // 创建当前组合
        var combinedSelection = {}; // 添加已选规格

        validSelectedEntries.forEach(function (_ref2) {
          var selectedKey = _ref2[0],
              val = _ref2[1];
          combinedSelection[selectedKey] = val;
        }); // 添加当前正在检查的规格值

        combinedSelection[key] = String(valueId); // 查找满足当前组合的SKU

        var matchingSku = skuList.filter(function (sku) {
          return Object.entries(combinedSelection).every(function (_ref3) {
            var selectedKey = _ref3[0],
                selectedVal = _ref3[1];
            return String(sku[selectedKey]) === String(selectedVal);
          });
        }); // 如果有匹配的SKU，检查它们是否全部被禁用

        if (matchingSku.length > 0) {
          var allDisabled = matchingSku.every(function (sku) {
            return sku.disable_status === 1;
          });
          return !allDisabled;
        }
      } // 默认保留所有规格值


      return true;
    }); // 如果是已选中的规格项，但过滤后没有包含已选值，则隐藏

    if (isSelectedSpec) {
      var selectedValueExists = treeItem.v.some(function (value) {
        return String(value.id) === String(selectedSku[key]);
      });
      return selectedValueExists;
    } // 如果该规格项下没有规格值了，则隐藏整个规格项


    return treeItem.v.length > 0;
  });
};

exports.filterDisabledSkuTree = filterDisabledSkuTree;

var getSelectedPropValues = function getSelectedPropValues(propList, selectedProp) {
  var normalizeProp = normalizePropList(propList);
  return Object.keys(selectedProp).reduce(function (acc, cur) {
    selectedProp[cur].forEach(function (it) {
      acc.push((0, _extends3.default)({}, normalizeProp[cur][it]));
    });
    return acc;
  }, []);
};

exports.getSelectedPropValues = getSelectedPropValues;

var getSelectedProperties = function getSelectedProperties(propList, selectedProp) {
  var list = [];
  (propList || []).forEach(function (prop) {
    if (selectedProp[prop.k_id] && selectedProp[prop.k_id].length > 0) {
      var v = [];
      prop.v.forEach(function (it) {
        if (selectedProp[prop.k_id].indexOf(it.id) > -1) {
          v.push((0, _extends3.default)({}, it));
        }
      });
      list.push((0, _extends3.default)({}, prop, {
        v: v
      }));
    }
  });
  return list;
};

exports.getSelectedProperties = getSelectedProperties;
var _default = {
  normalizeSkuTree: normalizeSkuTree,
  getSkuComb: getSkuComb,
  getSelectedSkuValues: getSelectedSkuValues,
  isAllSelected: isAllSelected,
  isSkuChoosable: isSkuChoosable,
  getSelectedPropValues: getSelectedPropValues,
  getSelectedProperties: getSelectedProperties,
  filterDisabledSkuTree: filterDisabledSkuTree
};
exports.default = _default;