import React from 'react'
import './index.scss'
import { Input, Button, Alert, Spin } from 'antd'
import API from '@/api'
import Param from '@/util/param'
import Rule from '@/util/rule'
import store from '@/store'
import { showError } from '@/util'

export default class Login extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      phone: this.getLoginPhone(),
      code: null,
      buttonText: '验证码',
      countTimes: -1,
      errorVisible: false,
      errorMsg: null,
      loading: false
    }
    this.timer = null// 读秒倒计时
  }
  componentDidMount () {
    if (store.userId && store.token) {
      this.props.history.push('/user/information')
    }
  }
  componentWillUnmount () {
    clearInterval(this.timer)
  }
  getLoginPhone () {
    return localStorage.getItem('loginPhone')
  }
  setLoginPhone (phone) {
    localStorage.setItem('loginPhone', phone)
  }
  updatePhoneInput (event) {
    this.setState({
      phone: event.target.value
    })
  }
  updateCodeInput (event) {
    this.setState({
      code: event.target.value
    })
  }
  async onGetCode () {
    let param = new Param({
      phone: [this.state.phone, 'require', Rule.Reg_Phone]
    })
    if (!param.checkParams()) {
      this.setState({
        errorVisible: true,
        errorMsg: param.error
      })
      return false
    } else if (this.state.countTimes < 0) {
      this.setState({
        errorVisible: false,
        errorMsg: null
      })
    }

    try {
      let data = await API.login.getCode({ phone: this.state.phone })
      if (data.code === 0) {
        this.startCountdown()
      } else {
        this.setState({
          errorVisible: true,
          errorMsg: data.msg
        })
      }
    } catch (e) {
      showError(e)
    }
  }
  startCountdown (seconds = 60) {
    this.setState({
      countTimes: seconds
    })
    this.timer = setInterval(() => {
      if (this.state.countTimes <= 0) {
        clearInterval(this.timer)
        this.setState({
          countTimes: -1,
          buttonText: `验证码`
        })
        return
      }

      this.setState({
        countTimes: this.state.countTimes - 1,
        buttonText: `验证码（${this.state.countTimes - 1}s）`
      })
    }, 1000)
  }
  async onSubmit () {
    if (this.state.loading) return

    let { phone, code } = this.state

    let param = new Param({
      phone: [phone, 'require', Rule.Reg_Phone],
      code: [code, 'require', Rule.Reg_Code]
    })
    if (!param.checkParams()) {
      this.setState({
        errorVisible: true,
        errorMsg: param.error
      })
      return false
    }
    this.setState({
      errorVisible: false
    })

    this.setState({ loading: true })

    try {
      let data = await API.login.checkCode({ phone, code })
      store.login(phone, data.data.token)
      this.setLoginPhone(phone)
      this.setState({ loading: false })
      this.props.history.push('/user/information')
    } catch (e) {
      this.setState({
        loading: false,
        errorVisible: true,
        errorMsg: e.message
      })
    }
  }
  render () {
    return (
      <div className="mod-login">
        <div className="mod-row">
          <label htmlFor="phoneInput">手机号：</label>
          <Input
            placeholder="请填写手机号"
            defaultValue={this.state.phone}
            id="phoneInput"
            onBlur={this.updatePhoneInput.bind(this)}
          />
          <Button
            className={`btn-code ${this.state.countTimes >= 0 &&
                            'countdown'}`}
            type="primary"
            onClick={this.onGetCode.bind(this)}
          >
            {this.state.buttonText}
          </Button>
        </div>

        <div className="mod-row">
          <label htmlFor="codeInput">验证码：</label>
          <Input
            placeholder="请输入验证码"
            id="codeInput"
            onBlur={this.updateCodeInput.bind(this)}
            onPressEnter={event => {
              this.updateCodeInput(event)
              setTimeout(this.onSubmit.bind(this), 0)
            }}
          />
        </div>

        <Alert
          className={this.state.errorVisible && 'visible'}
          message={this.state.errorMsg}
          type="error"
        />

        <Button
          className="btn-login"
          type="primary"
          size="large"
          onClick={this.onSubmit.bind(this)}
        >
                    登录
          {this.state.loading && <Spin />}
        </Button>
      </div>
    )
  }
}
