import React, { useCallback, useRef, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import { useDispatch } from 'react-redux'
import { editPreview } from '@/store/action/layout'
import { handleCopyClick } from '@/utils/copyTxt'
import { MessageFu } from '@/utils/message'
import html2canvas from 'html2canvas'
import { domShowFu } from '@/utils/domShow'
import { baseURL } from '@/utils/http'

function PreviewOperate({ src }: { src?: string }) {
  const dispatch = useDispatch()
  const iframeRef = useRef<HTMLIFrameElement>(null)
  const downloadRef = useRef<HTMLButtonElement>(null)
  // 用于标记 iframe 是否加载完成且文档就绪
  const [isIframeReady, setIsIframeReady] = useState(false)
  // const cachedImageUrl = useRef<string | null>(null)

  const copyLink = useCallback(() => {
    if (src) {
      handleCopyClick(`${baseURL}/mini/#${src}`)
    } else {
      MessageFu.error('暂无数据')
    }
  }, [src])

  const downloadImg = useCallback(async () => {
    domShowFu('#AsyncSpinLoding', true)
    if (iframeRef.current && isIframeReady) {
      try {
        const iframeDocument = iframeRef.current.contentDocument!
        const elInput: HTMLElement | null = iframeDocument.querySelector('.el-input')
        const virInput: HTMLElement | null = iframeDocument.querySelector('#vir-input')
        if (iframeDocument) {
          if (elInput && virInput) {
            elInput.style.display = 'none'
            virInput.style.display = 'flex'
          }
          const canvas = await html2canvas(iframeDocument.body)
          // cachedImageUrl.current = canvas.toDataURL('image/png')
          const imageDataUrl = canvas.toDataURL('image/png')
          const link = document.createElement('a')
          link.download = 'preview.png'
          link.href = imageDataUrl
          link.click()
          domShowFu('#AsyncSpinLoding', false)
          if (elInput && virInput) {
            elInput.style.display = 'flex'
            virInput.style.display = 'none'
          }
        }
      } catch (error) {
        MessageFu.error('截图下载失败，请稍后重试')
      }
    }
  }, [isIframeReady])

  // const download = useCallback(async () => {
  //   if (!cachedImageUrl.current) {
  //     MessageFu.error('正在加载...')
  //     await downloadImg()
  //     return
  //   }

  //   const link = document.createElement('a')
  //   link.download = 'preview.png'
  //   link.href = cachedImageUrl.current
  //   link.click()
  // }, [downloadImg])

  useEffect(() => {
    const iframe = iframeRef.current
    if (iframe) {
      const handleLoad = () => {
        const iframeWindow = iframe.contentWindow
        if (iframeWindow) {
          // 检查 iframe 文档是否就绪
          const checkDocumentReady = () => {
            if (iframeWindow.document.readyState === 'complete') {
              const iframeDocument = iframeWindow.document
              // 动态修改 CSS 路径
              const linkElements = iframeDocument.querySelectorAll('link[rel="stylesheet"]')
              linkElements.forEach((link: any) => {
                if (link.href.includes('index-BNWQR98R.css')) {
                  // 替换为正确的 CSS 路径，请根据实际情况修改
                  link.href = `${baseURL}/mini/assets/index-BNWQR98R.css`
                }
                if (link.href.includes('index-DqAPdNY3.css')) {
                  // 替换为正确的 CSS 路径，请根据实际情况修改
                  link.href = `${baseURL}/mini/assets/index-DqAPdNY3.css`
                }
              })
              setIsIframeReady(true)
            } else {
              // 若未就绪，100 毫秒后再次检查
              setTimeout(checkDocumentReady, 100)
            }
          }
          checkDocumentReady()
        }
      }
      iframe.addEventListener('load', handleLoad)
      return () => {
        iframe.removeEventListener('load', handleLoad)
      }
    }
  }, [])

  // useEffect(() => {
  //   if (isIframeReady) {
  //     setTimeout(() => {
  //       downloadRef.current?.click()
  //     }, 300)
  //   }
  // }, [isIframeReady])

  return (
    <div className={styles.PreviewOperate}>
      <div className='PreviewOperateMain'>
        <div className='pageBox'>
          {src ? (
            <iframe ref={iframeRef} src={`${baseURL}/mini/#${src}`} title='preview' />
          ) : (
            <div className='noData'>暂无数据</div>
          )}
          <div className='copyLink'>
            <Button onClick={copyLink}>复制链接</Button>
            <Button ref={downloadRef} onClick={downloadImg} disabled={!isIframeReady}>
              下载图片
            </Button>
            <Button onClick={() => dispatch(editPreview({ isOpenPreview: false }))}>关闭</Button>
          </div>
        </div>
      </div>
    </div>
  )
}

const MemoPreviewOperate = React.memo(PreviewOperate)

export default MemoPreviewOperate
