import React, { useEffect, useState } from "react";
import { Form, Input, Button, Checkbox } from "antd";
import { Link } from "react-router-dom";
import axios from 'axios';
import educoderLogo from '../login/educoder.png';
import cookie from 'react-cookies';
import './LoginRegisterPage.scss';

function Login(props){
  const [message,setMessage] = useState();
  const [setting, setSetting] = useState(undefined);
  const {form, location} = props;
  const {getFieldDecorator } = form;
  const {search} = location;

  useEffect(()=>{
    //控制密码输入框在DOM不可见value
    clear;
    //获取第三方登录平台信息
    setSetting(JSON.parse(localStorage.getItem("chromesetting")));
  },[])
  
  // 登录表单提交
  function handleSubmit(){
    form.validateFields((err, values) => {
      if (!err) {
        axios.post(`/accounts/login.json`, {
          login: values.username,
          password: values.password,
          autologin: values.remember?1:0,
        }).then((response) => {
          if (!response.data.login) {
            response.data.status === -2 ? setMessage(response.data.message) : setMessage("错误的账号或密码");
          } else {
            //判断用户是否选择【下次自动登录】
            cookie.save('autologin',values.remember);
            const searchParams = new URLSearchParams(search.substring(1));
            const goPage = searchParams.get("go_page");
            //意见反馈
            window.location.href = goPage ? goPage : `/${response.data.login}`
          }
        }).catch((error) => {
          console.log('error',error);
        })
      }
    });
  }

  //校验用户名
  function comfirmWrite(rule, value, callback, index){
    setMessage(undefined);
    value ? callback():index === 1? callback("请输入邮箱地址或用户名登录"):callback("请输入登录密码");
  }

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

  return(
    <div>
      <div className="right_cont login_content">
        <div className="login_register_head">
          <span>欢迎登录 GitLink</span>
          <span className="link_span">没有账号？<Link to={`/register`}>去注册</Link></span>
        </div>
        <p className = {message?"message active":"message"}>{message}</p>
        <Form className="login-form">
          <Form.Item>
            {getFieldDecorator('username',{
              rules:[
                {
                  validator: (rule, value, callback) => { comfirmWrite(rule, value, callback, 1) }
                }
              ],
              validateTrigger:"onBlur",
            })(<Input className="account" placeholder="请输入邮箱地址/用户名"/>)}
          </Form.Item>

          <Form.Item>
            {getFieldDecorator('password', {
              rules: [
                {
                  validator: (rule, value, callback) => { comfirmWrite(rule, value, callback, 2) }
                }
              ],
              validateTrigger:"onBlur",
            })(
              <Input.Password className="psd" placeholder="请输入登录密码" onBlur={clear} onChange={clear}/>,
            )}
          </Form.Item>

          <div className="login_register_head login">
            <Form.Item>
              {getFieldDecorator('remember', {
                valuePropName: 'checked',
                initialValue: cookie.load('autologin'),
              })(<Checkbox>下次自动登录</Checkbox>)}
            </Form.Item>
            <Link to="/resetPassword" className="goResetPsdBut">忘记密码？</Link>
          </div>
          <Button type="primary" htmlType="submit" onClick={handleSubmit} className="login_register_cofBut">登录</Button>
        </Form>

        {
          setting && setting.third_party && setting.third_party.length > 0 ?
          <p className="quick_logon">
            <p className="quick_logon_p"></p>
            <span className={"startlogin"}>&nbsp;快速登录&nbsp;</span>
            {setting.third_party.map((item,key)=>{
              return(
                <a href={`${item.url}`}>
                  <img src={item.name === "educoder" ? educoderLogo : ""} width="46px" alt={`${item.name}登录`} />
                </a>
              )
            })
            }
          </p>
          :"" 
        }
      </div>
    </div>
  )

}
export default Form.create({ name: 'login' })(Login);