import React from "react";
import {observer} from "mobx-react";
import "./LoginPop.less";
import {Button} from "@src/components/Button";
import {Toast} from "@spark/ui";
import API from "@src/api";
import {_asyncThrottle, getUrlParam} from "@src/utils/utils";
import {REG_TEL} from "@src/utils/constants";
import modalStore from "@src/store/modal";
import {LOG_KEY, pageView, sensorLog} from "@src/utils/sensors";

@observer
class LoginPop extends React.Component {

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

  componentDidMount() {
    pageView("b12830", {
      page_name: "手机号登录页",
    });
    sensorLog(LOG_KEY.exposure, "b12830", "d12832", {
      page_name: "手机号登录页",
      button_name: "登录按钮",
    });
    sensorLog(LOG_KEY.exposure, "b12830", "d12831", {
      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,
        });
      }
    }, 1000);
  };

  clickSend = _asyncThrottle(async () => {
    sensorLog(LOG_KEY.click, "b12830", "d12831", {
      page_name: "手机号登录页",
      button_name: "发送验证码按钮",
    });

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

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

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

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

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

    await this.bindPhone();

  });

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

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


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

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

    const {success, data, desc} = await API.bindPhone(param);
    if (success) {
      if(location.href.indexOf('localhost') > -1){
        modalStore.closePop('Login')
      }else{
        location.replace(data);
      }
    } else {
      Toast(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, ""),
    });
  };


  render() {
    const {phone, code, isSend, cd, reSend} = this.state;
    const loginBtnCls = phone && code ? "LoginBtn md2" : "LoginBtnNoAct md2";
    return <div className="LoginPop modal_center">
      <div className="light"/>
      <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 ? "sendCode md3" : "sendBtn md1"}
              onClick={this.clickSend}>
              {reSend ? "重新发送" : "发送验证码"}
            </div>
        }

        <Button className={loginBtnCls} onClick={this.closeLogin}/>
      </div>
    </div>;
  }
}

export default LoginPop;
