//计算账号累计活跃时长
import setting from '@/mixins/theme.js'
import {timeOnPage , recordActiveLogin} from '@/api/api.js';
//活跃时间间隔 (s)
const TimeInterval = 60*10
//页面停留时间 (s)
let stayTime = 0


//活跃时间记录计时器 1分钟记录一次
let intervalTimer=null

export const openLoginTimer=()=>{

  clearInterval(intervalTimer)
  intervalTimer = setInterval(()=>{
    let ActiveTime=0
    if(localStorage.getItem('loginTime')){
      ActiveTime = (new Date()-new Date(localStorage.getItem('loginTime')))/1000
      console.log("间隔记录时长",ActiveTime+'s');
      recordActiveLogin({ActiveTime:Math.round(ActiveTime)}).then(res=>{
        if(res.Ret!==200) return
      })
    }
  },1000*60)
}

export const recordActiveLoginFun=(time)=>{
  let inactiveTime = time || new Date()
  let ActiveTime=0
  if(localStorage.getItem('loginTime')){
    ActiveTime = (inactiveTime-new Date(localStorage.getItem('loginTime')))/1000
    console.log("结束计算时长",ActiveTime+'s');
    recordActiveLogin({ActiveTime:Math.round(ActiveTime)}).then(res=>{
      if(res.Ret!==200) return
    }).finally(()=>{
      // 清除工作
      clearInterval(intervalTimer)
      // localStorage.removeItem('loginTime')
    })
  }
}

let timer = null

//打开计时器
export const optionTimeCalc = ()=>{
  const IsActive = sessionStorage.getItem('IsActive')
  // console.log(IsActive,'IsActive');
  if(Number(IsActive)===0){
    //console.log('打开计时器')
    sessionStorage.setItem('IsActive',1)
    timeStr = new Date().getTime()
    startCalc()
  }
  
}
//开始计时
export const startCalc = ()=>{
  sessionStorage.setItem('preTitle',document.title)
  timer = setInterval(()=>{
    stayTime++
    if(stayTime>=TimeInterval){
      endCalc('timeup',0)
    }
  },1000)
}

//结束计时
export const endCalc = (type,intervalT)=>{
  //console.log('关闭计时器')
  clearInterval(timer)
  const IsActive = sessionStorage.getItem('IsActive')
  if(Number(IsActive) && localStorage.getItem('auth')){
     sendTOPInfo(type,intervalT)
  }
  stayTime = 0
  /* if(type==='timeup'){
    sessionStorage.setItem('IsActive',0)
  } */
  timeStr = new Date().getTime()
  sessionStorage.setItem('IsActive',0)
}

// 退出登录时的结算
export const loginEndCalc=()=>{
  let t = new Date().getTime() - timeStr
  //console.log('待了时长replacestate：'+ t)
  const IsActive = sessionStorage.getItem('IsActive')
  if(Number(IsActive)){
    endCalc('logout',t)
  }
}

//发送活跃时长数据
export const sendTOPInfo = (type,intervalT)=>{
  //获取上一个页面标题
  const Title = sessionStorage.getItem('preTitle')
  //console.log('发送活跃时长数据 ↓↓↓')
  //获取计时间隔时间和页面名称
  if(type==='timeup'){
    console.table([{'停留时间(timeup)':stayTime+' s','停留页面':Title}])
  }else{
    console.table([{'停留时间(other)':Number(intervalT)/1000+' s','停留页面':Title,'触发类型':type}])
  }
  const Part = Title.split('-').length>1?Title.split('-')[1]:Title
  const ActiveTime = type==='timeup'?stayTime:Number(intervalT)/1000
  //发送数据
  if(!Part.length||Part==setting.name) return
  if(ActiveTime>TimeInterval*12) return
  console.log("ActiveTime:",ActiveTime,"Part:",Part)
  timeOnPage({
    ActiveTime:Math.round(ActiveTime),
    Part:Part
  }).then(res=>{
    if(res.Ret!==200) return
  })
}

//路由监听部分 
//source https://juejin.cn/post/6905913200060366862#heading-2


let timeStr=null
let rewriteHis = function(type){
  let origin = window.history[type]
  return function(){
    let rs = origin.apply(this, arguments)
    let e = new Event(type.toLocaleLowerCase())
    e.arguments = arguments
    window.dispatchEvent(e)
    return rs
  }
}

