import ContentWarp from '@/components/ContentWarp';
import styles from '../../index.less';
import ButtonComp from '@/components/ButtonComp';
import { useEffect, useRef, useState } from 'react';
import { getGlqInfo } from '@/services/gql';
import ClearInfoDialog from '@/components/ClearInfoDialog';
import SaveAs from '@/components/SaveAs';

// 网络GQL管理 --> 获取安全策略
export default function Page() {
  const [lines, setLines] = useState<any>([]);
  const [currentLineIndex, setCurrentLineIndex] = useState(0);
  const [visibility, setVisibility] = useState<boolean>(false);
  const outputRef: any = useRef(null);

  useEffect(() => {
    const timer = setInterval(() => {
      if (currentLineIndex < lines.length) {
        setCurrentLineIndex((prevIndex) => prevIndex + 1);
      } else {
        clearInterval(timer);
      }
    }, 300);

    if (outputRef.current.scrollHeight > 330) {
      outputRef.current.scrollTop = outputRef.current.scrollHeight;
    }

    return () => {
      clearInterval(timer); // 组件卸载时清除定时器
    };
  }, [currentLineIndex, lines.length]);

  const statusQuery = () => {
    getGlqInfo({type: 3}).then((res) => {
      if (res?.result == "success") {
        setLines([
          ...lines,
          '发送命令成功',
          `获取安全策略`,
          `正在获取安全策略中...`,
          `获取安全策略完成`
        ])
      } else {
        setLines([`${res?.errorMsg}`])
      }
    })
  }

  return (
    <div className={styles.params_warp}>
      <ContentWarp text={'获取安全策略'}>
        <div className='pd20'>被控端报文过滤策略配置情况</div>
        <div className='line'></div>
        <div className='pd20 pb100'>
          <div ref={outputRef} className={styles.html_con}>
            <div id='messageInfo' style={{ padding: '0px 12px' }} key={currentLineIndex}>
              {lines.slice(0, currentLineIndex).map((line: string, index: number) => (
                <p key={index} style={{ paddingTop: index == 0 ? 20 : 10 }}>{line}</p>
              ))}
            </div>
          </div>
          <div className={styles.btn_warp}>
            <ButtonComp style={{ marginRight: 20 }} text={'发送命令'} onClick={() => { statusQuery() }} />
            <SaveAs style={{ marginRight: 20}} fileName='获取安全策略' domId='messageInfo'/>
            <ButtonComp type={'cancel'} disabled={lines.length == 0} text={'清空信息'} onClick={() => setVisibility(true)} />
          </div>
        </div>
      </ContentWarp>

      <ClearInfoDialog
        visibility={visibility}
        onCancel={() => setVisibility(false)}
        onOk={() => {
          setLines([]);
          setCurrentLineIndex(0);
          setVisibility(false);
        }}>
        <div>确定清空信息吗？</div>
      </ClearInfoDialog>
    </div>
  );
}