import { reportDataApi } from '@/api/statistic/index'

export const REPORT_TYPES = {
  ONLINE_COURSE: '在线课程',
  LIVE_TEACHING: '教学直播',
  MOCK_EXAMINATION: '模拟考试',
  ERROR_CONSOLIDATION: '错题巩固',
  CLASS_NOTE: '课堂笔记',
  ONLINE_FAQ: '在线答疑',
  RESOURCE_VIEW: '资源查看',
  SYSTEM_USE: '系统使用'
}

/**
 * 数据上报 mixin
 *
 * @param {[keyof REPORT_TYPES]} type 上报类型
 *
 * @param {Object} options 方法
 * @param {boolean} options.isListenerUnload 是否弹出关闭页面提示框
 * @param {()=>boolean} options.isCancelReport 是否取消上报
 * @param {()=>{ id?:number, field01?:string, field02?:string, field03?:string, remarks?:string }} options.handleReportData 处理上报数据
 * field01 备用字段
 * field02 备用字段
 * field03 备用字段
 * remarks 备注说明
 *
 * @returns
 */
export function dataReportMixin (type, { isListenerUnload, ...methods } = {}) {
  if (!type) throw Error('上报类型错误')

  return {
    mounted () {
      if (this.isCancelReport?.()) return console.warn('上报已中断，上报数据：', type)

      this.reportData()
      if (isListenerUnload) window.addEventListener('beforeunload', this.reportData)
    },

    beforeDestroy () {
      if (isListenerUnload) window.removeEventListener('beforeunload', this.reportData)
      this.reportData()
    },

    methods: {
      ...methods,

      async reportData (e) {
        e && (e.returnValue = '将要退出，是否继续？')

        reportDataApi({ ...this.handleReportData?.(), id: this.__report_data_id__, type })
          .then(({ data }) => (this.__report_data_id__ = data))
      }
    }
  }
}
