export default class CountDown {
  constructor(opts) {
    if (opts.endTime && opts.restTime) {
      throw new Error('endTime,resTime只能传一个');
    }
    if (!opts.endTime && !opts.restTime) {
      throw new Error('endTime,resTime必须传一个');
    }
    this.opts = opts;
    this.delay = opts.delay || 1000;
    this.endTime = new Date(opts.endTime).getTime();
    this.restTime = opts.restTime || 0;
    this.isPause = false;
  }
  start(notFirst) {
    if (!notFirst) {
      let o = this.format();
      this.opts.onChange(o);
    }
    setTimeout(() => {
      if (this.isPause) {
        return;
      }
      let o = this.format();
      this.opts.onChange(o);
      if (this.restTime <= 0) {
        this.opts.onCompleted();
        return;
      }
      this.start(1);
    }, this.opts.delay);
  }
  pause() {
    this.isPause = true;
  }
  format() {
    this.restTime = this.endTime ? this.endTime - new Date().getTime() : this.restTime - this.delay;
    let days = Math.floor(this.restTime / (1000 * 60 * 60 * 24));
    let hours = Math.floor((this.restTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((this.restTime % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((this.restTime % (1000 * 60)) / 1000);
    return {
      days,
      hours,
      minutes,
      seconds
    };
  }
}
