import { formatAmount } from '@pisell/utils';
export var checkSkuStockCanSell = function checkSkuStockCanSell(sku) {
  var canSell = true; // 是否可以售卖
  var hasStock = true; // 是否还有库存
  // 如果追踪库存
  if ((sku === null || sku === void 0 ? void 0 : sku.is_track) === 1) {
    // 如果允许超卖，则不检查库存
    // 追踪库存 & 不允许超卖，则检查库存
    if (Number((sku === null || sku === void 0 ? void 0 : sku.stock_quantity) || 0) <= 0) {
      canSell = false;
      hasStock = false;
    }
  } else {
    // 不跟踪库存，则可以售卖
    canSell = true;
    hasStock = true;
  }
  return {
    canSell: canSell,
    hasStock: hasStock
  };
};
export var checkProductStock = function checkProductStock(params) {
  var _value$bundle;
  var value = params === null || params === void 0 ? void 0 : params.value;
  var data = params === null || params === void 0 ? void 0 : params.data;
  if (!data) return true;

  // 检测 variant 库存
  if (value !== null && value !== void 0 && value.product_variant_id) {
    var _variant;
    var variantItem = data === null || data === void 0 || (_variant = data.variant) === null || _variant === void 0 ? void 0 : _variant.find(function (item) {
      return Number(item === null || item === void 0 ? void 0 : item.id) === Number(value.product_variant_id);
    });
    var variantCanSell = checkSkuStockCanSell(variantItem);
    if (!variantCanSell.hasStock) {
      return false;
    }
  }

  // 检测 bundle 库存
  if ((value === null || value === void 0 || (_value$bundle = value.bundle) === null || _value$bundle === void 0 ? void 0 : _value$bundle.length) > 0) {
    var bundleCanSell = value === null || value === void 0 ? void 0 : value.bundle.every(function (item) {
      var bundleStock = checkSkuStockCanSell(item);
      return bundleStock.hasStock;
    });
    if (!bundleCanSell) {
      return false;
    }
  }

  // 如果有 variant，则不检测商品本身的库存了
  if (value !== null && value !== void 0 && value.product_variant_id) {
    return true;
  }

  // 检测商品本身库存
  var productCanSell = checkSkuStockCanSell(data);
  if (!productCanSell.hasStock) {
    return false;
  }
  return true;
};

/**
 * @description 将已选 SKU 信息格式化为结构化列表，便于逐项渲染样式
 */
