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); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { forwardRef, useImperativeHandle, useState, useMemo } from 'react';
import { PisellModal, Button } from '@pisell/materials';
import Decimal from 'decimal.js';
import { PisellAdjustPrice } from '@pisell/materials';
import { createPortal } from 'react-dom';
import cloneDeep from 'lodash/cloneDeep';
import { locales } from '@pisell/utils';
import Delete_wght300_24px from '@pisell/icon/es/Delete_wght300_24px';
import localeTexts from "./locales";
import "./index.less";
import PisellNumberSelector from "../pisellNumberSelector";
import NoteModal from "../../plus/noteModal";
import useEngineContext from "../../hooks/useEngineContext";
var SkuDetailModal = function SkuDetailModal(_ref, ref) {
  var _context$appHelper, _store$getState, _context$engine, _productData$_extend2, _productData$_extend4, _productData$_extend6;
  var onConfirm = _ref.onConfirm,
    onRemove = _ref.onRemove,
    onClose = _ref.onClose;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    open = _useState2[0],
    setOpen = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    productData = _useState4[0],
    setProductData = _useState4[1];
  var _useState5 = useState(''),
    _useState6 = _slicedToArray(_useState5, 2),
    note = _useState6[0],
    setNote = _useState6[1];
  var _useState7 = useState(1),
    _useState8 = _slicedToArray(_useState7, 2),
    quantity = _useState8[0],
    setQuantity = _useState8[1];
  var _useState9 = useState(0),
    _useState10 = _slicedToArray(_useState9, 2),
    priceOverride = _useState10[0],
    setPriceOverride = _useState10[1];
  var _useState11 = useState([]),
    _useState12 = _slicedToArray(_useState11, 2),
    discounts = _useState12[0],
    setDiscounts = _useState12[1];
  var _useState13 = useState(false),
    _useState14 = _slicedToArray(_useState13, 2),
    noteModalOpen = _useState14[0],
    setNoteModalOpen = _useState14[1];
  var _useState15 = useState(false),
    _useState16 = _slicedToArray(_useState15, 2),
    showPriceAdjustModal = _useState16[0],
    setShowPriceAdjustModal = _useState16[1];
  var context = useEngineContext();
  var _ref2 = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    store = _ref2.store;
  var symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || '$';
  locales.init(localeTexts, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || 'en');
  useImperativeHandle(ref, function () {
    return {
      open: function open(data) {
        var _data$_extend, _data$_extend2, _data$_extend3;
        var _data = cloneDeep(data);
        setProductData(_data);
        setNote((_data === null || _data === void 0 || (_data$_extend = _data._extend) === null || _data$_extend === void 0 ? void 0 : _data$_extend.note) || '');
        setQuantity((_data === null || _data === void 0 || (_data$_extend2 = _data._extend) === null || _data$_extend2 === void 0 ? void 0 : _data$_extend2.quantity) || 1);
        setPriceOverride((_data === null || _data === void 0 || (_data$_extend3 = _data._extend) === null || _data$_extend3 === void 0 ? void 0 : _data$_extend3.total) || 0);
        // 手动改价和折扣信息互斥，手工改价后需要清除折扣信息
        setDiscounts((_data === null || _data === void 0 ? void 0 : _data.discount_list) || []);
        setOpen(true);
        console.log('data>>>>>', _data);
      }
    };
  });
  var priceText = useMemo(function () {
    var _productData$_extend;
    var price = (productData === null || productData === void 0 || (_productData$_extend = productData._extend) === null || _productData$_extend === void 0 ? void 0 : _productData$_extend.price) || 0;
    var priceSign = Number(price) < 0 ? '-' : '';
    return "".concat(priceSign).concat(symbol).concat(Math.abs(Number(price)));
  }, [productData === null || productData === void 0 || (_productData$_extend2 = productData._extend) === null || _productData$_extend2 === void 0 ? void 0 : _productData$_extend2.price, symbol]);

  /**
   * @title 售价小计
   * @description subtotal = productData?._extend?.price * quantity
   */
  var subtotal = useMemo(function () {
    var _productData$_extend3;
    var dePrice = new Decimal((productData === null || productData === void 0 || (_productData$_extend3 = productData._extend) === null || _productData$_extend3 === void 0 ? void 0 : _productData$_extend3.price) || '0');
    var deQuantity = new Decimal(quantity || '1');
    return dePrice.mul(deQuantity);
  }, [productData === null || productData === void 0 || (_productData$_extend4 = productData._extend) === null || _productData$_extend4 === void 0 ? void 0 : _productData$_extend4.price, quantity]);
  var subtotalText = useMemo(function () {
    var priceSign = subtotal.toNumber() < 0 ? '-' : '';
    return "".concat(priceSign).concat(symbol).concat(subtotal.abs().toNumber().toFixed(2));
  }, [subtotal, symbol]);
  var discountsCount = useMemo(function () {
    return (discounts === null || discounts === void 0 ? void 0 : discounts.length) || 0;
  }, [discounts]);

  /**
   * @title 折扣信息
   */
  var totalDiscounts = useMemo(function () {
    if ((discounts === null || discounts === void 0 ? void 0 : discounts.length) > 0) {
      return discounts.reduce(function (sum, discount) {
        var includeType = ['discount_card', 'product_discount_card'];
        var _quantity = includeType.includes((discount === null || discount === void 0 ? void 0 : discount.type) || '') ? quantity : 1;
        return sum.plus(new Decimal((discount === null || discount === void 0 ? void 0 : discount.amount) || 0).mul(_quantity));
      }, new Decimal(0)).toNumber().toFixed(2);
    }
    return '0.00';
  }, [discounts, quantity]);

  /**
   * @title 最终价格
   * @description total = priceOverride * quantity
   */
  var finalTotal = useMemo(function () {
    var deTotal = new Decimal(priceOverride || '0');
    var deQuantity = new Decimal(quantity || '1');
    return deTotal.mul(deQuantity);
  }, [priceOverride, quantity]);
  var totalText = useMemo(function () {
    var priceSign = finalTotal.toNumber() < 0 ? '-' : '';
    return "".concat(priceSign).concat(symbol).concat(finalTotal.abs().toNumber().toFixed(2));
  }, [finalTotal, symbol]);

  /**
   * @title 价格变动
   * @description priceChange = (priceOverride - productData?._extend?.price) * quantity
   */
  var priceChange = useMemo(function () {
    var _productData$_extend5;
    var dePrice = new Decimal((productData === null || productData === void 0 || (_productData$_extend5 = productData._extend) === null || _productData$_extend5 === void 0 ? void 0 : _productData$_extend5.price) || '0');
    var dePriceOverride = new Decimal(priceOverride || '0');
    var deQuantity = new Decimal(quantity || '1');
    return dePriceOverride.minus(dePrice).mul(deQuantity);
  }, [priceOverride, quantity, productData === null || productData === void 0 || (_productData$_extend6 = productData._extend) === null || _productData$_extend6 === void 0 ? void 0 : _productData$_extend6.price]);
  var priceChangeText = useMemo(function () {
    var priceChangeNumber = priceChange.toNumber();
    var priceChangeSign = priceChangeNumber > 0 ? '+' : priceChangeNumber < 0 ? '-' : '';
    var absPriceChange = priceChange.abs().toNumber().toFixed(2);
    return "".concat(priceChangeSign).concat(symbol).concat(absPriceChange);
  }, [priceChange, symbol]);
  var priceOverrideText = useMemo(function () {
    var prefix = "(".concat(locales.getText('pisell2.text.sku.detail.modal.price.override'), " ");
    var priceOverrideNumber = new Decimal(priceOverride || '0');
    var priceOverrideSign = priceOverrideNumber.toNumber() < 0 ? '-' : '';
    var absPriceOverride = priceOverrideNumber.abs().toNumber().toFixed(2);
    return "".concat(prefix).concat(priceOverrideSign).concat(symbol).concat(absPriceOverride, ")");
  }, [priceOverride, symbol]);
  var modalCloseAction = function modalCloseAction() {
    setOpen(false);
    setProductData(null);
    setNote('');
    setQuantity(1);
    setPriceOverride(0);
    setNoteModalOpen(false);
    setShowPriceAdjustModal(false);
    setDiscounts([]);
  };
  var handleCancel = function handleCancel() {
    modalCloseAction();
    onClose === null || onClose === void 0 || onClose();
  };
  var handleConfirm = function handleConfirm() {
    if (productData && onConfirm) {
      var updatedData = _objectSpread(_objectSpread({}, productData), {}, {
        discount_list: discounts || [],
        _extend: _objectSpread(_objectSpread({}, (productData === null || productData === void 0 ? void 0 : productData._extend) || {}), {}, {
          quantity: quantity,
          note: note,
          total: priceOverride
        })
      });
      onConfirm(updatedData);
      modalCloseAction();
    }
  };
  var handleRemove = function handleRemove() {
    if (productData && onRemove) {
      onRemove(productData);
      modalCloseAction();
    }
  };
  var handleManualPriceChange = function handleManualPriceChange() {
    if (productData) {
      // 这里可以打开一个价格修改弹窗
      console.log('Manual price change for:', productData.id);
      onOpenPriceAdjust();
    }
  };
  var handleQuantityChange = function handleQuantityChange(value) {
    if (value && value > 0) {
      setQuantity(value);
    }
  };
  var onNoteConfirm = function onNoteConfirm(note) {
    setNote(note);
    setNoteModalOpen(false);
  };
  var onNoteDelete = function onNoteDelete() {
    setNote('');
    setNoteModalOpen(false);
  };
  var onNoteCancel = function onNoteCancel() {
    setNoteModalOpen(false);
  };
  var onOpenPriceAdjust = function onOpenPriceAdjust() {
    setShowPriceAdjustModal(true);
  };
  var handlePriceAdjustConfirm = function handlePriceAdjustConfirm(value) {
    setPriceOverride(value);
    // 手动改价后需要清除折扣信息
    setDiscounts([]);
    setShowPriceAdjustModal(false);
  };

  // 无图时使用商品名称前两个字作为封面文字
  var coverText = useMemo(function () {
    var _productData$title;
    var title = (productData === null || productData === void 0 || (_productData$title = productData.title) === null || _productData$title === void 0 ? void 0 : _productData$title.trim()) || '';
    if (!title) return '';
    return Array.from(title).slice(0, 2).join('');
  }, [productData === null || productData === void 0 ? void 0 : productData.title]);
  if (!productData) return null;
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(PisellModal, {
    platform: "pc",
    open: open,
    title: "",
    headerDivider: false,
    footer: null,
    onCancel: handleCancel,
    destroyOnClose: true,
    width: 880,
    className: "pisell-sku-detail-modal"
  }, /*#__PURE__*/React.createElement("div", {
    className: "sku-detail-content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "sku-detail-content-main"
  }, /*#__PURE__*/React.createElement("div", {
    className: "sku-detail-left"
  }, /*#__PURE__*/React.createElement("div", {
    className: "product-image"
  }, productData.cover ? /*#__PURE__*/React.createElement("img", {
    src: productData.cover || ''
  }) : /*#__PURE__*/React.createElement("div", {
    className: "product-cover-text"
  }, coverText)), /*#__PURE__*/React.createElement("div", {
    className: "product-actions"
  }, /*#__PURE__*/React.createElement(Button, {
    size: "large",
    className: "add-note-btn",
    onClick: function onClick() {
      return setNoteModalOpen(true);
    }
  }, locales.getText('pisell2.text.sku.detail.modal.btn.add.note')))), /*#__PURE__*/React.createElement("div", {
    className: "sku-detail-right"
  }, /*#__PURE__*/React.createElement("div", {
    className: "product-info"
  }, /*#__PURE__*/React.createElement("div", {
    className: "product-info-left"
  }, /*#__PURE__*/React.createElement("div", {
    className: "product-name"
  }, (productData === null || productData === void 0 ? void 0 : productData.title) || ''), /*#__PURE__*/React.createElement("div", {
    className: "product-spec"
  })), /*#__PURE__*/React.createElement("div", {
    className: "item-price"
  }, priceText)), /*#__PURE__*/React.createElement("div", {
    className: "quantity-section"
  }, /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.text.sku.detail.modal.quantity')), /*#__PURE__*/React.createElement(PisellNumberSelector, {
    value: quantity,
    onChange: handleQuantityChange,
    min: 1,
    max: 99999,
    step: 1,
    size: "middle",
    enablePriceAdjust: true
  })), /*#__PURE__*/React.createElement("div", {
    className: "note-section"
  }, note && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", null, locales.getText('pisell2.text.sku.detail.modal.note')), /*#__PURE__*/React.createElement("div", {
    className: "note-text",
    onClick: function onClick() {
      return setNoteModalOpen(true);
    }
  }, note))), /*#__PURE__*/React.createElement("div", {
    className: "price-summary-section"
  }, /*#__PURE__*/React.createElement("div", {
    className: "price-item"
  }, /*#__PURE__*/React.createElement("div", null, locales.getText('pisell2.text.sku.detail.modal.subtotal')), /*#__PURE__*/React.createElement("div", null, subtotalText)), /*#__PURE__*/React.createElement("div", {
    className: "price-item"
  }, /*#__PURE__*/React.createElement("div", null, locales.getText('pisell2.text.sku.detail.modal.discount'), discountsCount > 0 && /*#__PURE__*/React.createElement("span", {
    className: "price-item-danger"
  }, "\xA0(", discountsCount, ")")), /*#__PURE__*/React.createElement("div", {
    className: "price-item-danger"
  }, discountsCount > 0 ? '-' : '', symbol, totalDiscounts)), /*#__PURE__*/React.createElement("div", {
    className: "price-item"
  }, /*#__PURE__*/React.createElement("div", null, locales.getText('pisell2.text.sku.detail.modal.manual.price.change'), /*#__PURE__*/React.createElement("span", {
    className: "price-item-override",
    onClick: onOpenPriceAdjust
  }, priceOverrideText)), /*#__PURE__*/React.createElement("div", {
    className: "price-item-danger"
  }, discountsCount > 0 ? "".concat(symbol, "0.00") : priceChangeText)), /*#__PURE__*/React.createElement("div", {
    className: "price-item-total"
  }, /*#__PURE__*/React.createElement("div", null, locales.getText('pisell2.text.sku.detail.modal.total'), /*#__PURE__*/React.createElement("span", {
    className: "price-item-total-gst"
  }, "\uFF08", productData !== null && productData !== void 0 && productData.is_charge_tax ? locales.getText('pisell2.text.sku.detail.modal.gst.incl') : locales.getText('pisell2.text.sku.detail.modal.gst.excl'), "\uFF09")), /*#__PURE__*/React.createElement("div", null, totalText))))), /*#__PURE__*/React.createElement("div", {
    className: "sku-detail-content-footer"
  }, /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    danger: true,
    size: "large",
    icon: /*#__PURE__*/React.createElement(Delete_wght300_24px, {
      style: {
        fontSize: 20
      }
    }),
    className: "sku-detail-content-footer-remove-btn",
    onClick: handleRemove
  }, locales.getText('pisell2.text.sku.detail.modal.btn.remove')), /*#__PURE__*/React.createElement("div", {
    className: "modal-actions"
  }, /*#__PURE__*/React.createElement(Button, {
    type: "default",
    size: "large",
    onClick: handleManualPriceChange,
    className: "sku-detail-content-footer-price-btn"
  }, /*#__PURE__*/React.createElement("span", {
    className: "sku-detail-content-footer-price-btn-text"
  }, locales.getText('pisell2.text.sku.detail.modal.btn.manual.price.change'))), /*#__PURE__*/React.createElement(Button, {
    type: "primary",
    size: "large",
    onClick: handleConfirm,
    className: "sku-detail-content-footer-confirm-btn"
  }, locales.getText('pisell2.text.sku.detail.modal.btn.confirm'))))), noteModalOpen && /*#__PURE__*/React.createElement(NoteModal, {
    open: noteModalOpen,
    value: note,
    onCancel: onNoteCancel,
    onConfirm: onNoteConfirm,
    onDelete: onNoteDelete
  }), showPriceAdjustModal && /*#__PURE__*/createPortal( /*#__PURE__*/React.createElement("div", {
    className: "pisell-price-adjust-overlay"
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-price-adjust-backdrop",
    onMouseDown: function onMouseDown(e) {
      e.preventDefault();
      setShowPriceAdjustModal(false);
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "pisell-price-adjust-container"
  }, /*#__PURE__*/React.createElement(PisellAdjustPrice, {
    originValue: priceOverride,
    value: priceOverride,
    onChange: handlePriceAdjustConfirm,
    selectType: "dark"
  }))), document.body)));
};
export default /*#__PURE__*/forwardRef(SkuDetailModal);