import React, { useEffect, useRef, useState } from "react";
import { Form, Input, Button, Checkbox, message } from "antd";
import { Link } from "react-router-dom";
import axios from 'axios';
import { setmiyah } from 'educoder';
import './LoginRegisterPage.scss';

function Register(props){
  const {form} = props;
  const {getFieldDecorator } = form;
  //用户输入的符合规则的邮箱（用于获取验证码）
  const [emailStr, setEmailStr] = useState(undefined);
  //用户输入的符合规则的用户名，用于当用户输入符合规则的用户名之后再更改又去触发check.json接口
  const [loginStr, setLoginStr] = useState(undefined);
  const [secondsStr, setSecondsStr] = useState(60);
  const [countDown, setCountDown] = useState(false);
  const [getCaptchaBut, setGetCaptchaBut] = useState(false);
  const [mess, setMess] = useState(undefined);
  const [tipVisable, setTipVisable] = useState(false);
  //用于表单提交时会再次校验数据
  const [userNameGo, setUserNameGo] = useState(true);
  const [emailGo, setEmailGo] = useState(true);
  const seconds = useRef();
  let interval = undefined;
  //页面加载完自动聚焦到第一个输入框
  const inputEl = useRef(null);

  //注册表单提交
  function handleSubmit(){
    form.validateFields((err, values) => {
      if (!err) {
        values.agreement && axios.post(`/accounts/register.json`, {
          login: values.email,
          namespace: values.register_username,
          password: values.register_psd,
          password_confirmation: values.psdComfirm,
          code: values.captcha
        }).then((response)=>{
          if(response.data && response.data.status === -6){
            //验证码不正确
            form.setFields({captcha: {value:values.captcha,errors:[new Error('验证码错误，请重新输入')]}});
            //设置邮箱内容-》不设置会被恢复成undefined,从而点击验证码失败
            setEmailStr(values.email);
          }else if(response.data && response.data.status === 0){
            //注册成功，页面跳转即可，注册后登录流程forge处理了
            window.location.href = "/"+values.register_username;
          } else {
            setEmailStr(values.email);
            setMess(response.data.message);
          }
        })
      }
    });
  }
  
  //判断用户名（username）是否注册
  function usernameConfirm(rule, value, callback){
    setUserNameGo(true);
    value && (userNameGo || value !== loginStr) ? axios.post(`/accounts/check.json`, {
      value: value,
      type: 1
    }).then(response => {
      if (response.data.status === -1) {
        callback('该名称已经被使用');
      } else {
        setLoginStr(value);
        setUserNameGo(false);
        callback();
      }
    }):callback();setLoginStr(undefined);
  }

  //判断邮箱是否注册
  function emailConfirm(rule, value, callback) {
    setEmailGo(true);
    value && (emailGo || value !== emailStr) ? axios.post(`/accounts/check.json`, {
      value: value,
      type: 2
    }).then(response => {
      if (response.data.status === -1) {
        setGetCaptchaBut(false);
        callback('该邮箱已被注册');
      } else {
        setEmailStr(value);
        setGetCaptchaBut(true);
        setEmailGo(false);
        callback();
      }
    }):callback();setEmailStr(undefined);
  }

  //确认密码
  function comfirmPassWord(rule, value, callback, index) {
    if ((index === 2 && value && form.getFieldValue('register_psd') && value !== form.getFieldValue('register_psd')) || (index === 1 && value && form.getFieldValue('psdComfirm') && value !== form.getFieldValue('psdComfirm'))) {
      if(index===1){
        form.setFields({psdComfirm: {value:form.getFieldValue('psdComfirm'),errors:[new Error('密码不一致，请重新输入')]}});
        callback();
      }else{
        callback('密码不一致，请重新输入');
      }
    } else {
      callback();
    }
  }

  //检查密码是否符合格式
  function checkPassWord(rule, value, callback){
    if(!value){
      setTipVisable(true);
      callback('请输入登录密码');
    }else if(/(?!.*\s)(?!^[\u4e00-\u9fa5]+$)^.{8,16}$/.test(value)){
      callback()
    }else{
      setTipVisable(true);
      if(value.length<8 || value.length>16){
        callback('密码长度为8-16个字符');
      }else{
        callback('密码不能使用空格');
      }
    }
  }

  //确认勾选服务
  function comfirmRead(rule, value, callback){
    if(value){
      callback();
    }else{
      callback("请阅读并接受我们的服务条款");
    }
  }

  //获取验证码
  function getCaptcha() {
    setMess(undefined);
    if (emailStr) {
      // 倒计时开始
      setCountDown(true);
      setGetCaptchaBut(false);
      seconds.current = 60;
      setSecondsStr(60);
      !interval && clearInterval(interval);
      interval = setInterval(() => {
        if (seconds.current > 1) {
          let oldSeconds = seconds.current;
          seconds.current = oldSeconds - 1;
          setSecondsStr(oldSeconds - 1);
        } else {
          clearInterval(interval);
          //倒计时结束->可以获取验证码
          setGetCaptchaBut(true);
          setCountDown(false);
        }
      }, 1000)

      //请求获取验证码接口
      axios.get(`/accounts/get_verification_code.json`, {
        params: {
          login: emailStr,
          type: 1,
          smscode: setmiyah(emailStr),
        }
      }).then(response => {
        if (response.data && response.data.status === 0) {
          //验证码发送成功
          let email = emailStr.substring(emailStr.indexOf("@")+1);
          message.success({content:<span>验证码已发送，请注意查收。<a href={`https://mail.${email}`} target="_blank">前往邮箱</a></span>});
        } else {
          //验证码发送失败,获取验证码按钮变灰并且文案变回【获取验证码】
          setGetCaptchaBut(false);
          setCountDown(false);
          clearInterval(interval);
          setMess(response.data.message);
        }
      })
    }
  }

  //清除密码框的value属性->DOM看不见密码值
  function clear(){
    const password = document.getElementById("register_register_psd");
    const passwordComfirm = document.getElementById("register_psdComfirm");
    if(password && password.type==="password"){
      setTimeout(()=>{
        password.removeAttribute('value');
      },0)
    }
    if(passwordComfirm && passwordComfirm.type==="password"){
      setTimeout(()=>{
        passwordComfirm.removeAttribute('value');
      },0)
    }
  }

  useEffect(() => {
    inputEl.current.focus();
    clear;
  }, [])

  return(
    <div>
      <div className="right_cont Register_content">
        <div className="login_register_head">
          <span>欢迎注册 GitLink</span>
          <span className="link_span">已有账号，<Link to={`/login`}>立即登录</Link></span>
        </div>
        <p className={mess ? "message active" : "message"}>{mess}</p>
        <Form className="login-form">
          <Form.Item>
            {getFieldDecorator('register_username',{
              rules:[
                {
                  required:true,
                  message:"请输入用户名"
                },
                {
                  pattern: /^[a-zA-Z]/,
                  message: "用户名必须以字母开头"
                },
                {
                  pattern: /[a-zA-Z0-9]$/,
                  message: "用户名只能使用英文字母和数字"
                },
                {
                  min: 4,
                  max: 15,
                  message: "用户名长度为4到15个字符"
                },
                {
                  validator: (rule, value, callback) => { usernameConfirm(rule, value, callback) }
                }
              ],
              validateTrigger:"onBlur",
              validateFirst: true,
            })(<Input ref={inputEl} className="account" placeholder="请输入4-15位用户名，以字母开头，只能使用字母和数字" readOnly onFocus={()=>{document.getElementById("register_register_username").removeAttribute("readOnly")}}/>)}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator('email',{
              rules:[
                {
                  type: 'email',
                  message: '请输入正确的邮箱格式',
                },
                {
                  required:true,
                  message:"请输入邮箱地址"
                },
                {
                  validator: (rule, value, callback) => { emailConfirm(rule, value, callback) }
                }
              ],
              validateTrigger:"onBlur",
              validateFirst: true,
            })(<Input className="email" placeholder="请输入邮箱地址" readOnly onFocus={()=>{document.getElementById("register_email").removeAttribute("readOnly")}} />)}
          </Form.Item>

          
          <Form.Item>
            <div className="login_register_head">
              {getFieldDecorator('captcha', {
                rules: [{
                  required: true,
                  message: "请输入验证码"
                }],
                validateTrigger: "onBlur",
              })(
                <Input className="captcha" placeholder="请输入验证码" readOnly onFocus={()=>{document.getElementById("register_captcha").removeAttribute("readOnly")}} />
              )}
              <Button className={getCaptchaBut ? 'codeBut':'codeBut disable'} disabled={!getCaptchaBut} onClick={getCaptcha}>{getCaptchaBut || (!getCaptchaBut && !countDown)?"获取验证码":`重发(${secondsStr}s)`}</Button>
            </div>
          </Form.Item>
          
          <Form.Item>
            {getFieldDecorator('register_psd',{
              rules:[
                {
                  validator: (rule, value, callback) => { comfirmPassWord(rule, value, callback, 1) }
                },
                {
                  validator: (rule, value, callback) => { checkPassWord(rule, value, callback) }
                }
              ],
              validateTrigger:"onBlur",
              validateFirst: true,
            })(<Input.Password className="register_psd" placeholder="请输入登录密码" onBlur={clear}  onChange={clear} readOnly onFocus={()=>{document.getElementById("register_register_psd").removeAttribute("readOnly")}}/>)}
          </Form.Item>
          <span className="password_tips" style={{display:tipVisable?"none":"block"}}>请输入8-16位密码，区分大小写、不能使用空格</span>

          <Form.Item>
            {getFieldDecorator('psdComfirm', {
              rules: [
                {
                  required: true,
                  message: "请确认登录密码"
                },
                {
                  validator: (rule, value, callback) => { comfirmPassWord(rule, value, callback, 2) }
                }
              ],
              validateTrigger: "onBlur",
              validateFirst: true,
            })(<Input.Password className="psdComfirm" placeholder="请确认登录密码" onBlur={clear} onChange={clear} readOnly onFocus={()=>{document.getElementById("register_psdComfirm").removeAttribute("readOnly")}}/>)}
          </Form.Item>

          
          <Form.Item className="register_last_form">
            {getFieldDecorator('agreement', {
              valuePropName: 'checked',
              initialValue: false,
              rules: [
                {
                  validator: (rule, value, callback) => { comfirmRead(rule, value, callback) }
                }
              ],
            })(<Checkbox>我已阅读并接受<a className="login-form-forgot" href="https://forum.trustie.net/forums/5029/detail" target="_blank">《GitLink服务协议条款》</a></Checkbox>)}
          </Form.Item>
          <Button type="primary" htmlType="submit" className="login_register_cofBut" onClick={handleSubmit}>注册</Button>
        </Form>
      </div>
    </div>
  )
}
export default Form.create({ name: 'register' })(Register);