/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2025-03-04 14:35:09
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-03-06 14:03:33
 * @FilePath: /KC-MiddlePlatform/src/components/intelligenceBot/AutoResizingTextarea.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useRef, useEffect } from 'react';

import './style.less';

interface AutoResizingTextareaProps {
  value: string;
  onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
  placeholder?: string;
  onKeyPress?: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void;
}

const AutoResizingTextarea: React.FC<AutoResizingTextareaProps> = ({ value, onChange, placeholder, onKeyPress }) => {
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const maxHeight = 150; // 设定最大高度，例如 150px

  const adjustHeight = () => {
    if (textareaRef.current) {
      // 重置高度，便于重新计算
      textareaRef.current.style.height = '28px';
      const newHeight = textareaRef.current.scrollHeight;
      if (newHeight < maxHeight) {
        textareaRef.current.style.height = newHeight + 'px';
        textareaRef.current.style.overflowY = 'hidden';
      } else {
        textareaRef.current.style.height = maxHeight + 'px';
        textareaRef.current.style.overflowY = 'auto';
      }
    }
  };

  useEffect(() => {
    adjustHeight();
  }, [value]);

  return (
    <textarea
      className="auto-resizing-textarea"
      ref={textareaRef}
      value={value}
      onChange={(e) => {
        onChange(e);
        adjustHeight();
      }}
      onKeyPress={onKeyPress}
      placeholder={placeholder}
      style={{ resize: 'none', outline: 'none', border: 'none !important', width: 430, height: 28, background: 'transparent' }} // 禁止手动拖拽调整大小
    />
  );
};

export default AutoResizingTextarea;
