import { createBrowseHistory, createBrowseRecord } from '@/core/libs/requests'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import dayjs from 'dayjs'

export enum AnalysisEventType {
  LaunchApp = 4,
  /**
   * 发布圈子
   */
  PublishCircle = 5,
  /**
   * 浏览页面
   */
  ViewPage = 3,
}
export const useAnalysis = (automatic: boolean, isApp = false) => {
  const userStore = useUserStore()
  const { userInfo, isLogined } = storeToRefs(userStore)
  const viewDuration = ref(0)
  const viewStartAt = ref<Date>()
  const option = ref<Record<string, any>>({})

  const report = async (type) => {
    if (!isLogined.value) return
    const duration = automatic
      ? (viewDuration.value = dayjs().diff(viewStartAt.value, 'second'))
      : 0

    await createBrowseRecord({
      stylistId: userInfo.value.userId,
      bizType: type,
      duration,
      ...option.value,
    })
    viewDuration.value = 0
    viewStartAt.value = undefined
    option.value = {}
  }

  onLaunch(async () => {
    // if (automatic && isLogined) {
    //   await createBrowseRecord({
    //     stylistId: userInfo.value.userId,
    //     bizType: AnalysisEventType.LaunchApp,
    //     duration: 1,
    //   })
    // }
  })
  onLoad(() => {
    console.log('analysis')
  })
  onShow(() => {
    console.log('show')
    if (automatic) {
      viewStartAt.value = new Date()
      // if (isApp) {
      //
      // }
    }
  })
  onHide(async () => {
    if (automatic) {
      if (isApp) {
        await report(AnalysisEventType.LaunchApp)
      }
    }
  })
  onUnload(async () => {
    if (automatic) {
      await report(AnalysisEventType.ViewPage)
    }
  })
  return { option, report }
}
