function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useMemo } from 'react';
import classNames from 'classnames';
import { Button, PisellToast } from '@pisell/materials';
import { image as imageAli, locales } from '@pisell/utils';
import NumericStepper from "../../pro/NumericStepper";
import PisellPriceText from "../productSelect/components/pisellPriceText";
import "./index.less";
import localeTexts from "./locales";
import useEngineContext from "../../hooks/useEngineContext";
import { cubicBezier } from "./utils";
var PREFIX = 'pisell-plus-sales-product-card';

/**
 * 解析多语言/普通字符串标题
 */
function resolveText(text) {
  if (!text) return '';
  if (typeof text === 'string') return text;
  var values = Object.values(text || {});
  return values.find(function (item) {
    return !!item;
  }) || '';
}
function toStringValue(value) {
  if (value === undefined || value === null) return '';
  return String(value);
}
function toNumber(value) {
  var parsed = Number(value);
  if (Number.isNaN(parsed)) return 0;
  return parsed;
}
function getTextCover(text) {
  var cleanText = text.trim();
  if (!cleanText) return '';
  return cleanText.substring(0, 2).toUpperCase();
}

/**
 * 普通商品: 可直接增减数量
 * 其它商品(单规格/组合规格/套餐): 需要进入 options 进一步选择
 */
