/// <reference path="./definition.d.ts" />

import * as React from 'react';
import Toast from '../toast';
import Hammer from 'react-hammerjs';
import classNames from 'classnames';
import { validatePattern, validateRequried } from '../util/validate';

const defaultLabel = '发送验证码';
const prefix = 'tsp-component-Verification';
class Verification extends React.Component<VerificationProps, VerificationState> {
  constructor(props: VerificationProps, state: VerificationState) {
    super(props, state);
    this.onClick = this.onClick.bind(this);
  }
  public static defaultProps: VerificationProps = {
    time: 60,
    validate: null,
    callback: null,
    disabledLabel: '下次发送',
    inputId: ''
  };

  /**
   * 存储setInterval，用于销毁定时器
   */
  private interval: any;

  public state: VerificationState = {
    label: defaultLabel,
    time: this.props.time
  };

  public componentWillUnmount(): void {
    // 销毁定时器
    clearInterval(this.interval);
  }

  /**
   * 设置按钮文本
   */
  public setBtnLabel(): void {
    const nowTime = --this.state.time;
    this.setState({
      time: nowTime < 0 ? this.props.time : nowTime,
      label: nowTime < 0 ? defaultLabel : `${this.props.disabledLabel}(${nowTime})`
    });
  }

  /**
   * 验证码获取
   */
  public onClick(): void {
    const inputElem = document.getElementById(this.props.inputId);
    if (!validateRequried(inputElem, (msg) => Toast.warning(msg))) {
      return;
    }
    if (!validatePattern(inputElem, (msg) => Toast.warning(msg))) {
      return;
    }
    if (this.props.validate) {
      if (!this.props.validate()) {
        return;
      }
    }
    if (this.state.time === this.props.time) {
      this.setBtnLabel();
      this.interval = setInterval(() => {
        this.setBtnLabel();
        if (this.state.time <= 0) {
          clearInterval(this.interval);
          this.setBtnLabel();
        }
      }, 1000);
      this.props.callback();
    }
  }

  public render(): any {
    const disabled = this.state.time !== this.props.time;
    return (
      <Hammer onTap={this.onClick}>
        <button
          className={classNames({
            [prefix]: true,
            [this.props.className]: this.props.className,
            [`${prefix}-disabled`]: disabled
          })}
          disabled={disabled}
          type="button"
        >{this.state.label}</button>
      </Hammer>
    );
  }
}

export default Verification;
