var _excluded = ["showTab", "layout", "list", "onChange", "amountSymbol", "scrollDom", "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 io = null;
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,
    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];
  useEffect(function () {
    if (list !== null && list !== void 0 && list.length) {
      setCurrentGroupId(list[0].id);
      requestAnimationFrame(function () {
        handleObserver();
      });
    }
  }, [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");
    io = 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 _topMostEntry$target$ = topMostEntry === null || topMostEntry === void 0 || (_topMostEntry$target = topMostEntry.target) === null || _topMostEntry$target === void 0 || (_topMostEntry$target = _topMostEntry$target.id) === null || _topMostEntry$target === void 0 ? void 0 : _topMostEntry$target.split('-'),
          _topMostEntry$target$2 = _slicedToArray(_topMostEntry$target$, 2),
          name = _topMostEntry$target$2[0],
          id = _topMostEntry$target$2[1];
        var newGroupId = Number(id);
        setCurrentGroupId(newGroupId);
        debouncedScroll.run(id);
        // tabsRef?.current?.scroll(id);
      }
    }, {
      root: null,
      rootMargin: _rootMargin
    });
    if (list !== null && list !== void 0 && list.length) {
      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) {
            io.observe(_item);
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    }
  });
  var handleUnobserver = useMemoizedFn(function () {
    if (list !== null && list !== void 0 && list.length && io) {
      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) {
            io.unobserve(_item);
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
  });
  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: i
      }, /*#__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 ? /*#__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) {
      var _document, _document2;
      var comWrapper = document.querySelector('.pisell-product-select-wrapper');
      var categoryDom = document.querySelector('.pisell-product-select-tabs-wrapper');
      var wrapperOffsetTop = comWrapper.offsetTop;
      var top = 0;
      if (categoryDom) {
        top = categoryDom.offsetHeight;
      }
      var dom = (_document = document) === null || _document === void 0 ? void 0 : _document.querySelector('#list-' + e);
      var main = (_document2 = document) === null || _document2 === void 0 ? void 0 : _document2.querySelector(scrollDom);
      if (dom && main) {
        var _list$;
        if (e === ((_list$ = list[0]) === null || _list$ === void 0 ? void 0 : _list$.id)) {
          main.scrollTop = 0;
        } else {
          main.scrollTop = dom.offsetTop - top - wrapperOffsetTop;
        }
      }
      handleUnobserver();
      setCurrentGroupId(e);
      setTimeout(function () {
        handleObserver();
      }, 1000);
    }
  })) : null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-product-select-product-list"
  }, renderContent()));
};
export default TabProduct;