import React, { memo, useContext, useEffect, useRef } from 'react';
import { TPhotoAdsConfig } from './schema';
import logo from 'editorAssets/hiHouse/图片广告-120x120.png';
import withLogo from 'editorUtils/withLogo';
import { PhotoAds as Component } from 'lwj-mobile-ui';
import Cover from 'editorComponents/Cover';
import _ from 'lodash';
import { useAutosize } from '../hooks/useAutosize';
import { dooringContext } from 'src/pages/lwj-editor/layouts';

const PhotoAds: React.FC<TPhotoAdsConfig> = memo((props) => {
  const { containerRef, updateHeight } = useAutosize([]);
  const context = useContext(dooringContext);
  const updateDomHeight = (arr: any, height: number) => {
    const len = arr?.length || 0;
    for (let i = 0; i < len; ++i) {
      const cur = arr[i];
      cur.style.height = height + 'px';
    }
  };

  const handleCarouselOnload = () => {
    if (containerRef?.current) {
      const { parentElement } = containerRef.current || {};
      if (parentElement) {
        const current = containerRef.current;
        const imgs = current?.querySelectorAll('img');
        let height = 0;
        const len = imgs?.length || 0;
        for (let i = 0; i < len; ++i) {
          const cur = imgs?.[i];
          const curHeight = cur?.clientHeight || 0;
          height = Math.max(height, curHeight);
        }
        const taroImageCores = current?.querySelectorAll('taro-image-core') || [];
        const taroSwiperCores = current?.querySelectorAll('taro-swiper-core') || [];
        updateDomHeight(taroImageCores, height);
        updateDomHeight(taroSwiperCores, height);
        updateHeight(height, parentElement.id);
      }
    }
  };

  const handleNormalOnload = () => {
    if (containerRef?.current) {
      const { parentElement } = containerRef.current || {};
      if (parentElement) {
        const imgs = containerRef.current?.getElementsByTagName('img');
        let height = 0;
        const len = imgs?.length || 0;
        for (let i = 0; i < len; ++i) {
          const cur = imgs?.[i];
          height += cur?.clientHeight || 0;
        }
        updateHeight(height, parentElement.id);
      }
    }
  };
  const handleOnload = _.debounce(
    props.template === 'carousel' ? handleCarouselOnload : handleNormalOnload,
    500,
  );
  const onLoad = (idx) => {
    context.removeImageLoadingNum?.(`${props.index}-${idx}`)
  }
  console.log("photo ads", props)
  return (
    <div ref={containerRef}>
      <Component autoplay imageCompression={false} handleOnLoad={(idx) => {
        onLoad(idx)
        handleOnload()
      }} {...props} />
    </div>
  );
});

export default withLogo(PhotoAds, logo);
