import React, { useEffect, useRef, useState} from 'react';
import {
  withRouter
} from 'react-router-dom';
import './Login.less';
import {Input,Popover,message} from 'antd';
import CheckBeforeSendCode from '../../components/CheckBeforeSendCode';
import Service from "../../common/js/service"
import User from '@/common/js/user';
import axios  from 'axios';
function Login(props) {
  const [phone, setPhone] = useState(''); // 登录手机号
  const [phoneverify, setPhoneverify] = useState(''); // 密码登录验证码
  const [openCheck1, setOpenCheck1] = useState(false);
  const [checking1, setChecking1] = useState(false);
  const [codeText, setCodeText] = useState('获取验证码'); // 验证码提示语
  const [waitStatus, setWaitStatus] = useState(false); // 验证码是否在倒计时
  const [errorMessage,setErrorMessage] = useState('');
  const [phoneError,setPhoneError] = useState(false);
  useEffect(() => {
  
  }, [])
  
  async function checkAccount(code, callback = () => { }) {
    callback();
  }
  function checkSend(code) {
    if (!phone) {
      setPhoneError(true);
      setErrorMessage("请输入手机号");
      return;
    }
    if (phone.length != 11) {
      setPhoneError(true);
      setErrorMessage("请输入11位手机号")
      return;
    }
    setOpenCheck1(true);
  }
  function handleSendSMSCode(checkData, userType) {
    if (waitStatus) return;
    let timer;
    // timeSub(60);
    // setChecking1(true)
    const params = {
      phone: phone,
      sig: checkData.sig,
      sessionId: checkData.csessionid,
      token: checkData.token,
      scene: 'nc_login',
    }
    axios.post('https://dev-heimdall.xiaomai5.com/hades/anon/store/sendLoginAuthCode', params).then((res) => {
      console.log('111',res.data.success);
      if (!res.data.success) {
        setErrorMessage(res.data.message);
      } else {
        console.log('111');
        timeSub(60);
        setChecking1(true)
      }
    })
    function timeSub(waitTime, unit) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (waitTime == 0) {
          setCodeText('发送验证码')
          setChecking1(false)
          setWaitStatus(false)
          clearTimeout(timer);
        } else {
          setCodeText(`${waitTime}秒后重发`)
          setWaitStatus(true)
          timeSub(--waitTime, 1000);
        }
      }, unit || 0);
    }
  }

  function handleSubmit() {
    if(!phoneverify){
      setErrorMessage("请输入验证码");
      return;
    }
    const params = {
      phone,
      authCode:phoneverify
    }
    axios.post('https://dev-heimdall.xiaomai5.com/hades/anon/store/login', params).then((res) => {
      const data = res.data;
      if (!data.success) {
        setErrorMessage(data.message);
      } else {
        User.setUserId(data.result.userId);
        User.setToken(data.result.xmToken);
        window.RCHistory.push({
          pathname: `/personal-info`,
        })
      }
    })
  }

  return (
    <div className="login-page" >
      <div className="login-main">
        <div className="left-banner">
          <div><img  src={require("../../common/images/logo.png")} alt="" style={{ width: 60,height:61}} /></div>
          <div className="name">小麦云课堂</div>
          <div className="desc">一键开启直播授课 让知识更有价值</div>
        </div>
        <div className="login-box">
            <div className="login">
              <div className="r">
                <div className="title">
                  手机号登录
                </div>
                <div className="login-form">
                  <div className="form">
                    <div className="username" style={{ marginBottom: 16 }}>
                      <Input
                        type="phone"
                        autoComplete="off"
                        name="account"
                        maxLength={11}
                        placeholder="手机号"
                        value={phone}
                        onChange={(e) => { setPhone(e.target.value) }}
                      />
                    </div>
                    <div className="error-message">
                      
                    </div>
                    <div className="phoneverify">
                      <Input
                        type="text"
                        id="phoneverify"
                        name="phoneverify"
                        placeholder="验证码"
                        autoComplete="off"
                        value={phoneverify}
                        onChange={(e) => { setPhoneverify(e.target.value) }}
                      />
                      <Popover
                          visible={openCheck1}
                          trigger="click"
                          title=""
                          content={<div>
                            <span style={{ fontSize: '12px', color: '#999', marginBottom: 8, display: 'block' }}>请完成安全验证</span>
                            <CheckBeforeSendCode
                              callback={(data, nc) => {
                                checkAccount(1, (userType) => {
                                  handleSendSMSCode(data, userType);
                                  setTimeout(() => {
                                    setOpenCheck1(false);
                                  }, 500)
                                })
                              }}
                            />
                          </div>}
                          onVisibleChange={(value) => {
                            if (!value) {
                              setOpenCheck1(false);
                            }
                          }}
                          placement="bottomRight"
                        >
                          <div
                            className="btn"
                            id="sendVerifyCode"
                            onClick={() => {
                              if (checking1) return;
                              checkSend(1)
                            }}
                          >{codeText}</div>
                        </Popover>
                    </div>
                    <div className="error-message">
                      {errorMessage}
                    </div>
                    <div className="submit">
                      <div className="btn">
                        <button id='loginIn'  onClick={ () => { handleSubmit() } }>登录</button>
                      </div>
                    </div>
                    {/* <div className="network-message">
                      <span className="icon iconfont">&#xe834;</span>网络不给力，请<span className="refresh">点击刷新</span>
                    </div> */}
                  </div>
                </div>
              </div>
            </div>
        </div>
      </div>
    </div>
  )
}

export default withRouter(Login);
