'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import './loginpop.less';
import API from '@/api';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { Button, Toast } from '@grace/ui';
import { _asyncThrottle } from '@/utils/utils';
import LightSDK from 'light-sdk/dist/index.umd'
import { CHANNEL } from '@/AppTools';
import Privacypop from '../privacypop/privacypop';

/* 电话号码验证规则 **/
export const REG_TEL = /^1[0-9]{10}$/;

@observer
class Loginpop extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      uid: "",

      loginPhone: "",
      loginCode: "",
      countDown: 60,  // 获取验证码倒计时
      showCountDown: false,  // 显示获取验证码
      showSendAgain: false, // 显示再次发送按钮
      showSend: true, // 显示发送按钮

      showPrivacyPop: false, // 显示隐私协议弹窗
      privacyChecked: false, // 隐私协议-是否勾选
    }
  }

  componentDidMount() {
    this.getUserInfo()
  }

  getUserInfo = () => {
    LightSDK.native.readData({
      key: "K_USERID",
      component_scope: "global"
    }, res => {
      console.info("LightSDK 请求结果>>>>>>>>>>>>>>>>", res)
      const uid = res.data?.result
      this.setState({ uid })
    })
  }

  /** 输入事件 */
  changeEvent = async (e, type) => {
    const value = e.target.value
    switch (type) {
      // 手机号
      case "loginPhone":
        const val = value.replace(/[^\d]/g, '')
        this.setState({ loginPhone: val })
        break;
      // 验证码
      case "loginCode":
        this.setState({ loginCode: value.replace(/[^\d]/g, '') })
        break;
      default:
        break;
    }
  }

  // 点击获取验证码
  clickGetCode = _asyncThrottle(() => {
    // 已经开始倒计时
    if (this.state.showCountDown) return false;
    if (!this.state.loginPhone || this.state.loginPhone == "") {
      Toast.show('请输入手机号')
    } else if (!REG_TEL.test(this.state.loginPhone)) {
      Toast.show('请输入正确手机号')
    } else {
      // 获取验证码
      this.getCode(this.state.loginPhone)
    }
  })

  // 获取验证码
  getCode = async (phoneNum) => {
    const params = {
      phoneNumber: phoneNum,
    }
    const { success, data } = await API.coop_sendCode(params)
    if (success) {
      if (data?.code == 0) {
        Toast.show("验证码已发送");
        this.setState({
          showSend: false,
          showCountDown: true,
          countDown: 60,
          showSendAgain: false
        })
        this.codeCountDown()
      } else {
        data?.errorMsg && Toast.show(data.errorMsg)
      }
    }
  }

  // 验证码倒计时
  codeCountDown = () => {
    clearInterval(this.timer)
    this.timer = setInterval(() => {
      if (this.state.countDown == 0) {
        clearInterval(this.timer)
        this.setState({
          showCountDown: false,
          showSendAgain: true,
        })
      } else {
        this.setState({
          countDown: this.state.countDown - 1
        })
      }
    }, 1000)
  }

  // 确认提交  
  handleSubmit = _asyncThrottle(() => {
    const { loginPhone, loginCode } = this.state;
    const { agreementTitle } = this.props || {};

    if (!!agreementTitle && !this.state.privacyChecked) {  // 未勾选隐私协议
      Toast.show('请仔细阅读服务协议并勾选')
      return false
    } else if (!loginPhone) {  // 未输入手机号
      Toast.show('请输入手机号')
      return false
    } else if (!REG_TEL.test(loginPhone)) {
      Toast.show('请输入正确手机号')
      return false
    } else if (!loginCode) {  // 未输入验证码
      Toast.show('请输入验证码')
      return false
    }
    this.bindPhone();
  })

  // 绑定手机号
  bindPhone = async () => {
    const { loginPhone, loginCode, uid } = this.state;
    const params = {
      "phoneNumber": loginPhone,
      "smsCode": loginCode,
      "origenUid": uid,
    }
    const { success, data } = await API.coop_checkCode(params)
    if (success) {
      location.replace(data);
    }
  }

  close = () => {
    ModalCtrl.closeModal()
  }

  render() {
    const { loginPhone, loginCode, showCountDown, countDown, showSendAgain, showSend } = this.state;
    const { showPrivacyPop, privacyChecked } = this.state;

    const { agreementTitle, agreementText, hideClose } = this.props || {};
    return (<>
      <div className={`loginpop modal_center ${!agreementTitle ? 'no_check' : ''}`}>
        <span className="bg"></span>
        <span className="title"></span>
        {/* 手机号 */}
        <div className="phone">
          <input
            className="phoneinput"
            type="tel"
            maxLength="11"
            placeholder="请输入手机号"
            value={loginPhone}
            onChange={(e) => this.changeEvent(e, 'loginPhone')}
          />
        </div>
        {/* 验证码 */}
        <div className="verification">
          <input
            className="verifyinput"
            maxLength="6"
            placeholder="请输入验证码"
            value={loginCode}
            onChange={(e) => this.changeEvent(e, 'loginCode')}
          />
          {showSend && <span className="get_btn" onClick={this.clickGetCode}>获取验证码</span>}
          {showSendAgain && <span className="get_btn resend" onClick={this.clickGetCode}>重新发送</span>}
          {showCountDown && <span className="get_btn">{countDown}s</span>}
        </div>
        {!!agreementTitle && <div className="check_box">
          <div className={`check_icon ${privacyChecked ? 'checked' : ''}`} onClick={() => this.setState({ privacyChecked: !this.state.privacyChecked })}></div>
          <div>请仔细阅读
            <span className="content_title" onClick={() => this.setState({ showPrivacyPop: true })} dangerouslySetInnerHTML={{ __html: agreementTitle }}></span>
          </div>
        </div>}
        <Button className={`btn ${CFG.channel === CHANNEL.OFFLINE_QRCODE ? 'enter_btn' : '' }`} onClick={this.handleSubmit}></Button>
        {!hideClose && <Button className="close" onClick={this.close}></Button>}
      </div>

      {/* 二级弹出遮罩 */}
      {(showPrivacyPop) && <div className="mask"></div>}
      {/* 隐私协议弹窗 */}
      {showPrivacyPop && <Privacypop agreementText={agreementText} closeCb={() => this.setState({ showPrivacyPop: false })} />}
    </>);
  }
}
export default Loginpop;
