import React, { useEffect, useRef, useState } from 'react'

import styles from '../css/TextEllipsis.module.scss'

interface ITextEllipsisProps {
  content: string | React.ReactNode // 展示的文本
  lineNumber?: number // 展示的行数
  showTipsText?: boolean // 是否需要提示文案
  openText?: string // 展开提示文案
  closeText?: string // 收起提示文案
  key?: number // 标识key
}
/**文本的展开收起暂时行高22px的 */
const TextEllipsis: React.FC<ITextEllipsisProps> = props => {
  const { content, lineNumber = 4, openText = '展开', closeText = '收起', showTipsText = false, key } = props
  const [expanded, setExpanded] = useState<boolean>(false) // false为收起，true展开
  const [isShowTips, setIsShowTips] = useState<boolean>(false)
  const ellipsisRef = useRef<HTMLDivElement>(null)

  const hanldeToOpenOrClose = (event: React.MouseEvent<HTMLElement, MouseEvent>) => {
    setExpanded(!expanded)
  }
  useEffect(() => {
    setIsShowTips(!!(ellipsisRef && ellipsisRef.current && ellipsisRef.current?.clientHeight >= 22 * lineNumber))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [content])

  return (
    <div className={styles['text-ellipsis-wrapper']} key={key}>
      <div className="content-text" style={{ WebkitLineClamp: expanded ? 9999 : lineNumber }} ref={ellipsisRef}>
        {isShowTips && showTipsText && (
          <span className="tips-text" onClick={hanldeToOpenOrClose}>
            {expanded ? closeText : openText}
          </span>
        )}
        {content}
      </div>
    </div>
  )
}

export default TextEllipsis
