import dayjs from 'dayjs'
import { P_TYPE_DAILY } from '../column'
import { userStore } from '@/stores'
import { storeToRefs } from 'pinia'

export function useAutoUpdate(activeType: any, date: any, init: any) {
  const { userInfo } = storeToRefs(userStore())
  const updateTime = ref(dayjs().format('HH:mm:ss'))
  const showUpdateTime = computed(
    () =>
      userInfo.value.isTeacher &&
      activeType.value === P_TYPE_DAILY &&
      dayjs(date.value).isSame(dayjs(), 'day'),
  )

  const autoUpdate = ref(false)
  function changeAuto() {
    autoUpdate.value = !autoUpdate.value
  }

  let timer: any
  watch([() => showUpdateTime.value, () => autoUpdate.value], () => {
    if (showUpdateTime.value && autoUpdate.value) {
      updateData()
    } else {
      clearInterval(timer)
      timer = null
    }
  })

  function _updateData() {
    init(false)
    updateTime.value = dayjs().format('HH:mm:ss')
  }

  function updateData() {
    clearInterval(timer)
    _updateData()

    // 20秒
    timer = setInterval(_updateData, 20000)
  }

  onUnmounted(() => {
    clearInterval(timer)
  })

  return {
    updateTime,
    showUpdateTime,
    autoUpdate,
    changeAuto,
  }
}
