/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-05-16 10:57:51
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-06-07 17:17:38
 * @FilePath: /BudgetManaSystem/src/components/ResizableContainer/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState, useCallback, useEffect, useRef } from 'react';
import './style.less';

interface ResizableContainerProps {
    width?: number;
    minWidth?: number;
    maxWidth?: number;
    height?:string;
}

const ResizableContainer: React.FC<React.PropsWithChildren<ResizableContainerProps>> = ({
    width = 250,
    minWidth = 100,
    maxWidth = 800,
    height = '800px',
    children,
}) => {
    const [containerWidth, setContainerWidth] = useState(width);
    const isResizing = useRef(false);

    const handleMouseMove = useCallback((e: MouseEvent) => {
        if (isResizing.current) {
            const newWidth = Math.min(Math.max(e.clientX, minWidth), maxWidth);
            setContainerWidth(newWidth);
        }
    }, [minWidth, maxWidth]);

    const handleMouseUp = useCallback(() => {
        isResizing.current = false;
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
        document.body.style.userSelect = 'auto'; // 恢复文本选择
    }, [handleMouseMove]);

    const handleMouseDown = useCallback(() => {
        isResizing.current = true;
        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);
        document.body.style.userSelect = 'none'; // 禁用文本选择
    }, [handleMouseMove, handleMouseUp]);

    useEffect(() => {
        return () => {
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        };
    }, [handleMouseMove, handleMouseUp]);

    useEffect(() => {
        setContainerWidth(width);
    }, [width]);

    return (
        <div className="ResizableContainer">
            <div className="resizable" style={{ width: `${containerWidth}px`, height: `${height}` }}>
                {children}
            </div>
            <div className="resizer" onMouseDown={handleMouseDown} />
        </div>
    );
};

export default ResizableContainer;
