import { ArrowLeftOutlined } from '@ant-design/icons';
import { message, Form, Button } from 'antd';
import React, { useState, useEffect, useCallback } from 'react';
import { connect, Dispatch, history } from 'umi';
import { StateType } from '@/models/login';
import { LoginParamsType, getCaptcha, ValidateCaptcha } from '@/services/login';
import { ConnectState } from '@/models/connect';
import styles from './style.less';

interface LoginProps {
  dispatch: Dispatch;
  userLogin: StateType;
  submitting?: boolean;
}

const Login: React.FC<LoginProps> = (props) => {
  const { userLogin = {}, submitting, dispatch } = props;
  const { status, type: loginType } = userLogin;

  const [userName, setUsername] = useState('');
  const [forgetflag, setForgetFlag] = useState(false);

  const [count, setCount] = useState<number>(60);
  const [timing, setTiming] = useState(false);

  // 提交按钮
  const handleSubmit = async (values: LoginParamsType) => {
    console.log(values);
    if (forgetflag) {
      if (!values.userName || !values.code) {
        message.error('The mailbox or verification code cannot be empty!!!');
        return;
      }
      console.log('校验验证码！');
      const res = await ValidateCaptcha({ account: values.userName, code: values.code });
      console.log(res);

      if (res.error_code === '0000') {
        console.log('通过跳转到修改密码页面');
        dispatch({
          type: 'login/goResetPwd',
          payload: userName,
        });
      } else {
        message.error('MemberCode!');
      }
    } else {
      if (values.userName && values.password) {
        dispatch({
          type: 'login/login',
          payload: { ...values },
        });
      } else {
        message.error('The username or password cannot be empty!');
      }
    }
  };

  // 用户名
  const usernameHandle = (e: any) => {
    setUsername(e.target.value);
  };

  // 登录
  const returnHandle = (e: any) => {
    history.push('/user/login');
  };
  // 忘记密码
  const gotoForgetHandle = (e: any) => {
    history.push('/user/forget');
  };

  const handleSend = (e: any) => {
    if (timing) return;
    if (
      userName !== '' &&
      /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(userName)
    ) {
      console.log('邮箱正确!');
      onGetCaptcha(userName);
    } else {
      message.warning('Please enter the correct email address!');
    }
  };

  // 监听路由
  useEffect(() => {
    if (location.pathname == '/user/forget') {
      setForgetFlag(true);
    } else {
      setForgetFlag(false);
    }
  }, [location.pathname]);

  // 获取验证码
  const onGetCaptcha = useCallback(async (email: string) => {
    // getFakeCaptcha
    // getCaptcha
    setTiming(true);
    const result = await getCaptcha({ account: email });
    console.log(result);
    if (result.error_code === '0000') {
      message.success('Has Been Sent!');
    }
  }, []);

  useEffect(() => {
    console.log('计算秒数');
    let interval: number = 0;
    console.log(timing);
    if (timing) {
      interval = window.setInterval(() => {
        setCount((preSecond) => {
          if (preSecond <= 1) {
            setTiming(false);
            clearInterval(interval);
            // 重置秒数
            return 60;
          }
          return preSecond - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [timing]);

  return (
    <div>
      {forgetflag ? (
        <div style={{ position: 'absolute', top: -50, cursor: 'pointer' }} onClick={returnHandle}>
          <ArrowLeftOutlined style={{ fontSize: '28px' }} />
        </div>
      ) : (
        <div />
      )}
      <Form onFinish={handleSubmit}>
        <div className={styles.box1}>
          {forgetflag ? 'Please enter email address' : 'Account Name'}
        </div>
        <Form.Item name="userName" initialValue={userName || ''}>
          <input className={styles.input} onChange={usernameHandle} />
        </Form.Item>
        <div className={styles.box1}>
          {forgetflag ? 'Please enter a verification code' : 'Password'}
        </div>
        {forgetflag ? (
          <div className={styles.box2}>
            <Form.Item name="code" initialValue="">
              <input className={styles.input5} />
            </Form.Item>
            <div className={styles.button2} style={{ float: 'right' }} onClick={handleSend}>
              {timing ? `${count} 秒` : 'Send'}
            </div>
          </div>
        ) : (
          <div>
            <Form.Item name="password" initialValue="">
              <input className={styles.input2} type="password" />
            </Form.Item>
            <div>
              <div className={styles.input3} onClick={gotoForgetHandle}>
                Forget Password
              </div>
              <div className={styles.input4}>
                {status === 'error' && loginType === 'account' && !submitting && (
                  <div>Wrong account or password</div>
                )}
              </div>
            </div>
          </div>
        )}
        <Form.Item>
          <Button
            style={{ width: 330, height: 50, fontSize: 20 }}
            type="primary"
            htmlType="submit"
            shape="round"
          >
            {forgetflag ? 'Next' : 'Submit'}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default connect(({ login, loading }: ConnectState) => {
  return {
    userLogin: login,
    submitting: loading.effects['login/login'],
  };
})(Login);
