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

function ResetPassword(props) {
  const {form } = props;
  const {getFieldDecorator } = form;
  const [emailStr, setEmailStr] = 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);
  //用于限制表单提交时会再次调用check.json接口校验数据
  const [emailGo, setEmailGo] = useState(true);
  const seconds = useRef();
  let interval = undefined;
  //页面加载完自动聚焦到第一个输入框
  const inputEl = useRef(null);

  //重置密码表单提交
  function handleSubmit() {
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        axios.post(`/accounts/reset_password.json`, {
          login: values.email,
          password: values.psd,
          password_confirmation: values.psdComfirm,
          code: values.captcha,
        }).then((response) => {
          if (response.data.status === 0) {
            //重置密码成功，调用登录接口
            axios.post(`/accounts/login.json`, {
              login: values.email,
              password: values.psd
            }).then((login_response) => {
              if (!login_response.data.login) {
                setMess(login_response.data.message);
              } else {
                window.location.href = "/" + login_response.data.login;
              }
            }).catch((error) => {
              console.log('error',error);
            })
          } else {
            //设置邮箱内容-》不设置会被恢复成undefined,从而点击验证码失败
            setEmailStr(values.email);
            const message = response.data.message;
            message === "验证码不正确" ? form.setFields({captcha: {value:values.captcha,errors:[new Error('验证码错误，请重新输入')]}}) : setMess(message);
          }
        })
      }
    });
  }

  //判断邮箱是否注册
  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 && response.data.status === -1) {
        setEmailStr(value);
        setGetCaptchaBut(true);
        setEmailGo(false);
        callback();
      } else {
        setGetCaptchaBut(false);
        callback('此邮箱未注册');
      }
    }):callback();setEmailStr(undefined);
  }

  //确认密码
  function comfirmPassWord(rule, value, callback, index) {
    if ((index === 2 && value && form.getFieldValue('psd') && value !== form.getFieldValue('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 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 {
          //倒计时结束->可以获取验证码
          setGetCaptchaBut(true);
          setCountDown(false);
          clearInterval(interval);
        }
      }, 1000)

      //请求获取验证码接口
      axios.get(`/accounts/get_verification_code.json`, {
        params: {
          login: emailStr,
          type: 2,
          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("resetPassword_psd");
    const passwordComfirm = document.getElementById("resetPassword_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 ResetPassword_content">
        <div className="login_register_head">
          <span>找回密码</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('email', {
              rules: [
                {
                  type: 'email',
                  message: '请输入正确的邮箱格式',
                },
                {
                  required: true,
                  message: "请输入已注册的邮箱"
                },
                {
                  validator: (rule, value, callback) => { emailConfirm(rule, value, callback) }
                }
              ],
              validateTrigger: "onBlur",
              validateFirst: true,
            })(<Input ref={inputEl} className="account" placeholder="请输入已注册的邮箱" readOnly onFocus={()=>{document.getElementById("resetPassword_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("resetPassword_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('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="psd" placeholder="请输入新密码" onBlur={clear} onChange={clear} readOnly onFocus={()=>{document.getElementById("resetPassword_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("resetPassword_psdComfirm").removeAttribute("readOnly")}} />)}
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login_register_cofBut" onClick={handleSubmit}>重置密码并登录</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )

}
export default Form.create({ name: 'resetPassword' })(ResetPassword);