import React, { FC, useEffect, useState } from 'react';
import styles from './index.less';
import { Input, Progress, message } from 'antd';
import { countType, sysType } from '@/utils/sysType';
import { useParams } from 'umi';
import DEV from '@/utils/env/dev';

interface PageProps {
  open: boolean;
  onCancel: (name?: string) => void;
  setInstallExe: (index: number, text: string) => void;
}

const CoreArea: FC<PageProps> = ({
  open = false,
  onCancel,
  setInstallExe
}) => {
  const [active, setActive] = useState(1);
  const [percentVal, setPercentVal] = useState(0);
  const [userName, setUserName] = useState('root');
  const [password, setPassword] = useState('');

  const [serverIp, setServerIp] = useState('127.0.0.1');
  const [serverPort, setServerPort] = useState('2222');
  const [localPort, setLocalPort] = useState('11110');

  const urlParams = useParams();

  useEffect(() => {
    if (open) {
      setActive(1)
      setPassword('')
      setServerIp('127.0.0.1')
    }
  }, [open])

  // 监听是否到安装进度条步骤
  useEffect(() => {
    if (active == 4) {
      const interval = setInterval(() => {
        setPercentVal((val) => {
          const randomStep = Math.round(Math.random() * (100 / 10));
          const newPercent = val + randomStep;

          if (newPercent >= 100) {
            clearInterval(interval);
            setValue()
            return 100;
          }

          return newPercent;
        });
      }, 500);

      return () => clearInterval(interval);
    }
  }, [active])

  // 设置安装步骤进度
  const setValue = () => {
    setActive((e) => { return e + 1 })
  }

  const getName = () => {
    return urlParams?.fileType == 'offLine' ? '离线版' : '在线版'
  }

  // 在指定的目录下安装快捷方式
  const installSuccess = async () => {
    try {
      const response = await fetch('http://localhost:3000/createShortcut', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        mode: "cors",
        body: JSON.stringify({
          folderPath: `${DEV.FILE_URL}/${getName()}/${countType[urlParams?.fileType]}`,
          shortcutName: '核心区客户端',
          shortcutURL: `${DEV.LOCAL_URL}/coreSystemEntrance/${urlParams?.fileType}?sysType=${encodeURIComponent(sysType[urlParams?.fileType] + 'hx')}`
        }),
      });
      const data = await response.text();
      setInstallExe(9, data)
      onCancel()
    } catch (error) {
      message.error(error); // 处理请求错误
    }
  }

  const verifyPassword = () => {
    if (userName.trim().length == 0) {
      message.error('请输入用户名！')
      return true;
    }

    if (password.trim().length == 0) {
      message.error('请输入密码！');
      return true;
    }

    let sysName = localStorage.getItem(`${urlParams?.fileType}`);
    if (sysName) {
      let info = JSON.parse(sysName)
      if (password != info.GBasePassword) {
        message.error('密码错误！');
        return true;
      }
    }
  }

  return <>
    {
      open &&
      <div className={styles.modalOverlay}>
        <div className={styles.modal} style={{ width: 500, height: 460 }}>
          <img src={require(`../../../assets/images/coreArea/${active}.png`)} width={500} height={460} />

          <div className={styles.close} onClick={() => {
            onCancel('核心区安装程序')
          }}></div>

          {[1, 2, 3].includes(active) && <div className={styles.title}>核心区客户端 安装程序</div>}
          {![1, 2, 3].includes(active) && <div className={styles.title1}>核心区客户端 安装程序</div>}

          {active == 1 && <div className={styles.pic1}>核心区客户端安装程序</div>}
          {active == 2 && <>
            <div className={styles.pic1} style={{ left: 10 }}>填写GBase账号信息</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 130, left: 16 }}>用户名</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 180, left: 27 }}>密码</div>
            <Input disabled value={userName} onChange={(e) => { setUserName(e.target.value) }} className={styles.input1} style={{ top: 121, left: 59, width: 325 }} />
            <Input value={password} onChange={(e) => { setPassword(e.target.value) }} className={styles.input2} style={{ top: 171, left: 59, width: 325 }} />
          </>}
          {active == 3 && <div className={styles.pic1} style={{ top: 166, left: 85 }}>核心区客户端</div>}
          {active == 5 && <div className={styles.pic1} style={{ top: 123, left: 85 }}>核心区客户端</div>}

          {active == 6 && <>
            <div className={styles.pic1} style={{ left: 15, top: 45 }}>填写GBase账号信息</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 130, left: 16 }}>服务器的ip地址</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 180, left: 39 }}>服务器端口</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 230, left: 50 }}>本地端口</div>
            <Input value={serverIp} onChange={(e) => { setServerIp(e.target.value) }} className={styles.input1} style={{ top: 121, left: 109, width: 325 }} />
            <Input disabled value={serverPort} onChange={(e) => { setServerPort(e.target.value) }} className={styles.input2} style={{ top: 171, left: 109, width: 325 }} />
            <Input disabled value={localPort} onChange={(e) => { setLocalPort(e.target.value) }} className={styles.input2} style={{ top: 221, left: 109, width: 325 }} />
            <div className={styles.pic1} style={{ fontSize: 12, top: 427, left: 265 }}>确定</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 427, left: 343 }}>取消</div>
            <div className={styles.pic1} style={{ fontSize: 12, top: 427, left: 420 }}>应用</div>
          </>}

          {[1, 2, 3].includes(active) && <div
            className={styles.net}
            onClick={() => {
              if (active == 2 && verifyPassword()) return
              setValue()
            }}>
          </div>}

          {active == 4 && <div className={styles.progress} style={{ background: '#fff', height: 15, width: 375, bottom: 222, left: 33, }}>
            <Progress percent={percentVal} steps={42} size={[7, 14]} strokeColor={'rgb(56, 158, 13)'} trailColor={'rgba(0,0,0,0)'} showInfo={false} />
          </div>}

          {[5, 6].includes(active) && <div
            className={styles.net}
            style={{ bottom: 17, right: active == 5 ? 27 : 187 }}
            onClick={() => {
              active == 5 ? setValue() : installSuccess()
            }}>
          </div>}
        </div>
      </div>
    }
  </>
};

export default CoreArea;
