import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["dataList", "maxSales", "onClick"];
import React, { useEffect, useState } from 'react';
import { debounce } from "../../utils/debounce";
import Carousel from "../carousel/carousel";
import "./goods-card-list.scss";
var GoodsCardList = function GoodsCardList(_ref) {
  var _ref$dataList = _ref.dataList,
    dataList = _ref$dataList === void 0 ? [] : _ref$dataList,
    _ref$maxSales = _ref.maxSales,
    maxSales = _ref$maxSales === void 0 ? 1000 : _ref$maxSales,
    _ref$onClick = _ref.onClick,
    _onClick = _ref$onClick === void 0 ? function () {} : _ref$onClick,
    otherProps = _objectWithoutPropertiesLoose(_ref, _excluded);
  var _useState = useState([]),
    positions = _useState[0],
    setPositions = _useState[1];
  var _useState2 = useState(0),
    columnWidth = _useState2[0],
    setColumnWidth = _useState2[1];
  var _useState3 = useState(0),
    maxContainerHeight = _useState3[0],
    setMaxContainerHeight = _useState3[1];
  useEffect(function () {
    var updateLayout = function updateLayout() {
      var container = document.querySelector('.waterfall-container');
      if (container) {
        var itemElements = document.querySelectorAll('.waterfall-item');
        // 横向间距
        var horizontalGap = 12;
        // 纵向间距
        var verticalGap = 10;
        var containerWidth = container.offsetWidth;
        // 每列宽度为容器宽度的一半减去间距
        var calculatedColumnWidth = (containerWidth - horizontalGap) / 2;
        setColumnWidth(calculatedColumnWidth);
        // 两列布局
        var columnHeights = Array.from({
          length: 2
        }).fill(0);
        var newPositions = [];
        // 循环计算所有的子元素的信息
        itemElements.forEach(function (item) {
          var _item$getBoundingClie = item.getBoundingClientRect(),
            height = _item$getBoundingClie.height;
          // 找到最短的那一列
          var minHeight = Math.min.apply(Math, columnHeights);
          // 获取该列的索引
          var columnIndex = columnHeights.indexOf(minHeight);
          var left = columnIndex * (calculatedColumnWidth + horizontalGap);
          var top = columnHeights[columnIndex];
          // 存储元素的定位
          newPositions.push({
            left: left,
            top: top
          });
          // 更新该列的高度
          columnHeights[columnIndex] += height + verticalGap;
        });
        // 更新位置
        setPositions(newPositions);
        setMaxContainerHeight(Math.max.apply(Math, columnHeights));
      }
    };
    var debouncedUpdateLayout = dataList.length < 15 ? updateLayout : debounce(updateLayout, 200);
    // 图片加载完成后更新布局
    var handleImageLoad = function handleImageLoad() {
      debouncedUpdateLayout();
    };
    // 初始化布局
    debouncedUpdateLayout();
    // 监听图片加载事件，以确保所有图片都加载完后再更新布局
    var images = document.querySelectorAll('.waterfall-container img');
    images.forEach(function (img) {
      // 如果图片已经加载完成（缓存中加载），则立即更新布局
      if (img.complete) {
        handleImageLoad();
      } else {
        // 如果图片未加载完成，监听加载事件
        img.addEventListener('load', handleImageLoad);
      }
    });

    // 窗口变化时更新布局
    window.addEventListener('resize', debouncedUpdateLayout);
    return function () {
      // 清理事件监听
      window.removeEventListener('resize', debouncedUpdateLayout);
      images.forEach(function (img) {
        return img.removeEventListener('load', handleImageLoad);
      });
    };
  },
  // 当 dataList 变化时重新计算
  [dataList]);
  var resolveResultDesc = function resolveResultDesc(desc) {
    var htmlString = "<div>" + desc + "</div>";
    // 创建一个虚拟的 DOM 容器
    var tempDiv = document.createElement('div');
    tempDiv.innerHTML = htmlString;
    // 提取文本
    return tempDiv.textContent || tempDiv.innerText;
  };
  var resultStyle = _extends({}, otherProps.style || {}, {
    height: maxContainerHeight + 20 + "px"
  });
  var _otherProps = _extends({}, otherProps || {}, {
    style: resultStyle
  });
  return /*#__PURE__*/React.createElement("div", _extends({
    className: "card-list-goods__container waterfall-container",
    style: {
      height: maxContainerHeight + 20 + "px"
    }
  }, _otherProps), dataList.map(function (item, index) {
    var _positions$index, _positions$index2;
    return /*#__PURE__*/React.createElement("div", {
      key: item.key,
      className: "card-list-goods__item waterfall-item",
      onClick: function onClick() {
        return _onClick(item);
      },
      style: {
        left: ((_positions$index = positions[index]) === null || _positions$index === void 0 ? void 0 : _positions$index.left) + "px",
        top: ((_positions$index2 = positions[index]) === null || _positions$index2 === void 0 ? void 0 : _positions$index2.top) + "px",
        width: columnWidth + "px"
      }
    }, item.imageList && item.imageList.length > 0 && /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__image"
    }, /*#__PURE__*/React.createElement(Carousel, {
      images: item.imageList,
      interval: 3000
    })), /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__content"
    }, /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__title"
    }, item.title), /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__desc"
    }, resolveResultDesc(item.desc)), /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__bottom"
    }, /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__unit"
    }, "\uFFE5"), /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__price"
    }, item.activePrice || item.price), item.activePrice && /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__unit__delete"
    }, "\uFFE5"), item.activePrice && /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__price__delete"
    }, item.price), /*#__PURE__*/React.createElement("div", {
      className: "card-list-goods__sales"
    }, "\u5DF2\u552E", item.sales > maxSales ? maxSales + "+" : item.sales))));
  }));
};
GoodsCardList.displayName = 'GoodsCardList';
export default GoodsCardList;