import { FC, useEffect, useRef, useState } from 'react';
import { history, useLocation, useParams } from "umi";
import styles from './index.less';
import { Input, Modal, message } from 'antd';
import ButtonComp from '@/components/ButtonComp';

interface PageProps { }

const CoreSystemEntrance: FC<PageProps> = ({ }) => {
  const urlParams = useParams();
  const inputRef = useRef(null);
  const location = useLocation()
  
  const [accessPermissions, setAccessPermissions] = useState<boolean>(false);
  const [visibility, setVisibility] = useState<boolean>(false);
  const [key, setKey] = useState<string>('一');
  const [pin, setPin] = useState<any>('');

  let sysInfo = localStorage.getItem(`${urlParams?.fileType}`);
  let info = sysInfo ? JSON.parse(sysInfo) : null;

  useEffect(() => {
    if (info) {
      // 获取选中安装的内容
      let installArr: string[] = []
      info.installExe.forEach((e: any) => {
        if (e.select) installArr.push(e.name)
      })

      if (!needInstall(installArr) && info?.powerOn && info?.restartService) {
        setAccessPermissions(true)
        localStorage.setItem(`${urlParams?.fileType}`, JSON.stringify({ ...info, accessPermissions: true }))
      } else {
        setAccessPermissions(false)
      }
    }


    function handleKeyPress(e: any) {
      if (e.key === 'Enter') {
        setVisibility(true)
      }
    }

    // 添加事件监听器
    document.addEventListener('keydown', handleKeyPress);

    // 清除事件监听器
    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, [])

  // 检查需要安装的内容
  const needInstall = (installArr: string | any[]) => {
    let res = false
    let names = ['密码资源输入输出设备驱动', '一体化密码机驱动安装程序', '一体化密码机管理软件']

    for (let i = 0; i < names.length; i++) {
      if (!installArr.includes(names[i])) {
        res = true;
        break;
      }
    }
    return res
  }

  const initData = () => {
    setVisibility(false);
    setKey('一');
    setPin('')
  }

  const submit = () => {
    if (key == '一' && pin == 'admin') {
      setKey('二');
      setPin('')
      setVisibility(false);
      setTimeout(() => { setVisibility(true) }, 300)
    } else if (key == '二' && pin == 'test') {
      initData()
      // 记录登陆成功状态
      localStorage.setItem(`${urlParams?.fileType}`, JSON.stringify({ ...info, pingLoginStatus: true, layoutInfo: null }))
      
      // 登录成功进入系统
      history.push(`/registerManage/deviceRegister/${urlParams?.fileType}${location?.search}`)
      setVisibility(false);
    } else {
      message.error('PIN码错误，请重新输入')
    }
  }

  return (
    <>
      {
        accessPermissions ?
          <div className={styles.entrance}>
            <div className={styles.text_warp}>
              <div>总参谋部</div>
              <div>一体化对称密码管理系统</div>
              <div>总参谋部密码管理中心</div>
            </div>

            <div className={styles.prompt}>请插入电子钥匙...</div>

            {/* 登录弹窗 */}
            <Modal
              title="用户登录"
              open={visibility}
              centered
              width={550}
              onCancel={() => setVisibility(false)}
              footer={null}
              maskClosable={false}
              afterOpenChange={() => {
                inputRef.current?.focus();
              }}
            >
              <div className={styles.login_warp}>
                <div className={styles.imges}></div>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <div style={{ width: 120, marginRight: 16 }}>请输入PIN码</div>
                    <Input ref={inputRef}  placeholder="请输入PIN码" value={pin} onChange={(e) => setPin(e.target.value)} onPressEnter={() => submit()} />
                  </div>
                  <div className='mt20'>提示信息：请插入第{key}个钥匙并输入PIN码</div>
                </div>
              </div>

              <div className='flex_jE mt20'>
                <ButtonComp style={{ marginRight: 20 }} text={'确定'} onClick={() => submit()} />
                <ButtonComp type="cancel" text={'退出'} onClick={() => initData()} />
              </div>
            </Modal>
          </div>
          : <Modal
            title={'系统提示'}
            open={!accessPermissions}
            centered
            width={500}
            closeIcon={false}
            footer={null}
            maskClosable={false}
          >
            <div style={{ padding: '20px 0' }}>
              无法进入系统，请检查是否重启服务，或者其他遗漏未的步骤！
            </div>
          </Modal>
      }
    </>
  )
}

export default CoreSystemEntrance