var _excluded = ["showTab", "layout", "list", "onChange", "amountSymbol", "scrollDom", "offsetDom", "value", "loading", "emptyDescription"];
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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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, { useEffect, useMemo, useRef, useState } from 'react';
import { Skeleton } from 'antd';
import { PisellEmpty } from '@pisell/materials';
import { useMemoizedFn, useDebounceFn } from 'ahooks';
import { locales } from '@pisell/utils';
import Tabs from "./tabs";
import ProductGroup, { ProductGroupSkeleton } from "../productGroup";
// 获取元素相对于指定滚动容器的偏移量
var getOffsetTopRelativeToScrollContainer = function getOffsetTopRelativeToScrollContainer(targetElement, scrollContainer) {
  if (!targetElement || !scrollContainer) return 0;

  // 如果目标元素就是滚动容器本身，返回0
  if (targetElement === scrollContainer) {
    return 0;
  }

  // 使用getBoundingClientRect计算相对偏移量
  var targetRect = targetElement.getBoundingClientRect();
  var containerRect = scrollContainer.getBoundingClientRect();

  // targetRect.top - containerRect.top 得到目标元素相对于容器顶部的可视距离
  // 考虑容器已经滚动的距离 再加上scrollContainer.scrollTop
  // 这样得到的是目标元素在容器内容中的绝对位置
  return targetRect.top - containerRect.top + scrollContainer.scrollTop;
};
var TabProduct = function TabProduct(props) {
  var _props$showTab = props.showTab,
    showTab = _props$showTab === void 0 ? true : _props$showTab,
    layout = props.layout,
    list = props.list,
    onChange = props.onChange,
    _props$amountSymbol = props.amountSymbol,
    amountSymbol = _props$amountSymbol === void 0 ? '$' : _props$amountSymbol,
    scrollDom = props.scrollDom,
    offsetDom = props.offsetDom,
    currentProductId = props.value,
    loading = props.loading,
    emptyDescription = props.emptyDescription,
    rest = _objectWithoutProperties(props, _excluded);
  var tabsRef = useRef();
  var _useState = useState(1),
    _useState2 = _slicedToArray(_useState, 2),
    currentGroupId = _useState2[0],
    setCurrentGroupId = _useState2[1];
  var tabLocatingRef = useRef(false);
  var ioRef = useRef(null);
  useEffect(function () {
    if (list !== null && list !== void 0 && list.length) {
      setCurrentGroupId(list[0].id);
      requestAnimationFrame(function () {
        handleObserver();
      });
    }

    // 清理函数
    return function () {
      handleUnobserver();
    };
  }, [list]);

  // 添加防抖的scroll函数
  var debouncedScroll = useDebounceFn(function (id) {
    var _tabsRef$current;
    tabsRef === null || tabsRef === void 0 || (_tabsRef$current = tabsRef.current) === null || _tabsRef$current === void 0 || _tabsRef$current.scroll(id);
  }, {
    wait: 100
  } // 100ms防抖
  );
  var handleObserver = useMemoizedFn(function () {
    var _marginTop = 270;
    var _marginBottom = window.innerHeight - 70 - 200 - 70;
    var _rootMargin = "".concat(_marginTop * -1, "px 0px ").concat(_marginBottom * -1, "px 0px");
    ioRef.current = new IntersectionObserver(function (entries) {
      var enteringEntries = entries.filter(function (entry) {
        return entry.isIntersecting;
      });
      if (enteringEntries.length > 0) {
        var _topMostEntry$target;
        // 选择最靠近顶部的元素
        var topMostEntry = enteringEntries.reduce(function (top, current) {
          return current.boundingClientRect.top < top.boundingClientRect.top ? current : top;
        });
        var targetId = topMostEntry === null || topMostEntry === void 0 || (_topMostEntry$target = topMostEntry.target) === null || _topMostEntry$target === void 0 ? void 0 : _topMostEntry$target.id;
        if (targetId) {
          var _targetId$split = targetId.split('-'),
            _targetId$split2 = _slicedToArray(_targetId$split, 2),
            name = _targetId$split2[0],
            id = _targetId$split2[1];
          var newGroupId = Number(id);
          if (!tabLocatingRef.current && !isNaN(newGroupId)) {
            setCurrentGroupId(newGroupId);
            debouncedScroll.run(id);
          }
        }
      }
    }, {
      root: null,
      rootMargin: _rootMargin
    });
    if (list !== null && list !== void 0 && list.length && ioRef.current) {
      var _iterator = _createForOfIteratorHelper(list),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var item = _step.value;
          var _item = document.querySelector("#list-".concat(item.id));
          if (_item) {
            ioRef.current.observe(_item);
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
  });
  var handleUnobserver = useMemoizedFn(function () {
    if (list !== null && list !== void 0 && list.length && ioRef.current) {
      var _iterator2 = _createForOfIteratorHelper(list),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var item = _step2.value;
          var _item = document.querySelector("#list-".concat(item.id));
          if (_item) {
            ioRef.current.unobserve(_item);
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
    // 断开观察器连接
    if (ioRef.current) {
      ioRef.current.disconnect();
      ioRef.current = null;
    }
  });
  var renderContent = function renderContent() {
    if (loading) {
      return /*#__PURE__*/React.createElement(ProductGroupSkeleton, {
        layout: layout
      });
    }
    if (!(list !== null && list !== void 0 && list.length)) {
      return /*#__PURE__*/React.createElement(PisellEmpty, {
        description: emptyDescription || locales.getText('pisell2.product-select.empty')
      });
    }
    return list.map(function (item, i) {
      return /*#__PURE__*/React.createElement("div", {
        id: "list-".concat(item.id),
        key: "list-".concat(item.id)
      }, /*#__PURE__*/React.createElement(ProductGroup, _extends({
        onSelectProduct: onChange,
        currentProductId: currentProductId,
        key: item.id,
        data: item,
        layout: layout
      }, rest)));
    });
  };
  var tabSkeleton = useMemo(function () {
    return /*#__PURE__*/React.createElement("div", {
      className: "booking-pisell-tabs"
    }, /*#__PURE__*/React.createElement("div", {
      className: "booking-pisell-tabs-btn-left",
      style: {
        marginLeft: 20,
        width: 0
      }
    }), /*#__PURE__*/React.createElement("div", {
      className: "booking-pisell-tabs-content"
    }, /*#__PURE__*/React.createElement(Skeleton.Button, {
      active: true,
      size: 'large',
      shape: 'round'
    })));
  }, []);
  return /*#__PURE__*/React.createElement(React.Fragment, null, showTab && list && list.length > 1 ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-product-select-tabs-wrapper"
  }, loading ? tabSkeleton : /*#__PURE__*/React.createElement(Tabs, {
    ref: tabsRef,
    options: list,
    rowKey: 'id',
    tab: currentGroupId,
    onChange: function onChange(e) {
      try {
        var _document, _document2, _document3;
        // 获取产品选择器包装容器
        var productSelectWrapper = document.querySelector('.pisell-product-select-wrapper');
        // 获取标签页包装容器
        var tabsWrapper = document.querySelector('.pisell-product-select-tabs-wrapper');
        // 计算标签页高度，用于滚动时的偏移
        var tabsHeight = 0;
        if (tabsWrapper) {
          tabsHeight = tabsWrapper.offsetHeight;
        }

        // 获取目标列表元素和滚动容器
        var targetListElement = (_document = document) === null || _document === void 0 ? void 0 : _document.querySelector('#list-' + e);
        var scrollContainer = scrollDom ? (_document2 = document) === null || _document2 === void 0 ? void 0 : _document2.querySelector(scrollDom) : null;
        // 获取额外偏移元素（如固定头部等）
        var offsetElement = offsetDom ? (_document3 = document) === null || _document3 === void 0 ? void 0 : _document3.querySelector(offsetDom) : null;
        var extraOffset = offsetElement ? offsetElement.clientHeight : 0;

        // 停止观察器，防止滚动时触发tab切换
        handleUnobserver();
        // 标记正在进行tab定位，避免滚动时的干扰
        tabLocatingRef.current = true;
        if (targetListElement && scrollContainer) {
          var _list$;
          if (e === ((_list$ = list[0]) === null || _list$ === void 0 ? void 0 : _list$.id)) {
            // 如果是第一个tab，滚动到产品选择器包装容器的位置
            if (productSelectWrapper) {
              var wrapperOffsetTop = getOffsetTopRelativeToScrollContainer(productSelectWrapper, scrollContainer);
              scrollContainer.scrollTop = wrapperOffsetTop - extraOffset;
            }
          } else {
            // 其他tab，滚动到对应列表元素位置，需要减去标签页高度
            var listOffsetTop = getOffsetTopRelativeToScrollContainer(targetListElement, scrollContainer);
            scrollContainer.scrollTop = listOffsetTop - tabsHeight - extraOffset;
          }
        }

        // 更新当前选中的分组ID
        setCurrentGroupId(e);
        // 触发防抖滚动
        debouncedScroll.run(e);
        // 延迟恢复观察器
        setTimeout(function () {
          tabLocatingRef.current = false;
          handleObserver();
        }, 500);
      } catch (error) {
        console.error('Tab onChange error:', error);
        // 即使出错也要恢复状态
        tabLocatingRef.current = false;
        setCurrentGroupId(e);
      }
    }
  })) : /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement("br", null)), /*#__PURE__*/React.createElement("div", {
    className: "pisell-product-select-product-list"
  }, renderContent()));
};
export default TabProduct;