<template>
  <span>
    <el-button
      @click="changeAutoRefresh"
      :size="size"
    >{{ autoRefreshText }}</el-button> <span class="tips">{{ countDownText }}</span>
  </span>
</template>

<script setup lang="ts">
/**
 * 自动刷新组件
 * emit: refresh - 刷新事件
 */
import { ref, computed, onBeforeUnmount } from 'vue';

const props = defineProps({
  // 刷新频率，默认：3秒
  frequency: { type: Number, default: 3000 },
  // 按钮大小
  size: { type: String, default: 'default' }
});

const emit = defineEmits(['refresh']);

// 定时器
const timer = ref<NodeJS.Timeout | null>(null);
const countDownTimer = ref<NodeJS.Timeout | null>(null);

// 倒计时
const countDown = ref(0);

const autoRefreshText = computed(() => {
  if (timer.value == null) {
    return '开启自动刷新';
  } else {
    return '关闭自动刷新';
  }
});

const countDownText = computed(() => {
  if (timer.value == null) {
    return '';
  } else {
    return countDown.value + ' 秒后自动刷新';
  }
});

function autoRefresh() {
  emit('refresh');
  resetCountDown();
}

function countDownReduce() {
  countDown.value--;
}

function resetCountDown() {
  countDown.value = Math.ceil(props.frequency * 0.001);
}

function openAutoRefresh() {
  resetCountDown();

  // 启动读秒计时器
  countDownTimer.value = setInterval(() => {
    countDownReduce();
  }, 1000);

  // 启动自动刷新计时器
  timer.value = setInterval(() => {
    autoRefresh();
  }, props.frequency);
}

function closeAutoRefresh() {
  if (timer.value) clearInterval(timer.value);
  if (countDownTimer.value) clearInterval(countDownTimer.value);

  timer.value = null;
  countDownTimer.value = null;
}

function changeAutoRefresh() {
  if (timer.value) {
    closeAutoRefresh();
  } else {
    openAutoRefresh();
  }
}

// 组件销毁前清除定时器
onBeforeUnmount(() => {
  closeAutoRefresh();
});
</script>

<style lang="scss" scoped>
.tips {
  margin-left: 10px;
  color: #666666;
  font-size: 12px;
}

.el-button:focus {
    outline: none;
}
</style>
