import { queryParams, windowVisibility, } from "./browser";
import { accessLog } from "./utils";

export let appID: string, channelType: string, projectID: string, isFromShare: boolean, newUser: boolean = true;

//appID提取
if (queryParams.appID) {
  appID = queryParams.appID;
} else if (CFG.appID) {
  appID = CFG.appID;
}

//渠道类型提取
if (queryParams.channelType) {
  channelType = queryParams.channelType;
}

//projectID提取
if (queryParams.projectID) {
  projectID = queryParams.projectID;
} else {
  const result = window.location.pathname.match(/\/projectx\/(.*?)\/.*?/);
  if (result) {
    projectID = result[1];
  }
}

//是否是分享回流
isFromShare = Object.prototype.hasOwnProperty.call(window, 'isFromShare') ? window['isFromShare'] : !!queryParams.is_from_share;

/**
 * 手动设置来自分享
 */
export function setFromShare() {
  isFromShare = true;
}

window['setFromShare'] = setFromShare

//新用户标记提取
function getNewUser() {
  if (!localStorage) {
    return
  }

  const key = 'nu_' + appID + '_' + projectID;
  const v = localStorage.getItem(key);
  if (v) {
    newUser = false;
  } else {
    localStorage.setItem(key, '1');
  }
}

getNewUser();

if (window['isSharePage']) {
  setTimeout(function () {
    accessLog(506);
  }, 100)
}

function dealPageRemainTime() {
  let startTimer = new Date().getTime();
  let endTimer: number;

  windowVisibility((visibility) => {
    if (visibility) {
      startTimer = new Date().getTime();
      //console.log('starttimer', startTimer)
    } else {
      endTimer = new Date().getTime();
      //console.log('endTimer', endTimer);
      sendData();
    }
  })

  const sendData = () => {
    const t0 = endTimer - startTimer;

    //console.log('duration', t0);

    accessLog(156, {
      remain: t0,
    });
  };

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

if (!window['stop_report_page_remain_time']) {
  dealPageRemainTime();
}
