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); }
var _excluded = ["dataSource", "type", "cartSkuType", "isShowBookingHeader", "relatedProductDataSource", "addTimeProductDataSources", "rightActions", "rightActionsDisplay", "escapeDom", "isShowImage", "isFormSubject", "isShowDelete", "isShowInlineDelete", "isShowNote", "isShowAmountFooter", "disabledClick", "disabledEdit", "statusOptions", "statusLoading", "statusDisabled", "isShowRelatedProduct", "holderOptions", "onBookingStatusChange", "onAddTimeProductCard", "onAction", "onDelete", "onNote", "onCard", "onPromotion", "onGift"];
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 _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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useMemo, useState } from 'react';
import classNames from 'classnames';
import { Button, Divider, Dropdown } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { locales } from '@pisell/utils';
import BasicInfo from "../cartSkuCard/components/basicInfo";
import Packages from "../cartSkuCard/components/packages";
import AmountFooter from "../cartSkuCard/components/AmountFooter";
import Note from "../cartSkuCard/components/Note";
import Promotion from "../cartSkuCard/components/Promotion";
import Gift from "../cartSkuCard/components/Gift";
import { SwipeAction } from "../cartSkuCard/components/swipeAction";
import InlineActions from "../cartSkuCard/components/inlineActions";
import Action from "../components/Action";
import TimeRange from "./components/TimeRange";
import Resources from "./components/Resources";
import Holders from "./components/Holders";
import Iconfont from "../../iconfont";
var PREFIX = 'pisell-line-item';
var ADD_TIME_PRODUCTS_PREVIEW_COUNT = 2;
var DEFAULT_STATUS_COLOR = '#91caff';
var getStatusOption = function getStatusOption(status) {
  var statusOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  return statusOptions.find(function (option) {
    return option.key === status;
  }) || statusOptions[0] || {
    key: status || '',
    label: status || '-',
    color: DEFAULT_STATUS_COLOR
  };
};
var BookingLineItem = function BookingLineItem(props) {
  var _ref, _ref2, _dataSource$promotion;
  var dataSource = props.dataSource,
    type = props.type,
    cartSkuType = props.cartSkuType,
    isShowBookingHeader = props.isShowBookingHeader,
    relatedProductDataSource = props.relatedProductDataSource,
    _props$addTimeProduct = props.addTimeProductDataSources,
    addTimeProductDataSources = _props$addTimeProduct === void 0 ? [] : _props$addTimeProduct,
    _props$rightActions = props.rightActions,
    rightActions = _props$rightActions === void 0 ? [] : _props$rightActions,
    _props$rightActionsDi = props.rightActionsDisplay,
    rightActionsDisplay = _props$rightActionsDi === void 0 ? 'swipe' : _props$rightActionsDi,
    escapeDom = props.escapeDom,
    isShowImage = props.isShowImage,
    isFormSubject = props.isFormSubject,
    isShowDelete = props.isShowDelete,
    _props$isShowInlineDe = props.isShowInlineDelete,
    isShowInlineDelete = _props$isShowInlineDe === void 0 ? isShowDelete : _props$isShowInlineDe,
    isShowNote = props.isShowNote,
    isShowAmountFooter = props.isShowAmountFooter,
    disabledClick = props.disabledClick,
    disabledEdit = props.disabledEdit,
    _props$statusOptions = props.statusOptions,
    statusOptions = _props$statusOptions === void 0 ? [] : _props$statusOptions,
    _props$statusLoading = props.statusLoading,
    statusLoading = _props$statusLoading === void 0 ? false : _props$statusLoading,
    _props$statusDisabled = props.statusDisabled,
    statusDisabled = _props$statusDisabled === void 0 ? false : _props$statusDisabled,
    _props$isShowRelatedP = props.isShowRelatedProduct,
    isShowRelatedProduct = _props$isShowRelatedP === void 0 ? true : _props$isShowRelatedP,
    holderOptions = props.holderOptions,
    onBookingStatusChange = props.onBookingStatusChange,
    onAddTimeProductCard = props.onAddTimeProductCard,
    _onAction = props.onAction,
    onDelete = props.onDelete,
    onNote = props.onNote,
    onCard = props.onCard,
    onPromotion = props.onPromotion,
    onGift = props.onGift,
    other = _objectWithoutProperties(props, _excluded);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isAddTimeProductsExpanded = _useState2[0],
    setIsAddTimeProductsExpanded = _useState2[1];
  var isShowAction = dataSource.isShowAction,
    actionText = dataSource.actionText;
  var currentStatus = useMemo(function () {
    return getStatusOption(dataSource === null || dataSource === void 0 ? void 0 : dataSource.appointment_status, statusOptions);
  }, [dataSource === null || dataSource === void 0 ? void 0 : dataSource.appointment_status, statusOptions]);
  var statusMenuItems = useMemo(function () {
    return statusOptions.filter(function (option) {
      return option.key !== currentStatus.key;
    }).map(function (option) {
      return {
        key: option.key,
        label: option.label,
        danger: option.danger
      };
    });
  }, [currentStatus.key, statusOptions]);
  var canChangeStatus = !!onBookingStatusChange && !statusDisabled && !statusLoading && !!(statusMenuItems !== null && statusMenuItems !== void 0 && statusMenuItems.length);
  var deleteAction = {
    key: 'delete',
    text: /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__swipe-delete")
    }, /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__swipe-delete-icon")
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-trash-01"
    })), /*#__PURE__*/React.createElement("span", null, locales.getText('pisell2.cart.sku-card.actions.delete'))),
    color: 'danger',
    onClick: function onClick(e) {
      e.preventDefault();
      e.stopPropagation();
      onDelete === null || onDelete === void 0 || onDelete(dataSource);
    }
  };
  var bookingRightActions = isShowDelete ? rightActionsDisplay === 'inline' ? [].concat(_toConsumableArray(rightActions), [deleteAction]) : [deleteAction].concat(_toConsumableArray(rightActions)) : rightActions;
  var resolvedHolderOptions = (_ref = (_ref2 = holderOptions !== null && holderOptions !== void 0 ? holderOptions : dataSource === null || dataSource === void 0 ? void 0 : dataSource.holderOptions) !== null && _ref2 !== void 0 ? _ref2 : dataSource === null || dataSource === void 0 ? void 0 : dataSource.holders) !== null && _ref !== void 0 ? _ref : [];
  var resolvedIsFormSubject = isFormSubject !== null && isFormSubject !== void 0 ? isFormSubject : dataSource === null || dataSource === void 0 ? void 0 : dataSource.isFormSubject;
  var bookingTitle = String((dataSource === null || dataSource === void 0 ? void 0 : dataSource.booking_id) || '');
  var renderDeleteButton = function renderDeleteButton() {
    var inline = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    return isShowInlineDelete ? /*#__PURE__*/React.createElement("button", {
      className: classNames("".concat(PREFIX, "__delete-btn"), _defineProperty({}, "".concat(PREFIX, "__delete-btn--inline"), inline)),
      type: "button",
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
        onDelete === null || onDelete === void 0 || onDelete(dataSource);
      }
    }, /*#__PURE__*/React.createElement(Iconfont, {
      type: "pisell2-trash-01"
    })) : null;
  };
  var renderStatusButton = function renderStatusButton() {
    var statusButtonProps = {
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
      }
    };
    return /*#__PURE__*/React.createElement(Button, _extends({
      className: "".concat(PREFIX, "__status"),
      htmlType: "button",
      disabled: !canChangeStatus,
      loading: statusLoading
    }, statusButtonProps), /*#__PURE__*/React.createElement("span", {
      className: "".concat(PREFIX, "__status-label")
    }, currentStatus.label), canChangeStatus ? /*#__PURE__*/React.createElement(DownOutlined, null) : null);
  };
  var renderPromotion = dataSource !== null && dataSource !== void 0 && (_dataSource$promotion = dataSource.promotions) !== null && _dataSource$promotion !== void 0 && _dataSource$promotion.length ? /*#__PURE__*/React.createElement(Promotion, {
    promotions: dataSource === null || dataSource === void 0 ? void 0 : dataSource.promotions,
    onClick: function onClick(item) {
      return onPromotion === null || onPromotion === void 0 ? void 0 : onPromotion(item);
    }
  }) : null;
  var renderProductCard = function renderProductCard(productDataSource, source) {
    var _productDataSource$pr;
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
    if (!productDataSource || productDataSource !== null && productDataSource !== void 0 && productDataSource.isGift) return null;
    var _options$showProductP = options.showProductPromotion,
      showProductPromotion = _options$showProductP === void 0 ? true : _options$showProductP;
    var productPromotion = productDataSource !== null && productDataSource !== void 0 && (_productDataSource$pr = productDataSource.promotions) !== null && _productDataSource$pr !== void 0 && _productDataSource$pr.length ? /*#__PURE__*/React.createElement(Promotion, {
      promotions: productDataSource.promotions,
      onClick: function onClick(item) {
        return onPromotion === null || onPromotion === void 0 ? void 0 : onPromotion(item);
      }
    }) : null;
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(BasicInfo, {
      isShowImage: isShowImage,
      dataSource: productDataSource,
      type: cartSkuType,
      maxSpecsCount: props.maxSpecsCount || 1
    }), /*#__PURE__*/React.createElement(Packages, {
      dataSource: productDataSource,
      isShowImage: isShowImage,
      type: cartSkuType
    }), isShowAmountFooter ? /*#__PURE__*/React.createElement(AmountFooter, {
      item: productDataSource,
      hideDivider: false,
      type: "total"
    }) : null, showProductPromotion ? productPromotion : null, isShowNote ? /*#__PURE__*/React.createElement(Note, _extends({}, other, {
      item: productDataSource,
      disabledEdit: disabledEdit,
      openNote: function openNote() {
        return onNote === null || onNote === void 0 ? void 0 : onNote(source);
      }
    })) : null);
  };
  var renderAddTimeProducts = function renderAddTimeProducts() {
    var displayAddTimeProducts = addTimeProductDataSources.filter(function (item) {
      return item && !item.isGift;
    });
    if (displayAddTimeProducts.length === 0) return null;
    var shouldCollapse = displayAddTimeProducts.length > ADD_TIME_PRODUCTS_PREVIEW_COUNT;
    var visibleAddTimeProducts = isAddTimeProductsExpanded ? displayAddTimeProducts : displayAddTimeProducts.slice(0, ADD_TIME_PRODUCTS_PREVIEW_COUNT);
    return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Divider, {
      style: {
        margin: 0
      }
    }), /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__add-time-products")
    }, /*#__PURE__*/React.createElement("div", {
      className: "".concat(PREFIX, "__section-title")
    }, locales.getText('pisell2.line-item.add-time-products')), visibleAddTimeProducts.map(function (item, index) {
      var _ref3, _item$_id;
      var key = (_ref3 = (_item$_id = item === null || item === void 0 ? void 0 : item._id) !== null && _item$_id !== void 0 ? _item$_id : item === null || item === void 0 ? void 0 : item.id) !== null && _ref3 !== void 0 ? _ref3 : index;
      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(PREFIX, "__add-time-product-card"),
        key: "".concat(key),
        onClick: function onClick(e) {
          var _item$_origin;
          e.preventDefault();
          e.stopPropagation();
          if (disabledClick) return;
          onAddTimeProductCard === null || onAddTimeProductCard === void 0 || onAddTimeProductCard((_item$_origin = item === null || item === void 0 ? void 0 : item._origin) !== null && _item$_origin !== void 0 ? _item$_origin : item);
        }
      }, renderProductCard(item, item));
    }), shouldCollapse ? /*#__PURE__*/React.createElement("button", {
      className: "".concat(PREFIX, "__add-time-products-toggle"),
      type: "button",
      onClick: function onClick(e) {
        e.preventDefault();
        e.stopPropagation();
        setIsAddTimeProductsExpanded(function (expanded) {
          return !expanded;
        });
      }
    }, locales.getText(isAddTimeProductsExpanded ? 'pisell2.line-item.collapse' : 'pisell2.line-item.show-all')) : null));
  };
  if (dataSource !== null && dataSource !== void 0 && dataSource.isGift) return null;
  var cardContent = /*#__PURE__*/React.createElement("div", {
    className: classNames(PREFIX, "".concat(PREFIX, "--booking"), "".concat(PREFIX, "--").concat(type)),
    onClick: function onClick(e) {
      if (disabledClick) return;
      e.preventDefault();
      e.stopPropagation();
      onCard === null || onCard === void 0 || onCard(dataSource);
    }
  }, isShowBookingHeader ? /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__booking-header"),
    style: {
      '--pisell-line-item-header-color': currentStatus.color || DEFAULT_STATUS_COLOR
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__booking-main")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__booking-title")
  }, bookingTitle), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__booking-actions")
  }, canChangeStatus ? /*#__PURE__*/React.createElement(Dropdown, {
    menu: {
      items: statusMenuItems,
      onClick: function onClick(_ref4) {
        var key = _ref4.key;
        return onBookingStatusChange === null || onBookingStatusChange === void 0 ? void 0 : onBookingStatusChange(String(key), dataSource);
      }
    },
    trigger: ['click']
  }, renderStatusButton()) : renderStatusButton(), renderDeleteButton()))) : null, /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(PREFIX, "__booking-detail"), _defineProperty({}, "".concat(PREFIX, "__booking-detail--with-delete"), !isShowBookingHeader && isShowInlineDelete))
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__booking-detail-content")
  }, /*#__PURE__*/React.createElement(Resources, {
    dataSource: dataSource
  }), /*#__PURE__*/React.createElement(TimeRange, {
    dataSource: dataSource
  }), resolvedIsFormSubject ? /*#__PURE__*/React.createElement(Holders, {
    dataSource: dataSource,
    holderOptions: resolvedHolderOptions,
    isFormSubject: resolvedIsFormSubject
  }) : null), !isShowBookingHeader ? renderDeleteButton(true) : null), isShowRelatedProduct && relatedProductDataSource ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Divider, {
    style: {
      margin: 0
    }
  }), /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__related-product")
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "__related-product-card")
  }, renderProductCard(relatedProductDataSource, dataSource, {
    showProductPromotion: false
  }), renderPromotion, isShowAction && actionText ? /*#__PURE__*/React.createElement(Action, {
    item: dataSource,
    onAction: function onAction() {
      return _onAction === null || _onAction === void 0 ? void 0 : _onAction(dataSource);
    }
  }) : null))) : null, renderAddTimeProducts());
  return /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(PREFIX, "-wrapper-container"), _defineProperty({}, "".concat(PREFIX, "-wrapper-container--inline"), rightActionsDisplay === 'inline'))
  }, rightActionsDisplay === 'inline' ? /*#__PURE__*/React.createElement("div", {
    className: classNames("".concat(PREFIX, "-wrapper"), "".concat(PREFIX, "-wrapper--inline"))
  }, /*#__PURE__*/React.createElement("div", {
    className: "".concat(PREFIX, "-inline-content")
  }, cardContent), /*#__PURE__*/React.createElement(InlineActions, {
    actions: bookingRightActions
  })) : /*#__PURE__*/React.createElement(SwipeAction, {
    closeOnAction: false,
    className: classNames("".concat(PREFIX, "-wrapper")),
    rightActions: bookingRightActions,
    escapeDom: escapeDom
  }, cardContent), /*#__PURE__*/React.createElement(Gift, _extends({}, (dataSource === null || dataSource === void 0 ? void 0 : dataSource.giftData) || {}, {
    onClick: function onClick() {
      return onGift === null || onGift === void 0 ? void 0 : onGift(dataSource);
    }
  })));
};
export default BookingLineItem;