import {View, Text} from '@tarojs/components';
import {ITouchEvent} from '@tarojs/components/types/common';
import Taro from "@tarojs/taro";
import {FC, useEffect, useState} from "react";
import styles from './collapse.module.scss'

interface Props {
  text: string
}

const LineEllipsis:FC<Props> = ({text}:Props) => {
  const [disabled, setDisabled] = useState(false)
  const [isExpansioned, setIsExpansioned] = useState(false)
  const [overflow, setOverflow] = useState(false)

  useEffect(()=>{
    init()
  },[text])

  function init () {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery()
      query.select('#Text').boundingClientRect()
      query.exec((res) => {
        console.log({res})
        const height = res[0].height
        if(height <= 30) {
          setDisabled(true)
        }else{
          setOverflow(true)
        }
      })
    })
  }

  function handleExpend (e?: ITouchEvent) {
    e && e.stopPropagation();
    setOverflow(false)
    setIsExpansioned(true)
  }

  function handleHide (e?: ITouchEvent) {
    e && e.stopPropagation();
    setOverflow(true)
    setIsExpansioned(false)
  };

  function toggle () {
    if (disabled) return;
    if (isExpansioned) {
      handleHide();
    } else {
      handleExpend();
    }
  }

    return (
      <View
        id="wrap"
        style={{
          position: 'relative',
          color: '#999795',
          fontSize: '25rpx',
          overflow: overflow ? 'hidden' : 'unset',
          height: overflow ? '35rpx' : 'unset',
          lineHeight: overflow ? '35rpx' : '35rpx',
          marginTop:'24rpx',
        }}>
        <View id='Text' onClick={toggle}>
          {text}
          {!overflow && isExpansioned && (
            <Text className={styles.expansion} onClick={handleHide}>
              收起
            </Text>
          )}
        </View>
        {overflow && (
          <Text
            className={styles.expansion}
            onClick={handleExpend}
            style={{position: 'absolute', top: '0', right: '0', background: '#fff'}}>
            ...展开
          </Text>
        )}
      </View>
    );
  // }
}

export default LineEllipsis;
