import React, { useEffect, useState } from 'react';
import {
  withRouter
} from 'react-router-dom';
import './Login.less';
import { Input, Popover, message, Tabs, Button } from 'antd';
import CheckBeforeSendCode from '../../components/CheckBeforeSendCode';
import User from '@/common/js/user';
import WechatLogin from './WechatLogin'
import BaseService from "@/domains/basic-domain/baseService";
import axios from 'axios';
import _ from 'underscore';
import user from '@/common/js/user';
const { TabPane } = Tabs;


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);
  const [checkObject1, setCheckObject1] = useState({});

  useEffect(() => {
    const enterpriseId = getParameterByName("enterpriseId");
    const userId = getParameterByName("userId");
    const from = getParameterByName("from");
    const storeId = getParameterByName("storeId");
    if (storeId) {
      User.setCustomerStoreId(storeId);
    }
    if (from === 'customer' && enterpriseId && userId) {
      if (!user.getToken() || enterpriseId !== user.getEnterpriseId()) {
        getWXWorkLoginNoCheck(enterpriseId, userId);
      } else {
        window.RCHistory.push({
          pathname: `/switch-route`,
        })
      }
    } else {
      User.removeUserId();
      User.removeToken();
      User.removeEnterpriseId();
    }
  }, [])
  function getWXWorkLoginNoCheck(enterpriseId, userId) {
    const params = {
      appTermEnum: "XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN",
      enterpriseId,
      userId
    }
    BaseService.getWXWorkLoginNoCheck(params).then((res) => {
      User.setUserId(res.result.loginInfo.userId);
      User.setToken(res.result.loginInfo.xmToken);
      User.setEnterpriseId(res.result.enterpriseId);
      window.RCHistory.push({
        pathname: `/switch-route`,
      })
    })
  }
  async function checkAccount(code, callback = () => { }) {
    callback();
  }
  function checkSend(code) {
    if (!phone) {
      setPhoneError(true);
      setErrorMessage("请输入手机号");
      return;
    }
    if (phone.length != 11) {
      setPhoneError(true);
      setErrorMessage("请输入11位手机号")
      return;
    }
    !_.isEmpty(checkObject1) && checkObject1.reset();
    setOpenCheck1(true);
  }
  function handleSendSMSCode(checkData, userType) {
    if (waitStatus) return;
    let timer;
    const params = {
      phone: phone,
      sig: checkData.sig,
      sessionId: checkData.csessionid,
      token: checkData.token,
      scene: 'nc_login',
      serverType: "CLOUD_CLASS_LOGIN",
      appTermEnum: 'XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN'
    }
    BaseService.sendLoginAuthCode(params).then((res) => {
      if (!res.success) {
        setErrorMessage(res.message);
      } else {
        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 (!phone) {
      setPhoneError(true);
      setErrorMessage("请输入手机号");
      return;
    }
    if (phone.length != 11) {
      setPhoneError(true);
      setErrorMessage("请输入11位手机号")
      return;
    }
    if (!phoneverify) {
      setErrorMessage("请输入验证码");
      return;
    }
    const params = {
      phone,
      authCode: phoneverify,
      appTermEnum: "XIAOMAI_CLOUD_CLASS_PC_WEB_ADMIN"
    }
    BaseService.login(params).then((res) => {
      if (!res.success) {
        setErrorMessage(res.message);
      } else {
        User.setUserId(res.result.userId);
        User.setToken(res.result.xmToken);
        window.RCHistory.push({
          pathname: `/switch-route`,
        })
      }
    })
  }

  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">
              <Tabs defaultActiveKey="1">
                <TabPane tab="企业微信登录" key="1">
                  <WechatLogin></WechatLogin>
                </TabPane>
                <TabPane tab="手机号登录" key="2">
                  <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}
                          maxLength={4}
                          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) => {
                                setCheckObject1(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">
                          <span id='loginIn' onClick={() => { handleSubmit() }} >登录</span>
                        </div>
                      </div>
                    </div>
                  </div>

                </TabPane>

              </Tabs>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default withRouter(Login);
