import { effectScope, onScopeDispose, watch } from 'vue'
import uesFetch from '@/hooks/useFetch'
import useMainStore from '@/store/main'
import { useRouter } from 'vue-router'
import { sessionStorage } from '@/plugins/storage'

import type { EffectScope, ShallowRef } from 'vue'
import type { ExtractApiResponse } from '@/api/api'

interface Msg {
  newCount: number
  messages: any[]
}

export const lastMsgs: Msg = {
  newCount: 0,
  messages: [],
}
export const setLastMsgs = (res: Msg) => {
  lastMsgs.newCount = res.newCount
  lastMsgs.messages = res.messages
}

const useMessageLoop = () => {
  const mainStore = useMainStore()
  const router = useRouter()

  const { fetch: getUnReadMessage, result: unReadMessage, cancel } = uesFetch('getUnReadMessage')

  let timer: number | null = null

  const cleanTimer = () => {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }
  }

  const getUnReadMessageFn = async () => {
    let seconds = 10
    try {
      if (sessionStorage.get('LOGIN_RESULT')) {
        await getUnReadMessage()
      } else {
        cleanTimer()
        return
      }
    } catch (err: any) {
      // if (err.response.status == 401) {
      //   cleanTimer()
      //   sessionStorage.remove('LOGIN_RESULT')
      //   router.replace({ name: 'Login' })
      //   return
      // } else {
      seconds = 30
      // }
    }
    cleanTimer()
    timer = window.setTimeout(getUnReadMessageFn, seconds * 1000)
  }
  watch(
    () => unReadMessage.value,
    (val: Msg) => {
      mainStore.setNewMsgs(val)
    }
  )
  watch(
    () => mainStore?.myUserInfo?.role,
    () => {
      if (mainStore?.myUserInfo?.role && mainStore?.myUserInfo?.role !== 'ADMIN') {
        getUnReadMessageFn()
      }
    },
    {
      immediate: true,
    }
  )

  onScopeDispose(cleanTimer)

  return unReadMessage
}

function createSharedComposable(composable: typeof useMessageLoop) {
  let subscribers = 0
  let state: ShallowRef<ExtractApiResponse<'getUnReadMessage'>> | null | undefined
  let scope: EffectScope | null

  const dispose = () => {
    if (scope && --subscribers <= 0) {
      scope.stop()
      state = scope = null
    }
  }

  return () => {
    subscribers++
    if (!state) {
      scope = effectScope(true)
      state = scope.run<ShallowRef<ExtractApiResponse<'getUnReadMessage'>>>(composable)
    }
    onScopeDispose(dispose)
    return state
  }
}

export default createSharedComposable(useMessageLoop)
