analysis.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { createBrowseHistory, createBrowseRecord } from '@/core/libs/requests'
  2. import { useUserStore } from '@/store'
  3. import { storeToRefs } from 'pinia'
  4. import dayjs from 'dayjs'
  5. export enum AnalysisEventType {
  6. LaunchApp = 4,
  7. /**
  8. * 发布圈子
  9. */
  10. PublishCircle = 5,
  11. /**
  12. * 浏览页面
  13. */
  14. ViewPage = 6,
  15. }
  16. export const useAnalysis = (automatic: boolean, isApp = false) => {
  17. const userStore = useUserStore()
  18. const { userInfo, isLogined } = storeToRefs(userStore)
  19. const viewDuration = ref(0)
  20. const viewStartAt = ref<Date | null>(null);
  21. const totalUsageTime = ref(0);
  22. const option = ref<Record<string, any>>({})
  23. const report = async (type) => {
  24. if (!isLogined.value) return
  25. const duration = automatic
  26. ? (viewDuration.value = dayjs().diff(viewStartAt.value, 'second'))
  27. : 0
  28. await createBrowseRecord({
  29. stylistId: userInfo.value.userId,
  30. bizType: type,
  31. duration,
  32. ...option.value,
  33. })
  34. viewDuration.value = 0
  35. viewStartAt.value = undefined
  36. option.value = {}
  37. }
  38. onLaunch(async () => {
  39. if (automatic) {
  40. if (isApp) {
  41. await report(AnalysisEventType.LaunchApp)
  42. }
  43. }
  44. })
  45. onLoad(() => {
  46. console.log('analysis')
  47. })
  48. onShow(() => {
  49. console.log('show')
  50. if (automatic) {
  51. viewStartAt.value = new Date()
  52. // if (isApp) {
  53. //
  54. // }
  55. }
  56. })
  57. onHide(async () => {
  58. if (automatic && viewStartAt.value) {
  59. const usageTime = dayjs().diff(viewStartAt.value, 'second'); // 本次使用时长(秒)
  60. totalUsageTime.value += usageTime; // 累计到总时长
  61. console.log(`本次使用时长:${usageTime} 秒`);
  62. console.log(`累计使用时长:${totalUsageTime.value} 秒`);
  63. await report(AnalysisEventType.ViewPage); // 上报页面浏览记录
  64. }
  65. })
  66. onUnload(async () => {
  67. // if (automatic) {
  68. // await report(AnalysisEventType.ViewPage)
  69. // }
  70. })
  71. return { option, report }
  72. }