export var formatSelectedSkuItems = function formatSelectedSkuItems(skuValue) {
  var currencySymbol = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var translationOriginal = arguments.length > 2 ? arguments[2] : undefined;
  if (!skuValue) return [];
  var items = [];
  var optionList = Array.isArray(skuValue === null || skuValue === void 0 ? void 0 : skuValue.option) ? skuValue.option : Array.isArray(skuValue === null || skuValue === void 0 ? void 0 : skuValue.options) ? skuValue.options : [];
  var getDisplayText = function getDisplayText(value) {
    return typeof value === 'string' ? value : (translationOriginal === null || translationOriginal === void 0 ? void 0 : translationOriginal(value)) || '';
  };
  if (skuValue !== null && skuValue !== void 0 && skuValue.product_option_string) {
    var productOptionText = skuValue.product_option_string;
    items.push({
      key: "variant-".concat(productOptionText),
      type: 'variant',
      label: productOptionText
    });
  }
  optionList.forEach(function (item, index) {
    var _item$id;
    var label = getDisplayText(item.name) || '';
    var quantity = Number((item === null || item === void 0 ? void 0 : item.num) || 1);
    var hasPrice = (item === null || item === void 0 ? void 0 : item.price) !== undefined && (item === null || item === void 0 ? void 0 : item.price) !== null && (item === null || item === void 0 ? void 0 : item.price) !== '';
    items.push({
      key: "option-".concat((_item$id = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id !== void 0 ? _item$id : index, "-").concat(label),
      type: 'option',
      label: label,
      meta: "".concat(hasPrice ? "".concat(formatAmount(item === null || item === void 0 ? void 0 : item.price, 2, currencySymbol), " ") : '', "x ").concat(quantity)
    });
  });
  if (Array.isArray(skuValue === null || skuValue === void 0 ? void 0 : skuValue.bundle) && skuValue.bundle.length > 0) {
    skuValue.bundle.forEach(function (item, index) {
      var _item$id2;
      var label = getDisplayText(item.title) || '';
      var quantity = Number((item === null || item === void 0 ? void 0 : item.num) || 1);
      var hasPrice = (item === null || item === void 0 ? void 0 : item.price) !== undefined && (item === null || item === void 0 ? void 0 : item.price) !== null && (item === null || item === void 0 ? void 0 : item.price) !== '';
      items.push({
        key: "bundle-".concat((_item$id2 = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id2 !== void 0 ? _item$id2 : index, "-").concat(label),
        type: 'bundle',
        label: label,
        meta: "".concat(hasPrice ? "".concat(formatAmount(item === null || item === void 0 ? void 0 : item.price, 2, currencySymbol), " ") : '', "x ").concat(quantity),
        children: []
      });
      var bundleDisplayItem = items[items.length - 1];
      var bundleOptions = Array.isArray(item === null || item === void 0 ? void 0 : item.options) ? item.options : Array.isArray(item === null || item === void 0 ? void 0 : item.option) ? item.option : [];
      bundleOptions.forEach(function (opt, optionIndex) {
        var _bundleDisplayItem$ch, _item$id3, _opt$id;
        var optionLabel = getDisplayText(opt.name) || '';
        var optionQuantity = Number((opt === null || opt === void 0 ? void 0 : opt.num) || 1);
        var optionHasPrice = (opt === null || opt === void 0 ? void 0 : opt.price) !== undefined && (opt === null || opt === void 0 ? void 0 : opt.price) !== null && (opt === null || opt === void 0 ? void 0 : opt.price) !== '';
        (_bundleDisplayItem$ch = bundleDisplayItem.children) === null || _bundleDisplayItem$ch === void 0 || _bundleDisplayItem$ch.push({
          key: "bundle-option-".concat((_item$id3 = item === null || item === void 0 ? void 0 : item.id) !== null && _item$id3 !== void 0 ? _item$id3 : index, "-").concat((_opt$id = opt === null || opt === void 0 ? void 0 : opt.id) !== null && _opt$id !== void 0 ? _opt$id : optionIndex, "-").concat(optionLabel),
          type: 'bundleOption',
          label: optionLabel,
          meta: "".concat(optionHasPrice ? "".concat(formatAmount(opt === null || opt === void 0 ? void 0 : opt.price, 2, currencySymbol), " ") : '', "x ").concat(optionQuantity)
        });
      });
    });
  }
  return items;
};
export var getStockValidationResult = function getStockValidationResult(params) {
  var _params$bookingConfig, _params$bookingConfig2, _params$bookingConfig3, _params$bookingConfig4, _params$bookingConfig5, _params$bookingConfig6, _params$data, _params$data2;
  var stockValidation = Number((_params$bookingConfig = params === null || params === void 0 || (_params$bookingConfig2 = params.bookingConfig) === null || _params$bookingConfig2 === void 0 || (_params$bookingConfig2 = _params$bookingConfig2.stock_setting) === null || _params$bookingConfig2 === void 0 ? void 0 : _params$bookingConfig2.stock_validation) !== null && _params$bookingConfig !== void 0 ? _params$bookingConfig : 0);
  var allowAddToCartWhenOutStock = Number((_params$bookingConfig3 = params === null || params === void 0 || (_params$bookingConfig4 = params.bookingConfig) === null || _params$bookingConfig4 === void 0 || (_params$bookingConfig4 = _params$bookingConfig4.stock_setting) === null || _params$bookingConfig4 === void 0 ? void 0 : _params$bookingConfig4.allow_add_to_cart_when_out_stock) !== null && _params$bookingConfig3 !== void 0 ? _params$bookingConfig3 : 0);
  var enableDontShowAgainToday = Number((_params$bookingConfig5 = params === null || params === void 0 || (_params$bookingConfig6 = params.bookingConfig) === null || _params$bookingConfig6 === void 0 || (_params$bookingConfig6 = _params$bookingConfig6.stock_setting) === null || _params$bookingConfig6 === void 0 ? void 0 : _params$bookingConfig6.do_not_show_again_today) !== null && _params$bookingConfig5 !== void 0 ? _params$bookingConfig5 : 0);
  var productId = Number((params === null || params === void 0 || (_params$data = params.data) === null || _params$data === void 0 ? void 0 : _params$data.product_id) || (params === null || params === void 0 || (_params$data2 = params.data) === null || _params$data2 === void 0 ? void 0 : _params$data2.id) || 0);
  if (stockValidation !== 1) {
    return {
      stockValidation: stockValidation,
      allowAddToCartWhenOutStock: allowAddToCartWhenOutStock,
      enableDontShowAgainToday: enableDontShowAgainToday,
      productId: productId,
      hasStock: true,
      shouldBlock: false,
      shouldShowAlert: false
    };
  }
  var hasStock = checkProductStock({
    value: params === null || params === void 0 ? void 0 : params.value,
    data: params === null || params === void 0 ? void 0 : params.data
  });
  if (hasStock) {
    return {
      stockValidation: stockValidation,
      allowAddToCartWhenOutStock: allowAddToCartWhenOutStock,
      enableDontShowAgainToday: enableDontShowAgainToday,
      productId: productId,
      hasStock: hasStock,
      shouldBlock: false,
      shouldShowAlert: false
    };
  }
  var shouldSkipAlert = allowAddToCartWhenOutStock === 1 && enableDontShowAgainToday === 1 && hasHiddenStockAlertForToday({
    productId: productId
  });
  return {
    stockValidation: stockValidation,
    allowAddToCartWhenOutStock: allowAddToCartWhenOutStock,
    enableDontShowAgainToday: enableDontShowAgainToday,
    productId: productId,
    hasStock: hasStock,
    shouldBlock: allowAddToCartWhenOutStock !== 1,
    shouldShowAlert: allowAddToCartWhenOutStock === 1 && !shouldSkipAlert
  };
};
export function getLocalDayKey() {
  var now = new Date();
  var yyyy = String(now.getFullYear());
  var mm = String(now.getMonth() + 1).padStart(2, '0');
  var dd = String(now.getDate()).padStart(2, '0');
  return "".concat(yyyy, "-").concat(mm, "-").concat(dd);
}
export function getStockAlertStorageKey(params) {
  return "pisell2_stock_alert_hidden_".concat(params.productId);
}
export function hasHiddenStockAlertForToday(params) {
  try {
    if (!params.productId) return false;
    if (typeof window === 'undefined') return false;
    var key = getStockAlertStorageKey(params);
    var value = window.localStorage.getItem(key);
    return value === getLocalDayKey();
  } catch (error) {
    return false;
  }
}
export function setHiddenStockAlertForToday(params) {
  try {
    if (!params.productId) return;
    if (typeof window === 'undefined') return;
    var key = getStockAlertStorageKey(params);
    window.localStorage.setItem(key, getLocalDayKey());
  } catch (error) {}
}