import { useEffect } from 'react'
import useRequest from '@ahooksjs/use-request'

import { useLogin2p } from 'Login2p/Login2pContext'
import { MaterialService } from '../Material.service'

/**
 * 计时器
 */
const useTimeCount = (
  articleID: number,
  sourcePage: 'article' | 'report' | 'column',
  isOpenTimer: boolean, // 是否开启定时器（无权限时，不开启计时器）
  source?: number // 1:深度研究、2:本周研究汇总、3:上周纪要汇总
): {
  stopTime: number
  handleCountTime: () => void
  handleClearTime: () => void
  handleChangeVisibility: () => void
  handleFocus: () => void
  handleBlur: () => void
  handlebeforeunload: (e: BeforeUnloadEvent) => void
} => {
  let stopTime = 0
  let timmer: NodeJS.Timeout | null = null
  const login2p = useLogin2p()

  // 计时器
  const handleCountTime = () => {
    stopTime++
    timmer && clearTimeout(timmer)
    // 24小时就不计时了吧
    if (stopTime >= 86400) {
      return
    }
    timmer = setTimeout(() => {
      handleCountTime()
    }, 1000)
  }
  // 关闭计时器
  const handleClearTime = () => {
    if (stopTime === 0) return
    handleSourceApiChoose(stopTime)
    timmer && clearTimeout(timmer)
    timmer = null
    stopTime = 0
  }
  // 切换窗口时
  const handleChangeVisibility = () => {
    if (document.hidden) {
      handleClearTime()
    }
  }
  // 获取焦点时，开启计时器
  const handleFocus = () => {
    handleCountTime()
  }
  // 焦点失去时，关闭计时器
  const handleBlur = () => {
    handleClearTime()
  }
  // 关闭当前窗口
  const handlebeforeunload = (e: BeforeUnloadEvent) => {
    e.preventDefault()
    // e.returnValue = '' // 浏览器有可能不会提示这个信息，会按照固定信息提示
    handleClearTime()
  }
  const handleSourceApiChoose = (stopTime: number) => {
    if (!login2p.jwt) return
    if (stopTime === 0) return
    const fnObj = {
      article: () => {
        stopTime > 1 && applyReadTime(articleID, stopTime)
      },
      report: () => {
        articleID && stopTime > 1 && applyReportReadTime(articleID, stopTime, (source || 1) as number)
      },
      column: () => {
        stopTime > 1 && applyColumnReadTime(articleID, stopTime)
      }
    }
    fnObj[sourcePage]()
  }

  // 阅读时长存档 弘则报告、研选报告
  const { run: applyReadTime } = useRequest(MaterialService.postAddReadTime, {
    manual: true,
    formatResult: response => response.data.Data
  })
  // 阅读时长存档 1:深度研究、2:本周研究汇总、3:上周纪要汇总
  const { run: applyReportReadTime } = useRequest(MaterialService.postReadingTime, {
    manual: true,
    formatResult: response => response.data.Data
  })
  // 阅读时长存档 专栏
  const { run: applyColumnReadTime } = useRequest(MaterialService.postColumnClickRecord, {
    manual: true,
    formatResult: response => response.data.Data
  })

  useEffect(() => {
    if (isOpenTimer) {
      handleCountTime()
      document.addEventListener('visibilitychange', handleChangeVisibility, false)
      window.addEventListener('focus', handleFocus, false)
      window.addEventListener('blur', handleBlur, false)
      window.addEventListener('beforeunload', handlebeforeunload)

      return () => {
        handleClearTime()
        document.removeEventListener('visibilitychange', handleChangeVisibility, false)
        window.removeEventListener('focus', handleFocus, false)
        window.removeEventListener('blur', handleBlur, false)
        window.removeEventListener('beforeunload', handlebeforeunload)
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpenTimer, articleID])

  return {
    stopTime,
    handleCountTime,
    handleClearTime,
    handleChangeVisibility,
    handleFocus,
    handleBlur,
    handlebeforeunload
  }
}

export default useTimeCount
