import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import styles from './style.css';
import logoIcon from './images/school_logo@2x.png';
import logoWord from './images/school_word_logo@2x.png';
import { Button, Modal, Toast } from 'antd-mobile';
import { getVcode, sendMsg, login } from '../../api/index';
import CodeView from '../../components/CodeView/CodeView';
import UserInfoContext from '../../context/userinfo-context';
import store from '../../store';

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirectToReferrer: false,
      sending: false,
      count: 60,
      cellphone: '',
      vcodeDialogVisible: false,
      vcode: '',
      svcode: '',
      code: '',
    };
  }

  componentWillUnmount() {
    const { sending } = this.state;
    if (sending) clearTimeout(this.timer);
  }

  updateCellphone = e => {
    this.setState({
      cellphone: e.target.value.replace(/\D/g, ''),
    });
  };
  getVcodeHandle = () => {
    const { sending, cellphone } = this.state;
    if (sending) return;
    if (!cellphone) {
      Toast.fail('请输入手机号');
      return;
    }
    if (cellphone.length !== 11) {
      Toast.fail('请输入正确手机号');
      return;
    }
    getVcode({ cellphone })
      .then(res => {
        console.log(res);
        this.setState({
          svcode: res.data,
          vcodeDialogVisible: true,
          vcode: '',
        });
      })
      .catch(err => {
        Toast.fail(err.msg || '获取验证码失败！');
        console.log(err);
      });
  };
  resetDialog = () => {
    this.setState({
      vcodeDialogVisible: false,
    });
  };
  checkVcode = () => {
    const { vcode, svcode } = this.state;
    if (vcode === svcode) {
      this.sendMsgHandle();
      this.resetDialog();
    } else {
      Toast.fail('请输入正确的验证码！');
    }
  };
  sendMsgHandle = () => {
    const { sending, cellphone, vcode } = this.state;
    if (sending) return;
    sendMsg({
      cellphone,
      valiCode: vcode,
    })
      .then(res => {
        console.log(res);
        Toast.success(res.msg || '发送验证码成功！');
      })
      .catch(err => {
        Toast.fail(err.msg || '发送验证码失败！');
        console.log(err);
      });
    this.setState({
      sending: true,
    });
    this.startCountDown();
  };
  startCountDown = () => {
    const { count } = this.state;
    if (count === 0) {
      clearTimeout(this.timer);
      this.setState(({ count }) => ({
        sending: false,
        count: 60,
      }));
    } else {
      this.setState(({ count }) => ({
        count: --count,
      }));
      this.timer = setTimeout(() => {
        this.startCountDown();
      }, 1000);
    }
  };
  loginHandle = () => {
    const { updateUserInfo } = this.props;
    const { code, cellphone } = this.state;
    if (!code) {
      Toast.fail('请输入短信验证码');
      return;
    }
    const entity = {
      cellphone,
      code,
    };
    login(entity)
      .then(res => {
        const { user, author } = res.data;
        store.updateUserId(user.userId);
        updateUserInfo({
          ...user,
          author,
        });
        this.setState({ redirectToReferrer: true });
        console.log(res);
      })
      .catch(err => {
        console.log(err);
        Toast.fail(err.msg || '登陆失败！');
      });
  };

  render() {
    // const { from } = this.props.location.state || { from: { pathname: '/' } };
    const {
      redirectToReferrer,
      sending,
      count,
      cellphone,
      vcodeDialogVisible,
      vcode,
      svcode,
      code,
    } = this.state;
    if (redirectToReferrer) {
      return <Redirect to={{ pathname: '/home' }} />;
    }
    return (
      <div className={styles.Login}>
        <div className={styles.loginBox}>
          <div className={styles.logo}>
            <img src={logoIcon} alt="" />
          </div>
          <div className={styles.logoWord}>
            <img src={logoWord} alt="" />
          </div>
          <div className={styles.inputWrap}>
            <div className={styles.inputBox}>
              <input
                className={styles.input}
                type="tel"
                placeholder="请输入手机号"
                value={cellphone}
                onChange={this.updateCellphone}
                maxLength="11"
              />
            </div>
            <div className={styles.vcodeBox}>
              <div className={styles.vInputBox}>
                <input
                  className={styles.input}
                  type="tel"
                  placeholder="请输入短信验证码"
                  value={code}
                  maxLength="6"
                  onChange={e =>
                    this.setState({
                      code: e.target.value,
                    })
                  }
                />
              </div>
              <div className={styles.vcode} onClick={this.getVcodeHandle}>
                {sending ? `${count}s后重新获取` : '获取验证码'}
              </div>
            </div>
          </div>

          <div className={styles.btnBox}>
            <Button className={styles.okbtn} onClick={this.loginHandle}>
              登录
            </Button>
            <Button className={styles.canclbtn}>取消</Button>
          </div>
          <Modal
            className={styles.vcodeDialog}
            visible={vcodeDialogVisible}
            transparent
            maskClosable={false}
            onClose={this.resetDialog}
            title=""
          >
            <div className={styles.vcodeinputBox}>
              <div className={styles.vcodeItem}>
                <input
                  className={styles.input}
                  type="tel"
                  value={vcode}
                  onChange={e => this.setState({ vcode: e.target.value })}
                  maxLength="6"
                />
              </div>
              <div className={styles.vcodeItem}>
                <CodeView value={svcode} alt="" />
              </div>
            </div>
            <Button className={styles.vcodeOkbtn} onClick={this.checkVcode}>
              确认
            </Button>
          </Modal>
        </div>
      </div>
    );
  }
}

export default props => (
  <UserInfoContext.Consumer>
    {({ userinfo, updateUserInfo }) => (
      <Login {...props} updateUserInfo={updateUserInfo} />
    )}
  </UserInfoContext.Consumer>
);
