import React, { useEffect, useRef, useState, useContext } from 'react'
import html2canvas from "html2canvas";
import CountContext from '@/components/Common/CreateContext'
import './index.less'

const BoxContent = (props: any) => {
  let sendDataToParent = useContext(CountContext) as any
  const componentRef = useRef(null) as any
  const boxRef = useRef(null) as any

  useEffect(() => {
    console.log(props?.screenshot);
    if (props?.screenshot) {
      // 截图打开
      sendDataToParent(generateImage()); // 调用父组件提供的回调函数，传递数据
    }
    else {
      // 不截图
    }
  }, [props?.screenshot]);

  useEffect(() => {
    // 监听组件的显示隐藏
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 当组件进入视口时，执行相应的逻辑
          console.log('Component is now visible')
          // boxRef.current.setWH()
          // 可以在这里触发你需要的操作
        }
      })
    })
    // observer.observe(componentRef.current)
    return () => {
      // observer.unobserve(componentRef.current)
    }
  }, [])

  const generateImage = async () => {
    try {
      const canvas = await html2canvas(componentRef.current);
      const image = canvas.toDataURL("image/png");
      return image
    } catch (error) {
      console.error("Error generating image:", error);
      return null
    }
  };

  return (
    <div className="BoxContent" ref={componentRef}>
      {/* BorderBox11 */}
      <div color={['#00d8ff', '#2362A6']} ref={boxRef}>
        <div className="boxTitle font-animate">
          {/* <i className="ya_icon" style={{ display: props?.config?.iconAddre === 'left' ? 'inline-block' : 'none' }}></i> */}
          {/* {props?.config?.title}/<span className="es">{props?.config?.es}</span> */}
          {/* <i className="ya_icon" style={{ display: props?.config?.iconAddre === 'right' ? 'inline-block' : 'none' }}></i> */}
        </div>
        <div className="canvasBox">
          <div className="canvasContent">{props.children}</div>
        </div>
      </div>
    </div>
  )
}
export default React.memo(BoxContent)
