index.tsx 5.06 KB
import { FC, useRef, useEffect, useState } from 'react'
import { useStore } from '@/app/components/app/store'
import dayjs from 'dayjs'
import cn from '@/utils/classnames'
import s from './index.module.scss'
import Toast from '@/app/components/base/toast'
import { GET_PARAMS } from '@/app/components/base/chat/constants'
import { v4 as uuidv4 } from 'uuid'

type ReportProps = {
  content: any | null
}

const Report: FC<ReportProps> = ({ content }) => {
  const { globalConfig } = useStore.getState()
  const { report_end_date, report_start_date, report_type } = content
  const reportType = report_type == '周报' ? 1 : 2
  const [isExpanded, setIsExpanded] = useState(true)
  const iframeRef = useRef<HTMLIFrameElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const [containerHeight, setContainerHeight] = useState(150)
  const reportId = useRef<string>(uuidv4())

  const handleToggleExpand = () => {
    setIsExpanded(!isExpanded)
  }

  // 监听来自 iframe 的消息
  useEffect(() => {
    const handleMessage = (event: MessageEvent) => {
      if (event.data && event.data.type === 'RESIZE_IFRAME' && event.data.reportId === reportId.current) {
        const height = event.data.height
        if (height && height > 0) {
          setContainerHeight(height)
          console.log('收到 iframe 高度:', height, 'reportId:', reportId.current)
        }
      }
      if (event.data && event.data.type === 'COPY_SUCCESS') {
        Toast.notify({
          message: '链接复制成功,快去粘贴吧~',
          type: 'success',
        })
      }
    }

    window.addEventListener('message', handleMessage)

    return () => {
      window.removeEventListener('message', handleMessage)
    }
  }, [])

  // 向 iframe 发送获取高度的消息
  const requestIframeHeight = () => {
    if (iframeRef.current && iframeRef.current.contentWindow) {
      iframeRef.current.contentWindow.postMessage({ 
        type: 'GET_IFRAME_HEIGHT',
        reportId: reportId.current
      }, '*')
    }
  }

  // iframe 加载完成后请求高度
  const handleIframeLoad = () => {
    console.log('iframe 加载完成,请求高度, reportId:', reportId.current)
    // 延迟发送,确保 iframe 内部内容已渲染
    setTimeout(() => {
      requestIframeHeight()
    }, 300)
  }

  // 展开时也请求一次高度
  useEffect(() => {
    if (isExpanded) {
      setTimeout(() => {
        requestIframeHeight()
      }, 100)
    }
  }, [isExpanded])

  const reportDateText = () => {
    if (!report_start_date) return ''

    if (reportType === 2) {
      // 月报:2026-01-10 转成 2026 年 1 月
      return dayjs(report_start_date).format('YYYY年M月')
    } else if (reportType === 1) {
      // 周报:2026-01-10 转成 2026 年第 2 周
      const date = dayjs(report_start_date)
      const year = date.year()
      // 计算是该年的第几周
      const startOfYear = dayjs(`${year}-01-01`)
      const weekNumber = Math.ceil((date.diff(startOfYear, 'day') + 1 + startOfYear.day()) / 7)
      return `${year}年第${weekNumber}周`
    }
    return ''
  }
  if (!globalConfig) {
    console.warn('全局配置尚未加载')
    return null
  }
  if (!report_start_date || !report_end_date) return null
  const corpId = GET_PARAMS.get('corpId')
  let { reportUrl } = globalConfig
  reportUrl += `?reportStartDate=${report_start_date}&reportEndDate=${report_end_date}&reportType=${reportType}&corpId=${corpId}`
  return (
    <div className={cn(s['report-box'])}>
      {reportUrl && (
        <>
          <div className={cn(s['report-type-title'], !isExpanded ? s['expanded'] : '')} onClick={handleToggleExpand} style={{ cursor: 'pointer' }}>
            展业{report_type}
            <div className={cn(s['block'])}>{reportDateText()}</div>
            <div className={cn(s['arrow'], 'transition-transform duration-500', isExpanded && 'rotate-180')}>
              <img src="https://img02.glsx.com.cn/weapp/resource/saas/ai/ai-data-arrow.png" alt="arrow" />
            </div>
          </div>

          {/* 外层控制高度的容器 */}
          <div
            style={{
              overflow: 'hidden',
              transition: 'height 0.5s ease',
              height: isExpanded ? `${containerHeight}px` : '0px',
            }}>
            {/* 实际内容容器 */}
            <div ref={containerRef} style={{ height: '100%' }}>
              <iframe
                ref={iframeRef}
                src={reportUrl}
                title="报告预览"
                width="100%"
                height={containerHeight}
                onLoad={handleIframeLoad}
                style={{
                  border: 'none',
                  display: 'block',
                  borderRadius: '0 0 16px 16px',
                  minHeight: '150px',
                  height: `${containerHeight}px`,
                }}
                scrolling="no"
              />
            </div>
          </div>
        </>
      )}
    </div>
  )
}

export default Report