export function init(){
  // const unloadT = sessionStorage.getItem('unloadT')
  // console.log("init",unloadT,IsActive);
  // if(unloadT){
  //   //console.log('刷新该页呆了时长',unloadT)
  //   sessionStorage.removeItem('unloadT')
  //   sessionStorage.setItem('preTitle',document.title)
  //   if(Number(IsActive)){
  //     endCalc('unload',unloadT)
  //   }
  // }
  // timeStr = new Date().getTime()
  sessionStorage.setItem('IsActive',0)
  optionTimeCalc()
  // const IsActive = sessionStorage.getItem('IsActive')

  // if(Number(IsActive)){
  //   sessionStorage.setItem('unloadT',t)
  // }
  if(localStorage.getItem("loginTime") && localStorage.getItem('auth')){
    openLoginTimer()
  }
}

export const doPageEventListener=function(){

  // init() 放在router.afterEach中，不然一开始拿不到正确的页面标题

  window.history.pushState = rewriteHis('pushState')

  window.history.replaceState = rewriteHis('replaceState')

  //刷新加载完成 
  // 因为监听改位置了，每次路由刷新时，由于需要等待接口返回，需要先判断是否有 权限才能监听，这时候onload已经执行了，根本监听不到
  // window.addEventListener('load',(e)=>{
    // const unloadT = sessionStorage.getItem('unloadT')
    // const IsActive = sessionStorage.getItem('IsActive')
    // if(unloadT){
    //   //console.log('刷新该页呆了时长',unloadT)
    //   sessionStorage.removeItem('unloadT')
    //   sessionStorage.setItem('preTitle',document.title)
    //   if(Number(IsActive)){
    //     endCalc('unload',unloadT)
    //   }
    // }
    // timeStr = new Date().getTime()
    // optionTimeCalc()
  
    // if((!localStorage.getItem("loginTime")) && localStorage.getItem('auth')){
    //   // 初始化的时候 先重置最近登录时长
    //   recordActiveLogin({ActiveTime:0}).then(res=>{
    //     if(res.Ret!==200) return
    //   })
    //   openLoginTimer()
    // }
  // })
  //刷新离开页面
  window.addEventListener('beforeunload',(e)=>{
    console.log('beforeunload')
    let t = new Date().getTime() - timeStr
    // const unloadT = sessionStorage.getItem('unloadT')
    const IsActive = sessionStorage.getItem('IsActive')
    console.log("init",IsActive);
    // if(unloadT){
      //console.log('刷新该页呆了时长',unloadT)
      // sessionStorage.removeItem('unloadT')
      // sessionStorage.setItem('preTitle',document.title)
      if(Number(IsActive)){
        endCalc('unload',t)
      }
    // }
    // timeStr = new Date().getTime()
    // optionTimeCalc()
    // const IsActive = sessionStorage.getItem('IsActive')
    // if(Number(IsActive)){
      // sessionStorage.setItem('unloadT',t)
    // }
  })

  //刷新离开页面
  window.addEventListener('unload',(e)=>{
    console.log('unload')
    recordActiveLoginFun()
    // 猜测在unload这里 浏览器不会等待异步返回 清除工作在这进行
    clearInterval(intervalTimer)
    // localStorage.removeItem('loginTime')
  })

  //popstate会在router.before/afterEach 之前触发,所以这里不对计时操作,操作放到before/afterEach
  window.addEventListener('popstate',(e)=>{
    //console.log('popState',e)
    let t = new Date().getTime() - timeStr
    timeStr = new Date().getTime()
    //console.log('待了时长popstate：'+ t)
    sessionStorage.setItem('routerChangeType','popstate')
    sessionStorage.setItem('popStayTime',t)
  })
  
  window.addEventListener('pushstate',()=>{
    let t = new Date().getTime() - timeStr
    timeStr = new Date().getTime()
    //console.log('待了时长pushstate：'+ t)
    const IsActive = sessionStorage.getItem('IsActive')
    if(Number(IsActive)){
      endCalc('pushstate',t)
    }
    optionTimeCalc()
  })
  
  window.addEventListener('replacestate',()=>{
    let t = new Date().getTime() - timeStr
    timeStr = new Date().getTime()
    //console.log('待了时长replacestate：'+ t)
    const IsActive = sessionStorage.getItem('IsActive')
    if(Number(IsActive)){
      endCalc('replacestate',t)
    }
    optionTimeCalc()
  })
  
  document.addEventListener('click',(e)=>{

    //console.log('click',e,e.composedPath())
    //只计算displayMain 的click
    const path = e.composedPath()
    const contentIndex = path.findIndex((item)=>{return item.className==="content-container"})
    if(contentIndex===-1) return 
    //console.log('合法的click')
    const IsActive = sessionStorage.getItem('IsActive')
    console.log(IsActive,'IsActive');
    if(Number(IsActive)===0){
      optionTimeCalc()
    }else{
      //console.log('重置活跃计时')
      //重置活跃时间
      stayTime = 0
    }
  })
}




