// 页面停留时长
// initstatistics()

import { NetManager } from "../../libs/tw/manager/NetManager";

let startTimer = new Date().getTime();
let endTimer;
//设置隐藏属性和改变可见属性的事件的名称
let hidden, visibilityChange;
if (typeof document.hidden !== 'undefined') {
    hidden = 'hidden';
    visibilityChange = 'visibilitychange';
} else if (typeof document['msHidden'] !== 'undefined') {
    hidden = 'msHidden';
    visibilityChange = 'msvisibilitychange';
} else if (typeof document['webkitHidden'] !== 'undefined') {
    hidden = 'webkitHidden';
    visibilityChange = 'webkitvisibilitychange';
}

const handleVisibilityChange = (e) => {
    if (document.visibilityState == "visible") {
        startTimer = new Date().getTime();
        console.log('starttimer', startTimer)
    }

    if (document.visibilityState == "hidden") {
        endTimer = new Date().getTime();
        console.log('endTimer', endTimer);
        sendData();
    }
};
const sendData = () => {
    const t0 = endTimer - startTimer;
    
    console.log('停留时间是', t0);
    if (localStorage.getItem('xxl_first_statistics') == null) {
        // NetManager.ins.remainDuration(t0, true);
        NetManager.ins.remainDurationProjectX(t0, true);
        localStorage.setItem('xxl_first_statistics', '1');
    } else {
        // NetManager.ins.remainDuration(t0, false);
        NetManager.ins.remainDurationProjectX(t0, false);
    }
};

export const initstatistics = () => {
    document.addEventListener(
        visibilityChange,
        handleVisibilityChange,
        false
    );

    document.body['onbeforeunload']=()=>{
        endTimer = new Date().getTime();
        return  sendData();
    }
};
