import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import { createVNode as _createVNode } from "vue";
import _extends from "@babel/runtime/helpers/esm/extends";
import { cloneVNode, computed, defineComponent, ref, watch } from 'vue';
import { stringType } from '../_util/type';
import Statistic, { statisticProps } from './Statistic';
import { formatCounter } from './utils';
import { initDefaultProps } from '../_util/props-util';
import { omit } from 'lodash';
const UPDATE_INTERVAL = 1000 / 60;
export const statisticTimerProps = () => _extends(_extends({}, statisticProps()), {
  type: stringType(),
  format: String,
  onFinish: Function,
  onChange: Function
});
function getTime(value) {
  return new Date(value).getTime();
}
export default defineComponent({
  name: 'AStatisticTimer',
  props: initDefaultProps(statisticTimerProps(), {
    format: 'HH:mm:ss'
  }),
  slots: Object,
  setup(props, {
    slots
  }) {
    const down = computed(() => props.type === 'countdown');
    const statisticRef = ref();
    // ======================== Update ========================
    const update = () => {
      var _a, _b;
      const now = Date.now();
      const timestamp = getTime(props.value);
      const timeDiff = !down.value ? now - timestamp : timestamp - now;
      (_a = props.onChange) === null || _a === void 0 ? void 0 : _a.call(props, timeDiff);
      if (down.value && timestamp < now) {
        (_b = props.onFinish) === null || _b === void 0 ? void 0 : _b.call(props);
        return false;
      }
      return true;
    };
    watch([down, () => props.value], (_, __, onCleanup) => {
      let intervalId;
      const tick = () => {
        var _a;
        if (!update()) {
          window.clearInterval(intervalId);
        } else {
          (_a = statisticRef.value) === null || _a === void 0 ? void 0 : _a.$forceUpdate();
        }
      };
      const startTimer = () => {
        intervalId = window.setInterval(tick, UPDATE_INTERVAL);
      };
      const stopTimer = () => {
        window.clearInterval(intervalId);
      };
      startTimer();
      onCleanup(stopTimer);
    }, {
      flush: 'post',
      immediate: true
    });
    // ======================== Format ========================
    const formatter = ({
      value,
      config
    }) => formatCounter(value, _extends(_extends({}, config), {
      format: props.format
    }), down.value);
    const valueRender = node => cloneVNode(node, {
      title: undefined
    });
    return () => {
      return _createVNode(Statistic, _objectSpread(_objectSpread({
        "ref": statisticRef
      }, omit(props, ['onChange', 'onFinish', 'type', 'format'])), {}, {
        "formatter": formatter,
        "valueRender": valueRender
      }), slots);
    };
  }
});