import React, { useEffect, useRef, useState } from 'react';
import qs from 'qs';

import {
  withRouter
} from 'react-router-dom';
import './Login.less';
import md5 from 'blueimp-md5';
import { message, Row, Col, Tabs, Input, Button, Popover , Select } from 'antd';

import originAxios from 'axios';

import CheckBeforeSendCode from '../../components/CheckBeforeSendCode';

const {Option} = Select;
const {TabPane} = Tabs;
const GH = require('../../images/guohui.png')

function Login(props) {

  const initApi = LS.get('DRURL') || '';
  const [api, setApi] = useState(initApi);
  const [drList, setDrList] = useState([]); // 线路列表
  const [loginStyle, setLoginStyle] = useState('passwordLogin');// 登录方式
  const [showPassword, setShowPassword] = useState(false);// 显示密码

  const [phone, setPhone] = useState(''); // 登录手机号
  const [password, setPwd] = useState(''); // 密码
  const [phoneverify, setPhoneverify] = useState(''); // 密码登录验证码
  const [certificate, setCertificate] = useState(''); // 语音电话参数

  const [instName, setInstName] = useState(''); // 免费试用机构名字
  const [regPhone, setRegPhone] = useState(''); // 免费试用手机号
  const [code, setCode] = useState(''); // 免费试用验证码

  const [btnText, setBtnText] = useState('登录'); // 登录按钮文本
  const [btnDisabled, setBtnDisabled] = useState(false); // 登录按钮禁用状态

  const [modalVisible, setModalVisible] = useState(false); // 注册弹窗可见状态
  const [voiceCodeTip, setVoiceCodeTip] = useState(false); // 语音验证码提示状态

  const [codeText, setCodeText] = useState('获取验证码'); // 验证码提示语
  const [waitStatus, setWaitStatus] = useState(false); // 验证码是否在倒计时

  const [regBtnText, setRegBtnText] = useState('提交'); // 注册弹窗按钮文本
  const [regBtnDisabled, setRegBtnDisabled] = useState(false) // 注册按钮禁用状态
  const [regCodeText, setRegCodeText] = useState('获取验证码'); // 注册弹窗文本

  const [userType, setUserType] = useState('B');  // 账号类型 B or CRM_INST

  const [regWaitStatus, setRegWaitStatus] = useState(false); // 验证码是否在倒计时
  const [regVoiceCodeTip, setRegVoiceCodeTip] = useState(false); // 语音验证码提示状态
  const [openCheck1, setOpenCheck1] = useState(false);
  const [openCheck2, setOpenCheck2] = useState(false);
  const [openCheck3, setOpenCheck3] = useState(false);
  const [openCheck4, setOpenCheck4] = useState(false);

  const [checking1, setChecking1] = useState(false);
  const [checking3, setChecking3] = useState(false);

  const [checkObject1, setCheckObject1] = useState({});
  const [checkObject2, setCheckObject2] = useState({});
  const [checkObject3, setCheckObject3] = useState({});
  const [checkObject4, setCheckObject4] = useState({});

  useEffect(() => {
    getDrList();
    window.WEBTRACING('Web_B_LoginPage_View', '曝光事件_首页_WebB_打开登录页');


    // 默认
    const sear = props.location.search
    if(sear){
      const urlParams = qs.parse(props.location.search.substr(1))
      if(urlParams.tab=== "code"){
        setLoginStyle("phoneverifyLogin")
      }

      if(urlParams.phone){
        setPhone(urlParams.phone)
      }
    }
  }, [])


  function getDrList() {
    originAxios.get('https://res.xiaomai5.com/devops/xmRouteConfig/xmRouteB.conf?spm=5176.8466032.0.dopenurl.218a1450V7oSvA&file=xmRouteB.conf').then((res) => {
      setDrList(res.data.routes);
    }).catch(() => { })
    document.title = "机构管理端登录｜小麦助教";
  }

  async function handleLogin(e) {
    const ifVerifyLogin = (loginStyle == 'phoneverifyLogin');
    e.preventDefault();
    const data = {
      account: phone,
      pwd: password,
      phoneverify
    };
    if (!data.account) {
      setBtnText('请输入手机号');
      setBtnDisabled(true);
      setTimeout(function () {
        setBtnText('登录');
        setBtnDisabled(false);
      }, 1500);
      return;
    }
    if (data.account.length != 11) {
      message.warning('请输入11位长度手机号')
      return;
    }
    if (ifVerifyLogin) {
      if (!data.phoneverify) {
        setBtnText('无有效验证码，请先获取短信验证码');
        setBtnDisabled(true);
        setTimeout(function () {
          setBtnText('登录');
          setBtnDisabled(false);
        }, 1500);
        return;
      }
    } else if (!data.pwd) {
      setBtnText('请输入密码');
      setBtnDisabled(true);
      setTimeout(function () {
        setBtnText('登录');
        setBtnDisabled(false);
      }, 1500);
      return;
    }
    data.pwd = md5(data.pwd);

    const param = {
      accountNo: data.account,
      certificate: ifVerifyLogin ? data.phoneverify : data.pwd,
      appTerm: 'PC',
      loginType: ifVerifyLogin ? 'PHONE_AUTH_CODE' : 'PHONE_PWD'
    }

    setBtnText('登录中...');
    setBtnDisabled(true);
    setTimeout(() => {
      setBtnText('登录');
      setBtnDisabled(false);
    }, 3000);

    const option = {
      sync: true, noCache: true, userType, success: (res) => {
        if (typeof res === 'object') {
          if (res.code == '200' && !res.result.exists) {  // 非机构用户
            setRegPhone(data.account)
            setModalVisible(true)
            return
          }
          switch (res.code) {
            // 成功
            case "200":
              window.location.reload();
              window.WEBTRACING('Web_B_LoginPage_Loginin', '曝光事件_首页_WebB_登陆成功');
              localStorage.removeItem('xmsy');
              window.LS.set('isCrmInstAdmin', false);  // 机构后台账号
              var storageDate = window.LS.get('storageDate');
              if (storageDate != CONFIG.cacheUpdateTime) {
                const apis = localStorage.getItem('server-apis');
                // window.LS.clear();
                window.LS.set('storageDate', CONFIG.cacheUpdateTime);
                if (apis) {
                  localStorage.setItem('server-apis', apis)
                }
              }
              window.LS.set('token', res.result.xmToken);
              window.LS.set('uid', res.result.userId);
              window.LS.set('uPhone', /^\d{11}$/.test(data.account) ? data
                .account : '');
              window.LS.set('crmInstIds', JSON.stringify(res.result.crmInstIds));
              if (res.result.userType === 'CRM_INST') {
                window.LS.set('isCrmInstAdmin', true);  // 机构后台账号
                window.RCHistory.push({
                  pathname: `/campus_panel`,
                })
              } else if (res.result.isCenterAccount && process.env.DEPLOY_ENV !== 'beta') {
                window.LS.set('hasCenter', true);
                if (process.env.DEPLOY_ENV === 'dev1') {
                  location.href = `${location.origin  }/dev1/center/index.html${  drLink ? '?type=dr' : ''}`;
                } else if (process.env.DEPLOY_ENV === 'gray') {
                  location.href = `${location.origin  }/center/gray/index.html${  drLink ? '?type=dr' : ''}`;
                } else {
                  location.href = `${location.origin  }/center/index.html${  drLink ? '?type=dr' : ''}`;
                }

              } else {
                window.RCHistory.push({
                  pathname: `/`,
                })
              }
              break;
            // token非法
            case '404':
              break;
            // 手机号,密码错误
            case '500':
              setBtnText('手机号或密码错误');
              setBtnDisabled(true);
              setTimeout(function () {
                setBtnText('登录');
                setBtnDisabled(false);
              }, 1500);
              break;
            default:
              setBtnText(res.message);
              setBtnDisabled(true);
              setTimeout(function () {
                setBtnText('登录');
                setBtnDisabled(false);
              }, 1500);
              break;
          }
        }
      }
    }
    axios.postJSON('business/anon/b/login', param, option)
  }

  function handleSendSMSCode(checkData, userType) {
    if (waitStatus) return;
    const phoneLength = phone.trim().length;
    const params = {
      phone,
      sig: checkData.sig,
      sessionId: checkData.csessionid,
      token: checkData.token,
      scene: 'nc_login',
      serverType: 'B_LOGIN',
      sideType: 0,
    };
    if (userType === 'CRM_INST') {
      params.serverType = 'CRM_INST';
    };
    axios.postJSON('business/anon/sms/sendSmsCode', params, { reject: true }).then((res) => {
      if (!res.success) {
        message.warning(res.message);

      } else {
        timeSub(60);
        setChecking1(true)
        setCertificate(res.result);
      }
    })
    let timer;

    function timeSub(waitTime, unit) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (waitTime == 0) {
          setCodeText('发送验证码')
          setChecking1(false)
          setWaitStatus(false)
          clearTimeout(timer);
        } else {
          if (waitTime < 40) {
            setVoiceCodeTip(true)
          }
          setCodeText(`${waitTime  }秒后重发`)
          setWaitStatus(true)
          timeSub(--waitTime, 1000);
        }
      }, unit || 0);
    }
  }

  function handleSendVoiceCode(checkData, code) {
    let calledVoiceSend = false;
    const thePhone = code < 3 ? phone : regPhone;
    const phoneLength = thePhone.trim().length;
    if (isValidPhone(thePhone) && !calledVoiceSend) {
      calledVoiceSend = true;
      const params = {
        certificate,
        sig: checkData.sig,
        sessionId: checkData.csessionid,
        token: checkData.token,
        scene: 'nc_login',
      }
      axios.postJSON('business/anon/sms/bSendLoginVoiceCode', params, { reject: true }).then((res) => {
        if (!res.success) {
          message.warning(res.message);
          return;
        }
        message.success('验证码将以电话的形式通知到您，请注意接听');
        timeSub(60);

        let timer;

        function timeSub(waitTime, unit) {
          clearTimeout(timer);
          timer = setTimeout(function () {
            if (waitTime == 0) {
              calledVoiceSend = false;
              clearTimeout(timer);
            } else {
              calledVoiceSend = true;
              timeSub(--waitTime, 1000);
            }
          }, unit || 0);
        }
      })
    } else if (calledVoiceSend) {
      message.warning('验证码将以电话的形式通知到您，请注意接听');
    } else {
      setBtnText('请输入正确的手机号');
      setBtnDisabled(true);
      setTimeout(function () {
        setBtnText('登录');
        setBtnDisabled(false);
      }, 2500);
    }
  }

  function handleSendCode(checkData) {
    if (regWaitStatus) { return }
    const phoneLength = regPhone.trim().length;
    if (phoneLength == 11) {
      const params = {
        phone: regPhone,
        sig: checkData.sig,
        sessionId: checkData.csessionid,
        token: checkData.token,
        scene: 'nc_login',
        serverType: 'TRIAL_SAAS',
        sideType: 0, // 0 表示web端
      }
      axios.postJSON('business/anon/sms/sendSmsCode', params, { reject: true }).then((res) => {
        if (!res.success) {
          message.warning(res.message);

        } else {
          timeSub(60);
          setChecking3(true);
          setCertificate(res.result);
        }
      })

      let timer;

      function timeSub(waitTime, unit) {
        clearTimeout(timer);
        timer = setTimeout(function () {
          if (waitTime == 0) {
            setRegCodeText('发送验证码');
            setRegWaitStatus(false)
            setChecking3(false);
            clearTimeout(timer);
          } else {
            if (waitTime < 40) {
              setRegVoiceCodeTip(true)
            }
            setRegCodeText(`${waitTime  }秒后重发`);
            setRegWaitStatus(true)
            timeSub(--waitTime, 1000);
          }
        }, unit || 0);
      }
    } else {
      setRegBtnText('请输入正确的手机号');
      setRegBtnDisabled(true)
      setTimeout(function () {
        setRegBtnText('提交');
        setRegBtnDisabled(false)
      }, 2500);

    }
  }

  function handleRegiste(e) {
    e.preventDefault();
    const data = {
      instName,
      phone: regPhone,
      code
    };
    function verifity(tips) {
      setRegBtnText(tips);
      setRegBtnDisabled(true)
      setTimeout(function () {
        setRegBtnText('提交');
        setRegBtnDisabled(false)
      }, 2500);
    }

    if (!data.phone) {
      verifity('请输入手机号');
      return;
    }

    if (data.phone.length != 11) {
      verifity('请输入正确的手机号');
      return;
    }

    if (!data.code) {
      verifity('请输入验证码');
      return;
    }

    if (!data.instName) {
      verifity('请输入机构名');
      return;
    }
    data.inviteCode = 'web-b'
    data.contract = '-';
    data.source = 'web-b-免费试用'

    data.pwd = '';
    data.serverType = 'TRIAL_SAAS';
    axios.post('api-b/b/web/register', data).then((res) => {
      if (res.resultCode == 1103) {
        message.info('请输入正确的验证码');
        return;
      }
      setInstName('');
      setRegPhone('');
      setCode('');
      setModalVisible(false);
      message.success("申请成功，我们会在1-2个工作日审核完，请耐心等待！", "提醒");
    })
      .catch((res) => {
        setRegBtnText('提交');
        setRegBtnDisabled(false);
      });
  }

  function handleDownloadChrome() {
    const url = 'http://www.chromeliulanqi.com/';
    window.open(url, '_black');
  }

  function checkSend(code) {
    const value = code < 3 ? phone : regPhone;
    if (!value) {
      message.warning('请输入手机号');
      return;
    }
    if (value.length != 11) {
      message.warning('请输入11位手机号')
      return;
    }
    switch (code) {
      case 1:
        !_.isEmpty(checkObject1) && checkObject1.reset();
        setOpenCheck1(true)
        break;
      case 2:
        !_.isEmpty(checkObject2) && checkObject2.reset();
        setOpenCheck2(true)
        break;
      case 3:
        !_.isEmpty(checkObject3) && checkObject3.reset();
        setOpenCheck3(true)
        break;
      case 4:
        !_.isEmpty(checkObject4) && checkObject4.reset();
        setOpenCheck4(true)
        break;
      default:
        break;
    }
  }

  async function checkAccount(code, callback = () => { }) {
    const value = code < 3 ?
      phone
      : regPhone;

    const userType = await axios
      .postJSON('business/anon/b/checkUserType', { "mainAccount": value })
      .then(({ result: { userType } }) => {
        return userType
      })

    if (userType === 'CRM_INST') {
      setUserType('CRM_INST');
      callback('CRM_INST');
      return;
    }

    callback();
  }

  return (
    <div className="login-page" style={{ background: `url(${  require('../../images/main_banner.png')  })`, backgroundSize: '100%', backgroundRepeat: 'no-repeat', backgroundColor: '#21242E' }}>

      <div className="header">
        <Row className="header-main" type="flex" justify="space-between" align="middle">
          <Col>
            <a target="_blank" href="http://www.xiaomai5.com/">
              <img  src={require("../../images/logo_primary_new.png")} className='logo' alt="" />
            </a>
          </Col>
          <Col>
            <Select defaultValue={api} style={{ width: 150 }} onChange={
              (val) => {
                LS.set('DRURL', val);
                setApi(val);
                DRURL = val;
                LS.set('DRURL', DRURL);
              }
            }>
              <Option value="">线路1-杭州</Option>
              {
                _.map(drList, (item) => {
                  return <Option value={`${item.url  }/`}>{item.describe}</Option>
                })
              }

            </Select>
          </Col>
        </Row>
      </div>

      <div className="login-main">
        <div className="left-banner">
          <img  src='https://image.xiaomaiketang.com/xm/DXDsNKB3Fn.png' alt="" style={{ width: 448, marginTop: 60 }} />
        </div>
        <div className="login-box stage">
          <div className="login">
            <div className="r">
              <div className="title">

                <Tabs activeKey={loginStyle} tabBarStyle={{ border: 'none', padding: '0 25px' }} onChange={(activeKey) => { setLoginStyle(activeKey) }}>
                  <TabPane tab="密码登录" key="passwordLogin" />
                  <TabPane tab="验证码登录" key="phoneverifyLogin" />
                </Tabs>
              </div>
              <form action="" className="login-form" onSubmit={handleLogin}>
                <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>
                  {loginStyle == 'passwordLogin' &&
                  <div className="password" style={{ marginBottom: 16 }}>
                    <Input type={showPassword ? 'text' : 'password'} id="pwd" name="pwd" placeholder="密码" value={password} onChange={(e) => { setPwd(e.target.value) }} />
                    <span className="icon iconfont" id="password-icon" onClick={() => { setShowPassword(!showPassword) }} dangerouslySetInnerHTML={{ __html: showPassword ? '&#xe6af;' : '&#xe6ae;' }} />
                  </div>

                  }
                  {
                    loginStyle == 'phoneverifyLogin' &&
                    [
                      <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) => {
                                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="phoneverify-voice" style={{ display: voiceCodeTip ? 'block' : 'none', marginBottom: 10 }}>
                        <span style={{ color: '#333' }}>收不到短信? </span>
                        <Popover
                          visible={openCheck2}
                          trigger="click"
                          title=""
                          content={<div>
                            <span style={{ fontSize: '12px', color: '#999', marginBottom: 8, display: 'block' }}>请完成安全验证</span>
                            <CheckBeforeSendCode
                              callback={(data, nc) => {
                                handleSendVoiceCode(data, 2);
                                setCheckObject2(nc);
                                setTimeout(() => {
                                  setOpenCheck2(false);
                                }, 500);
                              }}
                            />
                          </div>}
                          onVisibleChange={(value) => {
                            if (!value) {
                              setOpenCheck2(false);
                            }
                          }}
                          placement="bottomRight"
                        >
                          <span
                            style={{ color: '#58B7EF', }}
                            id="sendVoiceVerifyCode"
                            onClick={() => {
                              checkSend(2)
                            }}
                          >使用语音验证码</span>
                        </Popover>
                      </div>
                    ]


                  }
                  <div className="submit">
                    <div className="btn">
                      <button id='loginIn' type="submit" disabled={btnDisabled}>{btnText}</button>
                    </div>
                    <div className="apply" onClick={() => { setModalVisible(true) }}>
                      <span>免费试用</span>
                    </div>
                  </div>

                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
      <div className="footer">
        <div className="footer-main" style={{marginTop:4}}>
          <span><span className="icon iconfont">&#xe627;</span>杭州市西湖区古墩路598号同人广场A座3楼</span>
          <span className="tel ml22"><span className="icon iconfont">&#xe628;</span>400-6677-456(小麦助教) </span>
          <span className="download-chrome ml22" onClick={handleDownloadChrome}><img src={require("../../images/chrome.png")} />前往下载chrome谷歌浏览器 </span>
        </div>
        <div className="footer-main mt8">
          <span>@2015-2020    杭州杰竞科技有限公司</span>
          <a target="_blank"
            href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010602006090"><img src={GH} alt="" style={{width: '16px', height: '16px', display: 'inline-block', margin: '0 4px 0 0'}}/>浙公网安备33010602006090号</a>
          <a target="_blank"
             href="http://www.beian.miit.gov.cn/state/outPortal/loginPortal.action;jsessionid=oLD4DenLthr_n8liJdOYupeEe9iZYycUySDz15TmoSGC9ZeRF157!1870117190">浙ICP备15025826号-2</a>
          <a target="_blank" href="https://image.xiaomaiketang.com/xm/ffXeG5fXn8.jpg">增值电信业务经营许可证：浙B2-20180802</a>
        </div>
      </div>

      <div className="layout layout-reg" style={{ display: modalVisible ? 'block' : 'none' }}>
        <div className="box">
          <div className="reg">
            <div className="t clearfix" onClick={() => { setModalVisible(false) }}>
              <span style={{ float: 'right' }} className="close icon iconfont">&#xe608;</span>
            </div>
            <div className="c">
              <div className="title">免费试用</div>
              <div className="form" style={{ textAlign: 'center' }}>
                <form action="" className="register-form" onSubmit={handleRegiste}>
                  <Input type="text" placeholder="机构名" name="instName" id="instName" autoComplete="off" value={instName} onChange={(e) => { setInstName(e.target.value) }} />
                  <Input
                    type="text"
                    placeholder="手机号"
                    name="phone"
                    id="phone"
                    maxLength={11}
                    autoComplete="off"
                    value={regPhone}
                    onChange={(e) => {
                      const value = (`${e.target.value  }`).replace(/[^0-9]/g, '');
                      setRegPhone(value);
                    }}
                  />
                  <div className="vertify-code">
                    <Input type="text" placeholder="验证码" name="code" id="code" autoComplete="off" value={code} onChange={(e) => { setCode(e.target.value) }} />
                    <Popover
                      visible={openCheck3}
                      trigger="click"
                      title=""
                      content={<div>
                        <span style={{ fontSize: '12px', color: '#999', marginBottom: 8, display: 'block' }}>请完成安全验证</span>
                        <CheckBeforeSendCode
                          callback={(data, nc) => {
                            handleSendCode(data);
                            setCheckObject3(nc);
                            setTimeout(() => {
                              setOpenCheck3(false);
                            }, 500);
                          }}
                        />
                      </div>}
                      onVisibleChange={(value) => {
                        if (!value) {
                          setOpenCheck3(false);
                        }
                      }}
                      placement="bottomRight"
                    >
                      <div
                        className="btn"
                        id="sendCode"
                        onClick={() => {
                          if (checking3) return;
                          checkSend(3)
                        }}
                      >{regCodeText}</div>
                    </Popover>
                  </div>
                  <div className="phoneverify-voice" style={{ display: regVoiceCodeTip ? 'block' : 'none' }}>
                    <span style={{ color: '#686868' }}>收不到短信?</span>
                    <Popover
                      visible={openCheck4}
                      trigger="click"
                      title=""
                      content={<div>
                        <span style={{ fontSize: '12px', color: '#999', marginBottom: 8, display: 'block' }}>请完成安全验证</span>
                        <CheckBeforeSendCode
                          callback={(data, nc) => {
                            handleSendVoiceCode(data, 4);
                            setCheckObject4(nc);
                            setTimeout(() => {
                              setOpenCheck4(false);
                            }, 500);
                          }}
                        />
                      </div>}
                      onVisibleChange={(value) => {
                        if (!value) {
                          setOpenCheck4(false);
                        }
                      }}
                      placement="bottomRight"
                    >
                      <span
                        style={{ color: '#FFAB1A', cursor: 'pointer' }}
                        id="sendRegVoiceVerifyCode"
                        onClick={() => {
                          checkSend(4)
                        }}
                      >使用语音验证码</span>
                    </Popover>
                  </div>
                  <button type="submit" disabled={regBtnDisabled}>{regBtnText}</button>
                </form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default withRouter(Login);
