import React from "react";
import {observer} from "mobx-react";
import "./LoginPop.less";
import {REG_TEL, _asyncThrottle, getUrlParam} from "../../utils/utils";
import { LOG_KEY, pageView, sensorLog } from "../../utils/sensors.js";
import { Button, Toast } from "@grace/ui";
import API from "../../api";


@observer
class LoginPop extends React.Component {

  state = {
    phone: "",
    code: "",
    isSend: false,
    reSend: false,
    cd: 60,
  };

  componentDidMount() {
    pageView("b14257", {
      page_name: "手机号登录页",
    });
    sensorLog(LOG_KEY.exposure, "b14257", "d14260", {
      page_name: "手机号登录页",
      button_name: "登录按钮",
    });
    sensorLog(LOG_KEY.exposure, "b14257", "d14258", {
      page_name: "手机号登录页",
      button_name: "发送验证码按钮",
    });

  }

  startCd = () => {
    this.cdInterval = setInterval(() => {
      const cd = this.state.cd -= 1;
      this.setState({
        cd,
      });

      if (cd <= 0) {
        clearInterval(this.cdInterval);
        this.setState({
          isSend: false,
          reSend: true,
        },()=>{
          sensorLog(LOG_KEY.exposure, "b14257", "d14259", {
            page_name: "手机号登录页",
            button_name: "重新发送按钮",
          });
        });
      }
    }, 1000);
  };

  clickSend = _asyncThrottle(async () => {
    const {phone, reSend} = this.state;
    if(reSend){
      sensorLog(LOG_KEY.click, "b14257", "d14259", {
        page_name: "手机号登录页",
        button_name: "重新发送按钮",
      });
    }else{
      sensorLog(LOG_KEY.click, "b14257", "d14258", {
        page_name: "手机号登录页",
        button_name: "发送验证码按钮",
      });
    }
    

    if (!phone) {
      return Toast.show("请输入手机号");
    }
    if (!REG_TEL.test(phone)) {
      return Toast.show("请输入正确的手机号～");
    }
    await this.getCode(phone);
  });

  closeLogin = _asyncThrottle(async () => {
    sensorLog(LOG_KEY.click, "b14257", "d14260", {
      page_name: "手机号登录页",
      button_name: "登录按钮",
    });
    const {phone, code} = this.state;

    if (!phone) {
      return Toast.show("请输入手机号");
    }

    if (!REG_TEL.test(phone)) {
      return Toast.show("请输入正确的手机号～");
    }

    if (!code) {  // 未输入验证码
      return Toast.show("请输入验证码");
    }

    await this.bindPhone();

  });

  getCode = async (phoneNum) => {
    const params = {
      appId: getUrlParam("appID"),
      mobile: phoneNum,
    };

    const {success} = await API.getCode(params);
    if (success) {
      Toast.show("验证码已发送");
      this.setState({
        isSend: true,
        cd: 60,
      });
      this.startCd();
    }
  };


  bindPhone = async () => {
    const {phone, code} = this.state;

    const param = {
      mobile: phone,
      code: code,
      redirectUrl: window.location.href,
    };

    const {success, data, desc} = await API.bindPhone(param);
    if (success) {
      if(location.href.indexOf('localhost') > -1){
        ModalCtrl.closeModal()
      }else{
        location.replace(data);
      }
    } else {
      Toast.show(desc);
    }
  };

  // 输入手机号
  onPhoneInput = (e) => {
    let lastValue = "";
    let currentValue = e.target.value;
    if (currentValue !== lastValue) {
      this.setState({
        reSend: false
      });
    }

    this.setState({
      phone: e.target.value.replace(/[^\d]/g, ""),
    });
  };

  onCodeInput = (e) => {
    this.setState({
      code: e.target.value.replace(/[^\d]/g, ""),
    });
  };

  handleClose = _asyncThrottle(() => {
    ModalCtrl.closeModal();
  })


  render() {
    const {phone, code, isSend, cd, reSend} = this.state;
    const loginBtnCls = phone && code ? "LoginBtn md3" : "LoginBtnNoAct md3";
    return <div className="LoginPop modal_center">
      <div className="bg">

        <input
          className="input phoneInput"
          placeholder="输入手机号"
          maxLength="11"
          value={phone}
          autoComplete="off"
          onChange={this.onPhoneInput}
        />

        <input
          className="input codeInput"
          placeholder="输入验证码"
          maxLength="8"
          value={code}
          autoComplete="off"
          onChange={this.onCodeInput}
        />

        {
          isSend ? <div className="sendCode">{cd}s</div>
            : <div
              className={reSend ? "sendBtn md2" : "sendBtn md1"}
              onClick={this.clickSend}>
              {reSend ? "重新发送" : "发送验证码"}
            </div>
        }

        <Button className={loginBtnCls} onClick={this.closeLogin}/>
      </div>
      {/* <Button className="close" onClick={this.handleClose} /> */}
    </div>;
  }
}

export default LoginPop;
