reportTrackFunMixin.js 4.55 KB
import { util } from 'utils'
import api from '../api/baseApi'
export default {
  data() {
    return {
      prePagePath: '',
      track_timerFlag: false,
      track_batchId: null,
      track_page_view_flag: false,
      track_timer_out: null
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.prePagePath = from.path
    })
  },
  computed: {
    loginAccount() {
      return this.$store.state.d2admin.user.info.loginAccount
    }
  },

  methods: {
    /**
     *
     * @param {动作类型} eventType
     * @param {事件别名} eventCode
     * @param {业务参数} businessParam
     * @param {浏览批次id} batchId
     */
    setReportTrackData(eventType, eventCode = '', businessParam = '', batchId = '') {
      let recordList = localStorage.getItem('recordList')
      const route = this.$route

      const userInfo = util.getLocalStorage('ww_userInfo')
      let { prePagePath } = this
      const item = {
        loginAccount: userInfo.phone || '',
        systemSource: 10,
        eventTime: util.dateFormate(Date.now(), 'YYYY-MM-DD HH:mm:ss'),
        eventType,
        pagePath: route?.path || ''
      }
      if (!prePagePath) prePagePath = this.getPrePagePath(this)
      item.prePagePath = prePagePath || '/index'
      if (batchId) item.batchId = batchId
      if (eventCode) item.eventCode = eventCode
      if (businessParam) item.businessParam = JSON.stringify(businessParam)
      if (!recordList) recordList = [item]
      else {
        recordList = JSON.parse(recordList)
        recordList.push(item)
      }
      localStorage.setItem('recordList', JSON.stringify(recordList))
      if (!window.TRACK_TIMER) {
        console.log('---------------- 重新打开定时埋点 ----------------')
        this.sendTrack() //开启定时埋点
      }
      if (recordList.length > 9) this.sendTrackData()
    },
    getRandomString(length = 30) {
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      let result = ''
      for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length))
      }
      return result
    },
    onPageShow() {
      if (this.track_page_view_flag) return
      if (!this.track_batchId) {
        this.track_batchId = `DJ_${this.getRandomString()}_${Date.now()}`
      }
      this.track_timerFlag = true
      this.track_page_view_flag = true
      if (this.track_timer_out) {
        clearTimeout(this.track_timer_out)
        this.track_timer_out = null
      }
      setTimeout(() => {
        this.setBrowseTrackData()
      }, 300)
    },
    onPageHide() {
      this.track_timerFlag = false
      this.track_batchId = null
      this.track_page_view_flag = false
      clearTimeout(this.track_timer_out)
      this.track_timer_out = null
    },
    setBrowseTrackData() {
      try {
        // || (this.$route.path != "/qualityControlList" && this.$route.path != "/shopConfig")
        if (!this.track_timerFlag && !this.track_event_code) {
          //无eventcode时不上报
          return
        } else {
          this.track_timer_out = setTimeout(() => {
            this.setBrowseTrackData()
          }, 10e3)
        }
        let trackParams = {}
        if (this.track_businessParam_key) trackParams = this[this.track_businessParam_key] || {}
        this.setReportTrackData(2, this.track_event_code, trackParams, this.track_batchId)
      } catch (error) {
        console.log(error)
      }
    },
    getPrePagePath(_this) {
      let current = _this
      const visited = new Set()

      while (current) {
        if (visited.has(current)) {
          // 防止无限循环
          console.error('Detected circular reference in parent chain')
          return ''
        }
        visited.add(current)

        if (current.$parent && current.$parent.prePagePath) {
          return current.$parent.prePagePath
        }

        current = current.$parent
      }

      return ''
    },
    sendTrackData() {
      let recordList = localStorage.getItem('recordList')
      if (recordList && recordList.length) {
        api
          .reportTrack({
            recordList: JSON.parse(recordList)
          })
          .then(res => {
            if (res) localStorage.removeItem('recordList')
          })
      } else {
        clearInterval(window.TRACK_TIMER)
        window.TRACK_TIMER = null
        console.log('---------------- 暂停定时埋点 ----------------')
      }
    },

    /** 定时发送埋点数据 */
    sendTrack() {
      window.TRACK_TIMER = setInterval(() => {
        this.sendTrackData()
      }, 30e3)
    }
  }
}