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, { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';
import dayjs from 'dayjs';
import SkuDetailModal from "../../../pro/skuDetailModal";
import { Context as BookingContext } from "../../../components/booking/info/model";
import { useSalesSdkHostBridges } from "../context/SalesSdkHostBridgesContext";
import { useSalesSdk } from "../hooks/useSalesSdk";
import { prepareNormalProductEditCacheItem, transformNormalProductCreateConfirm } from "./transformNormalProductConfirm";
import { normalizeCatalogProduct, resolveCatalogProductId } from "../giftSelect/resolveCatalogProductId";
import { useMemoizedFn } from 'ahooks';

/** pending 长期未打开弹窗时的兜底超时 */
var OPEN_NORMAL_PRODUCT_DETAIL_TIMEOUT_MS = 120000;

/**
 * 挂载在 SalesSdkProvider 子树内，承接普通商品 SkuDetailModal Host 的渲染。
 * 仅响应本 Provider 实例 bridge 的请求，不依赖全局广播。
 */
export var NormalProductDetailHostRenderer = function NormalProductDetailHostRenderer() {
  var bridges = useSalesSdkHostBridges();
  var bridge = bridges.normalProductDetail;
  var pending = useSyncExternalStore(bridge.subscribe, bridge.getSnapshot, function () {
    return null;
  });
  var _useSalesSdk = useSalesSdk(),
    bookingTicket = _useSalesSdk.bookingTicket;
  var modalRef = useRef(null);
  var timerRef = useRef(null);
  var bookingContextValue = useMemo(function () {
    var _bookingTicket$getBoo, _bookingTicket$getBoo2;
    return {
      state: {
        bookingConfig: (_bookingTicket$getBoo = bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$getBoo2 = bookingTicket.getBookingConfig) === null || _bookingTicket$getBoo2 === void 0 ? void 0 : _bookingTicket$getBoo2.call(bookingTicket)) !== null && _bookingTicket$getBoo !== void 0 ? _bookingTicket$getBoo : null
      }
    };
  }, [bookingTicket, pending === null || pending === void 0 ? void 0 : pending.payload]);
  useEffect(function () {
    var _modalRef$current2, _payload$cacheItem;
    if (!pending) {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      return;
    }
    timerRef.current = setTimeout(function () {
      if (bridge.getSnapshot()) {
        console.error('[SalesSdk] openNormalProductDetail 超时：SkuDetailModal 未响应');
        bridge.complete(null);
      }
    }, OPEN_NORMAL_PRODUCT_DETAIL_TIMEOUT_MS);
    var payload = pending.payload;
    if (payload.mode === 'create') {
      var _ref, _detailPayload$produc, _modalRef$current;
      var detailPayload = payload.requiresDetailPayload;
      var item = normalizeCatalogProduct((_ref = (_detailPayload$produc = detailPayload.productData) !== null && _detailPayload$produc !== void 0 ? _detailPayload$produc : detailPayload.item) !== null && _ref !== void 0 ? _ref : {});
      var productId = resolveCatalogProductId(item);
      var rawDate = detailPayload.date;
      var date = dayjs(rawDate).isValid() ? dayjs(rawDate).format('YYYY-MM-DD') : dayjs().format('YYYY-MM-DD');
      (_modalRef$current = modalRef.current) === null || _modalRef$current === void 0 || _modalRef$current.open({
        id: productId !== null && productId !== void 0 ? productId : item === null || item === void 0 ? void 0 : item.id,
        date: date,
        is_eject: detailPayload.isEject,
        productData: item,
        skuDetailConfig: (item === null || item === void 0 ? void 0 : item.skuDetailConfig) || {}
      });
      return;
    }
    (_modalRef$current2 = modalRef.current) === null || _modalRef$current2 === void 0 || _modalRef$current2.open(_objectSpread(_objectSpread({}, payload.cacheItem), {}, {
      skuDetailConfig: payload.skuDetailConfig || ((_payload$cacheItem = payload.cacheItem) === null || _payload$cacheItem === void 0 ? void 0 : _payload$cacheItem.skuDetailConfig) || {}
    }));
    return function () {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [pending, bridge]);
  var handleConfirm = useMemoizedFn(function (data) {
    if (!pending) return;
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    if (pending.payload.mode === 'create') {
      var _ref2, _detailPayload$produc2;
      var detailPayload = pending.payload.requiresDetailPayload;
      var item = normalizeCatalogProduct((_ref2 = (_detailPayload$produc2 = detailPayload.productData) !== null && _detailPayload$produc2 !== void 0 ? _detailPayload$produc2 : detailPayload.item) !== null && _ref2 !== void 0 ? _ref2 : {});
      var productId = resolveCatalogProductId(item);
      if (!productId) {
        console.warn('[SalesSdk] openNormalProductDetail: 商品缺少有效 id/product_id');
        bridge.complete(null);
        return;
      }
      bridge.complete({
        mode: 'create',
        detailResult: transformNormalProductCreateConfirm(productId, data)
      });
      return;
    }
    bridge.complete({
      mode: 'edit',
      cacheItem: prepareNormalProductEditCacheItem(data)
    });
  });
  var handleClose = useMemoizedFn(function () {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    bridge.complete(null);
  });

  /**
   * 编辑态点击 Remove 时，把 SkuDetailModal 事件转交给购物车层删除当前行。
   *
   * @example
   * handleRemove();
   */
  var handleRemove = useMemoizedFn(function () {
    if (!pending) return;
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    if (pending.payload.mode !== 'edit') {
      bridge.complete(null);
      return;
    }
    bridge.complete({
      mode: 'remove'
    });
  });
  return /*#__PURE__*/React.createElement(BookingContext.Provider, {
    value: bookingContextValue
  }, /*#__PURE__*/React.createElement(SkuDetailModal, {
    ref: modalRef,
    onConfirm: handleConfirm,
    onClose: handleClose,
    onRemove: handleRemove
  }));
};