export function isNormalProduct(product) {
  if (!product) return true;
  var _ref = product,
    is_variant = _ref.is_variant,
    is_bundle = _ref.is_bundle;
  var hasOption = Array.isArray(product.option_group) && product.option_group.length > 0;
  return !(hasOption || is_bundle || is_variant);
}
var PisellSalesProductCard = function PisellSalesProductCard(_ref2) {
  var _context$appHelper$ut, _product$price, _value$num, _stepperProps$min3, _stepperProps$step;
  var product = _ref2.product,
    value = _ref2.value,
    _ref2$disabled = _ref2.disabled,
    disabled = _ref2$disabled === void 0 ? false : _ref2$disabled,
    stepperProps = _ref2.stepperProps,
    optionsText = _ref2.optionsText,
    skuCardConfig = _ref2.skuCardConfig,
    cartElementId = _ref2.cartElementId,
    style = _ref2.style,
    className = _ref2.className,
    _onChange = _ref2.onChange,
    _onClick = _ref2.onClick;
  var context = useEngineContext();
  locales.init(localeTexts, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut = _context$appHelper$ut.storage) === null || _context$appHelper$ut === void 0 ? void 0 : _context$appHelper$ut.get('umi_locale')) || 'en');
  var normalProduct = useMemo(function () {
    return isNormalProduct(product);
  }, [product]);
  var mergedDisabled = disabled || (product === null || product === void 0 ? void 0 : product.disabled) === 1 || (product === null || product === void 0 ? void 0 : product.disabled) === true;
  var title = resolveText((product === null || product === void 0 ? void 0 : product.title) || (product === null || product === void 0 ? void 0 : product.name));
  var textCover = getTextCover(title);
  var imageStyle = useMemo(function () {
    var _skuCardConfig$image, _skuCardConfig$image3;
    var _style = {};
    if (skuCardConfig !== null && skuCardConfig !== void 0 && (_skuCardConfig$image = skuCardConfig.image) !== null && _skuCardConfig$image !== void 0 && _skuCardConfig$image.width) {
      var _skuCardConfig$image2;
      _style.width = skuCardConfig === null || skuCardConfig === void 0 || (_skuCardConfig$image2 = skuCardConfig.image) === null || _skuCardConfig$image2 === void 0 ? void 0 : _skuCardConfig$image2.width;
    }
    if (skuCardConfig !== null && skuCardConfig !== void 0 && (_skuCardConfig$image3 = skuCardConfig.image) !== null && _skuCardConfig$image3 !== void 0 && _skuCardConfig$image3.height) {
      var _skuCardConfig$image4;
      _style.height = skuCardConfig === null || skuCardConfig === void 0 || (_skuCardConfig$image4 = skuCardConfig.image) === null || _skuCardConfig$image4 === void 0 ? void 0 : _skuCardConfig$image4.height;
    }
    return _style;
  }, [skuCardConfig]);
  var buildNextValue = function buildNextValue(nextNum) {
    var _is_charge_tax, _ref3;
    if (value) {
      return _objectSpread(_objectSpread({}, value), {}, {
        num: nextNum
      });
    }
    return {
      product_id: product === null || product === void 0 ? void 0 : product.id,
      num: nextNum,
      product_option_item: [],
      original_price: toStringValue(product === null || product === void 0 ? void 0 : product.original_price),
      is_charge_tax: (_is_charge_tax = product === null || product === void 0 ? void 0 : product.is_charge_tax) !== null && _is_charge_tax !== void 0 ? _is_charge_tax : 0,
      discount_list: [],
      product_bundle: (_ref3 = product === null || product === void 0 ? void 0 : product.product_bundle) !== null && _ref3 !== void 0 ? _ref3 : [],
      metadata: {}
    };
  };
  var cardMaxQuantity = useMemo(function () {
    var _stepperProps$min, _stepperProps$min2;
    var maxNum = 200;
    var detailAny = product;
    var hasVariantGroup = Array.isArray(detailAny === null || detailAny === void 0 ? void 0 : detailAny.variant_group) && detailAny.variant_group.length > 0;
    if (!hasVariantGroup && (detailAny === null || detailAny === void 0 ? void 0 : detailAny.is_track) === 1 && (detailAny === null || detailAny === void 0 ? void 0 : detailAny.over_sold) === 0) {
      var stock = toNumber(detailAny === null || detailAny === void 0 ? void 0 : detailAny.stock_quantity);
      maxNum = stock >= 200 ? 200 : stock;
    }
    var selectedVariantId = toNumber(value === null || value === void 0 ? void 0 : value.product_variant_id);
    if (selectedVariantId > 0 && Array.isArray(detailAny === null || detailAny === void 0 ? void 0 : detailAny.variant)) {
      var selectedVariant = detailAny.variant.find(function (item) {
        return toNumber(item === null || item === void 0 ? void 0 : item.id) === selectedVariantId;
      });
      if ((selectedVariant === null || selectedVariant === void 0 ? void 0 : selectedVariant.is_track) === 1 && (selectedVariant === null || selectedVariant === void 0 ? void 0 : selectedVariant.over_sold) === 0) {
        var variantStock = toNumber(selectedVariant === null || selectedVariant === void 0 ? void 0 : selectedVariant.stock_quantity);
        maxNum = variantStock >= 200 ? 200 : variantStock;
      }
    }
    var propMax = Number.isFinite(stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.max) ? Number(stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.max) : Infinity;
    var mergedMax = Math.min(maxNum, propMax);
    if (!Number.isFinite(mergedMax)) return Math.max((_stepperProps$min = stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.min) !== null && _stepperProps$min !== void 0 ? _stepperProps$min : 0, maxNum);
    return Math.max((_stepperProps$min2 = stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.min) !== null && _stepperProps$min2 !== void 0 ? _stepperProps$min2 : 0, mergedMax);
  }, [product, value === null || value === void 0 ? void 0 : value.product_variant_id, stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.max, stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.min]);
  var handleCardClick = function handleCardClick() {
    if (mergedDisabled) return;
    var meta = {
      intent: normalProduct ? 'detail' : 'options',
      trigger: 'card',
      product: product
    };
    _onClick === null || _onClick === void 0 || _onClick(value || {
      product_id: product === null || product === void 0 ? void 0 : product.id
    }, meta);
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: classNames(PREFIX, className),
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(PREFIX, "__inner"), _defineProperty({}, "".concat(PREFIX, "__inner-disabled"), mergedDisabled)),
    onClick: handleCardClick
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__image"),
    style: imageStyle
  }, product !== null && product !== void 0 && product.cover ? /*#__PURE__*/React.createElement("img", {
    src: imageAli.ali(product.cover, 360),
    alt: title
  }) : /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__image-placeholder")
  }, textCover)), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__content")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__title")
  }, title), /*#__PURE__*/React.createElement(PisellPriceText, {
    value: (_product$price = product.price) !== null && _product$price !== void 0 ? _product$price : 0,
    isMini: !!product.is_bundle
  })), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__action")
  }, normalProduct ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__stepper")
  }, /*#__PURE__*/React.createElement(NumericStepper, {
    value: (_value$num = value === null || value === void 0 ? void 0 : value.num) !== null && _value$num !== void 0 ? _value$num : 0,
    min: (_stepperProps$min3 = stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.min) !== null && _stepperProps$min3 !== void 0 ? _stepperProps$min3 : 0,
    max: cardMaxQuantity,
    step: (_stepperProps$step = stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.step) !== null && _stepperProps$step !== void 0 ? _stepperProps$step : 1,
    disabled: mergedDisabled,
    onLimitExceeded: function onLimitExceeded(limitMeta) {
      // 仅当 item_rule_limit 显式给出对应方向的文案时才提示。
      // 达到库存 / 默认上限等"非 item_rule_limit 触发"的场景不弹 toast。
      var raw = stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.limitMessage;
      // 兼容旧 string 用法（等价于 { max: string }）
      var limitMsg = typeof raw === 'string' ? {
        max: raw
      } : raw || {};
      var content = limitMeta.reason === 'max' ? limitMsg.max : limitMsg.min;
      if (!content) return;
      PisellToast({
        content: content,
        duration: 2
      });
    },
    onChange: function onChange(next, stepperMeta) {
      var _stepperProps$min4;
      var safeNext = Math.max((_stepperProps$min4 = stepperProps === null || stepperProps === void 0 ? void 0 : stepperProps.min) !== null && _stepperProps$min4 !== void 0 ? _stepperProps$min4 : 0, Math.min(cardMaxQuantity, next));
      if ((stepperMeta === null || stepperMeta === void 0 ? void 0 : stepperMeta.action) === 'increase' && stepperMeta.event && cartElementId) {
        cubicBezier({
          position: {
            x: stepperMeta.event.clientX,
            y: stepperMeta.event.clientY
          },
          cartElementId: cartElementId
        });
      }
      var nextValue = buildNextValue(safeNext);
      var meta = {
        intent: 'quantity',
        trigger: 'stepper',
        product: product
      };
      _onChange === null || _onChange === void 0 || _onChange(nextValue, meta);
    }
  })) : /*#__PURE__*/React.createElement(Button, {
    type: "default",
    size: "small",
    className: "".concat(PREFIX, "__options-button"),
    disabled: mergedDisabled,
    onClick: function onClick(e) {
      e.stopPropagation();
      var meta = {
        intent: 'options',
        trigger: 'button',
        product: product
      };
      _onClick === null || _onClick === void 0 || _onClick(value || {
        product_id: product === null || product === void 0 ? void 0 : product.id
      }, meta);
    }
  }, optionsText || locales.getText('pisell2.text.options'))))));
};
export default PisellSalesProductCard;