import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
/**
 * 持续时间
 *
 * @class DurationTime
 * @extends {Component}
 */
class DurationTime extends Component {

  static propTypes = {
    date: PropTypes.string,
    format: PropTypes.string
  };

  static defaultProps = {
    format: 'YYYY-MM-DD HH:mm:ss'
  };

  constructor(props) {
    super(props);
    this.state = {
      runTime: 0
    };
  }

  componentDidMount() {
    this.getStartTime();
  }

  componentWillUpdate(nextProps, nextState) {
    if (nextProps.date !== this.props.date) {
      this.getStartTime();
    }
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }

  start = () => {
    const one = 1000;
    this.timer && clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.setState({ runTime: this.state.runTime + one });
    }, one);
  }

  getStartTime = () => {
    const { date, format } = this.props;
    if (date) {
      const time = moment().diff(moment(date, format));
      this.setState({ runTime: time > 0 ? time : 0 }, () => {
        this.start();
      });
    }
  }

  secondToDate = (time) => {
    const timeCovert = 60;
    const onHour = 3600;
    const oneSecends = 1000;
    const onday = 24;
    const days = Math.floor(time / (onday * onHour * oneSecends));
    const leave1 = time % (onday * onHour * oneSecends);
    const hours = Math.floor(leave1 / (onHour * oneSecends));
    const leave2 = leave1 % (onHour * oneSecends);        // 计算小时数后剩余的毫秒数
    const minutes = Math.floor(leave2 / (timeCovert * oneSecends));
    // 计算相差秒数
    const leave3 = leave2 % (timeCovert * oneSecends);      // 计算分钟数后剩余的毫秒数
    const seconds = Math.round(leave3 / oneSecends);


    return [days, hours, minutes, seconds];
  }

  render() {
    const { date } = this.props;
    if (!date) {
      return null;
    }
    const { runTime } = this.state;
    const [d, h, m, s] = this.secondToDate(runTime);
    return (
      <span title={`${h !== '00' ? `${h}时` : ''}${m !== '00' ? `${h}分` : ''}${s}秒`}>
        {d && <span>{d}天</span>}
        {(d || h) && <span>{h}小时</span>}
        {(d || m || h) && <span>{m}分</span>}
        {<span>{s}秒</span>}
      </span>
    );
  }
}

export default DurationTime;
