import React, { useMemo, useState, useEffect, useRef } from 'react';
import { isArray } from 'cbkfe-utils';
import { Toast } from 'cbkfe-ui';
import './style/index';

function remTopx(int) {
    let docEl = document.documentElement;
    let rem = (docEl.clientWidth > 800 ? 800 : docEl.clientWidth) / 18.75;
    return int * rem;
}

export default function Warn({ messages, className, marginTop = 0.75, lineHeight = 0.95, limitLine = 2, children, isFold = true }) {

    const [_limitLine, setLimitLine] = useState(limitLine);
    const [fold, setFold] = useState(isFold);
    const [showFoldArrow, updateShowFoldArrow] = useState(false);
    const warnRef = useRef(null);

    useEffect(() => {
        if (!messages && !children) return;
        if (!warnRef || !warnRef.current) return;
        let dom = warnRef.current;
        // 检测只有一个数据并且这个数据只有一行的情况
        if (_limitLine > 1 && dom.children.length === 1 && (dom.children[0].offsetHeight) <= remTopx(lineHeight)) {
            setLimitLine(1);
            return;
        }
        // 这个减去5是为了保证精度
        if ((dom.scrollHeight - dom.clientHeight) > 2) {
            updateShowFoldArrow(true);
        }
    }, [messages, children, _limitLine]);

    return useMemo(() => {
        if (!isArray(messages, true) && !children) return null;
        return <div ref={warnRef} style={{
            height: fold ? lineHeight * _limitLine + 'rem' : 'auto',
            'WebkitLineClamp': _limitLine,
            marginTop: marginTop + 'rem'
        }} className={`cbkfe-warn ${className} ${fold ? 'cbkfe-warn--fold' : ''}`}>
            {
                children
                    ? children
                    : messages.map((msg, index) => <div key={index} className="cbkfe-warn__item" >
                        <img className="cbkfe-warn__icon" src="https://static.caibeike.com/i/625c9fa6aa59c588841dce473180df13-uzAhnh" />
                        {msg}
                    </div>)
            }
            {showFoldArrow && <i style={{ lineHeight: lineHeight + 'rem' }} onClick={(() => setFold(!fold))} className={`cbkfe-warn__foldIcon ${!fold ? 'cbkfe-warn__foldIcon--packup' : ''} iconfont icon--arrow--down`} />}
        </div>;
    }, [messages, _limitLine, showFoldArrow, fold, marginTop, className, children]);
}