import { App } from 'vue'
import router from '@/router/index'
import { setLog } from '@/apis/log'
import tokenInfo from '@/stores/modules/token'

// 使用时间戳精确计算页面停留时间，避免间隔计时带来的误差
let pageEnterAt = 0;
const resetEnterTime = () => { pageEnterAt = Date.now(); };
const getStaySeconds = () => Math.max(0, Math.round((Date.now() - pageEnterAt) / 1000));

export function setLogInfo(router: any, describe: any,type = 5) {
  setLog({
    page: router.meta.title,
    page_url: router.fullPath,
    describe: describe,
    type,
  });

  resetEnterTime();
}

export function setLogInfoHide(router: any, describe: any) {
  setLog({
    page: router.meta.title,
    page_url: router.fullPath,
    describe: describe,
    time: getStaySeconds(),
    type: 3
  });
}

// 停留
export function setLogInfoRemain(router: any) {
  setLog({
    page: router.meta.title,
    page_url: router.fullPath,
    describe: {
      action: '停留' + router.meta.title + '10s',
      query: { ...router.query, ...router.params }
    },
    time: getStaySeconds(),
    type: 6
  });
}

/*
* 埋点--操作
*/
export function lissenLog(app: App) {
  function log(el: HTMLElement, binding: any, thisRoute = router.currentRoute.value) {
    return function(e: Event) {
      e.stopPropagation();
      let log = binding.value;
      if (!log) {
        try {
          log = JSON.parse(el.getAttribute('log') || '{}');
        } catch (e) {
          log = {};
        }
      }

      setLog({
        page: thisRoute.meta.title,
        page_url: thisRoute.fullPath,
        describe: log.describe,
        type: 5,
      });
    }
  }

  /*
  * 获取具体参数，传参数到后台，
  * 因为vue3.0中用了vue2.0的写法，在v-log中，数据无法响应式,故部分log信息 会绑定到dom的log下
  */
  /* 绑定 v-log 事件 默认为click */
  app.directive('log', {
    mounted(el: HTMLElement, binding: any) {
      el.addEventListener('click', log(el, binding));
    },
    unmounted(el: HTMLElement, binding: any) {
      el.removeEventListener('click', log(el, binding));
    }
  });
}

/*埋点 点击*/
export async function clickLog(describe: any, route?: any, type = 5) {
  const currentRoute = router.currentRoute.value;
  const page = route?.meta?.title || currentRoute?.meta?.title;
  const page_url = route?.path || currentRoute?.fullPath;

  await setLog({
    page,
    page_url,
    describe: describe,
    type,
  });
}

/*
* 埋点--进入页面
*/
export function log(router: any) {
  console.log('注册路由监听器...'); // 调试信息

  // 确保router对象存在
  if (!router) {
    console.error('Router对象不存在');
    return;
  }

  // 检查router.afterEach方法是否存在
  if (typeof router.afterEach !== 'function') {
    console.error('router.afterEach方法不存在');
    return;
  }

  router.afterEach((to: any, from: any) => {
    console.log('路由变化:', {
      from: from?.path || 'null',
      to: to?.path || 'null',
      toMeta: to?.meta,
      fromMeta: from?.meta
    }); // 调试信息

    /*
    * 第一次 进入页面
    */
    const tokenStore = tokenInfo();
    const hasToken = tokenStore.getToken;

    let this_to = {
      ...to,
      ...{},
    };
    let this_from = {
      ...from,
      ...{},
    };

    // 离开页面埋点 - 排除重定向情况
    if(from && from.path !== '/' && from.meta?.log !== false && from.meta?.title){
      console.log('离开页面埋点:', from.meta.title); // 调试信息
      setLogInfoHide(this_from, {
        action: '离开' + this_from.meta.title,
        query: { ...from.query, ...from.params }
      });
    }

    // 进入页面埋点 - 排除根路径和重定向
    if (to.path !== '/' && to.meta?.log !== false && to.meta?.title) {
      console.log('进入页面埋点:', to.meta.title); // 调试信息
      setLogInfo(this_to, {
        action: '进入' + this_to.meta.title,
        query: { ...to.query, ...to.params }
      },1);
    }
  });

  console.log('路由监听器注册完成'); // 调试信息
}

// 测试函数 - 用于验证路由监听是否工作
export function testLogFunction() {
  console.log('测试埋点函数被调用');
  setLog({
    page: '测试页面',
    page_url: '/test',
    describe: { action: '测试埋点' }
  });
}
