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

// 网络MMJ管理 --> 密码机遥毙
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 sending = () => {
    
    secretInit_sendCommand({type: 2}).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 style={{ padding: '0px 12px' }}>
              {lines.slice(0, currentLineIndex).map((line: string, index: number) => (
                <p key={line} style={{ paddingTop: index == 0 ? 20 : 10 }}>{line}</p>
              ))}
            </div>
          </div>
          <div className={styles.erroInfo}>注意：执行此操作后，设备需返厂修复！</div>
          <div className={styles.btn_warp}>
            <ButtonComp style={{ marginRight: 20 }} text={'发送命令'} onClick={() => sending()} />
            <ButtonComp type={'cancel'} text={'清空信息'} onClick={() => setVisibility(true)} />
          </div>
        </div>
      </ContentWarp>

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