function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
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, { useMemo, useState } from 'react';
import { ProductCard, Iconfont } from '@pisell/materials';
// import ProductCard from '../../../../../../materials/src/components/productCard';
import useClearCart from "../../hooks/useClearCart";
import { useContext } from "../../hooks/useContext";
import useAddService from "../../hooks/useAddService";
import { useMemoizedFn } from 'ahooks';
import { isNormalProductByDurationSchedule } from "../../../booking/info/service2/utils";
import PisellNumberSelector from "../../../../pro/pisellNumberSelector";
import { formatAmount } from "@pisell/utils";
import { locales } from '@pisell/utils';
import Decimal from 'decimal.js';
var Product = function Product(props) {
  var id = props.id,
    lists = props.lists,
    _props$isAdd = props.isAdd,
    isAdd = _props$isAdd === void 0 ? true : _props$isAdd;
  var _useContext = useContext(),
    state = _useContext.state,
    _onAction = _useContext.onAction,
    onChange = _useContext.onChange;
  var disabledEdit = state.disabledEdit,
    isShowPackageNote = state.isShowPackageNote,
    isShowNote = state.isShowNote,
    hideAddBtn = state.hideAddBtn,
    platform = state.platform,
    isShowChangeResource = state.isShowChangeResource,
    isShowDelete = state.isShowDelete,
    isShowChangeHolder = state.isShowChangeHolder,
    isShowHolder = state.isShowHolder,
    isShowAddHolderButton = state.isShowAddHolderButton,
    isShowEditProduct = state.isShowEditProduct,
    _state$productCardSty = state.productCardStyleConfig,
    productCardStyleConfig = _state$productCardSty === void 0 ? {} : _state$productCardSty;
  var clearCart = useClearCart(id);

  // 控制编辑区域展开收起状态
  var _useState = useState(true),
    _useState2 = _slicedToArray(_useState, 2),
    isEditExpanded = _useState2[0],
    setIsEditExpanded = _useState2[1];

  /**
   * @title: 更新商品数据
   * @description:
   * @param {any} item
   * @return {*}
   * @Author: WangHan
   * @Date: 2024-11-28 22:02
   */
  var handleChange = useMemoizedFn(function (item, type, other) {
    if (disabledEdit && !(other !== null && other !== void 0 && other.disabled)) return;
    onChange(item, type, other);
  });

  // 切换编辑区域展开收起状态
  var toggleEditExpanded = useMemoizedFn(function (e) {
    e === null || e === void 0 || e.preventDefault();
    setIsEditExpanded(!isEditExpanded);
  });
  var productParams = useMemo(function () {
    return {
      isShowNote: isShowNote,
      isShowPackageNote: isShowPackageNote,
      disabledEdit: disabledEdit,
      isShowChangeResource: isShowChangeResource,
      isShowChangeHolder: isShowChangeHolder,
      isShowDelete: isShowDelete,
      isShowHolder: isShowHolder,
      isShowAddHolderButton: isShowAddHolderButton,
      isShowEditProduct: isShowEditProduct
    };
  }, [isShowNote, isShowPackageNote, disabledEdit, isShowChangeResource, isShowDelete, isShowHolder, isShowAddHolderButton, isShowChangeHolder, isShowEditProduct]);
  var getProductCardStyleProps = useMemoizedFn(function (type) {
    var conf = productCardStyleConfig["".concat(type, "_product_card_style")];
    if (state.scenario !== 'booking2') return {};
    return {
      isShowImage: conf === null || conf === void 0 ? void 0 : conf.show_product_image,
      isShowDelete: conf === null || conf === void 0 ? void 0 : conf.show_remove_button,
      disabledEdit: true
    };
  });

  // 预先根据是否处于编辑态切分列表，避免多次 filter 计算
  var editItems = useMemo(function () {
    return (lists || []).filter(function (item) {
      var _item$_origin;
      return item === null || item === void 0 || (_item$_origin = item._origin) === null || _item$_origin === void 0 ? void 0 : _item$_origin.edit;
    });
  }, [lists]);
  var normalItems = useMemo(function () {
    return (lists || []).filter(function (item) {
      var _item$_origin2;
      return !(item !== null && item !== void 0 && (_item$_origin2 = item._origin) !== null && _item$_origin2 !== void 0 && _item$_origin2.edit);
    });
  }, [lists]);
  var editTotal = useMemo(function () {
    var total = editItems.reduce(function (total, item) {
      var itemTotal = new Decimal((item === null || item === void 0 ? void 0 : item.total) || 0).mul(item.num);
      return total.add(itemTotal);
    }, new Decimal(0));
    return formatAmount(total.toNumber(), 2, (state === null || state === void 0 ? void 0 : state.amountSymbol) || '$');
  }, [editItems]);

  // 统一渲染单个商品卡片，去重映射逻辑
  var renderProductItem = useMemoizedFn(function (item) {
    var Comp = ProductCard;
    var isRetail;
    if (state.scenario === 'booking2') {
      isRetail = isNormalProductByDurationSchedule(item === null || item === void 0 ? void 0 : item._origin);
      Comp = ProductCard.V2;
    }
    return /*#__PURE__*/React.createElement(Comp, _extends({
      type: isRetail ? 'a2' : 'a5',
      rightActions: [{
        key: 'update_number',
        text: /*#__PURE__*/React.createElement(PisellNumberSelector, {
          enablePriceAdjust: true,
          min: 1,
          className: "pisell-sku-card__pisell-number-setter",
          value: item === null || item === void 0 ? void 0 : item.num,
          onChange: function onChange(value) {
            if (value < 1) {
              handleChange(item, 'num', {
                num: 1
              });
            } else {
              handleChange(item, 'num', {
                num: value
              });
            }
          }
        }),
        color: '#667085'
      }],
      escapeDom: ".pisell-number-selector-popover",
      key: item._id,
      dataSource: item,
      onAction: function onAction(e) {
        return _onAction === null || _onAction === void 0 ? void 0 : _onAction(e);
      },
      onDelete: function onDelete(e) {
        return handleChange(e, 'delete', item);
      },
      onNote: function onNote(e) {
        return handleChange(e, 'note', {
          note: e.note
        });
      },
      onLike: function onLike(e) {
        return handleChange(e, 'like', {
          like_status: e.like_status
        });
      },
      onEditProduct: function onEditProduct(e) {
        return handleChange === null || handleChange === void 0 ? void 0 : handleChange(e, 'edit_product');
      },
      onCard: function onCard(e) {
        return handleChange === null || handleChange === void 0 ? void 0 : handleChange(e, 'view');
      },
      onChangeResource: function onChangeResource(e) {
        return handleChange(item, 'change_resource', e);
      },
      onChangeHolder: function onChangeHolder(e) {
        return handleChange(item, 'change_holder', e);
      },
      onAddHolder: function onAddHolder(e) {
        return handleChange(item, 'add_holder', e);
      }
    }, productParams, getProductCardStyleProps(isRetail ? 'retail' : 'appointment'), {
      scenario: state.scenario
    }));
  });
  return useMemo(function () {
    console.log('render cart', lists);
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-content"
    }, clearCart, editItems.length > 0 && /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-edit"
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-edit-header",
      onClick: toggleEditExpanded,
      style: {
        cursor: 'pointer'
      }
    }, /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-edit-header-title"
    }, locales.getText('pisell2.text.shopping-cart.save.items')(editItems.length)), /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-edit-header-summary"
    }, editTotal), /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-edit-header-switch"
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-chevron-down",
      style: {
        transform: isEditExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
        transition: 'transform 0.3s ease'
      }
    }))), /*#__PURE__*/React.createElement("div", {
      className: "pisell-lowcode__shopping-cart-edit-content",
      style: {
        maxHeight: isEditExpanded ? 'unset' : '0',
        overflow: 'hidden',
        transition: 'max-height 0.3s ease'
      }
    }, editItems.map(renderProductItem))), normalItems.map(renderProductItem), !hideAddBtn && platform !== 'h5' && isAdd ? useAddService(id, 'more') : null);
  }, [clearCart, editItems, normalItems, productParams, hideAddBtn, isAdd, platform, isEditExpanded]);
};
export default Product;