import "@/utils/loghub-tracking.js";
import { VUE_APP_SLS_STORE_NAME } from "@/constants/constants";
import moment from "moment";
import getDeviceInfos from "./deviceInfo";

const host = "cn-shenzhen.log.aliyuncs.com";
const project = "examcloud";
const logstore = VUE_APP_SLS_STORE_NAME;
const logger = new window.Tracker(`${host}`, `${project}`, `${logstore}`);
// logger.push("customer", "zhangsan");
// logger.push("product", "iphone 6s");
// logger.push("price", 5500);
// logger.logger();
// logger.push("customer", "lisi");
// logger.push("product", "ipod");
// logger.push("price", 3000);
// logger.logger();

// 封装logger
// 注意没有 window.Tracker 的情况

import store from "@/store";

// console.log(store);
// console.log(store.state.user);

// export function createNoAuthLog(logs) {
//   for (let [k, v] of Object.entries(logs)) {
//     logger.push(k, v);
//   }
//   logger.logger();
// }

// ip 定位?
// 要在用户登录后调用
export function createUserDetailLog(logs) {
  try {
    const user = store.state.user;
    logger.push("userName", user.displayName);
    logger.push("userId", user.id);
    logger.push("userIdentityNumber", user.identityNumber);
    logger.push("userStudentCodeList", user.studentCodeList.join(","));
    logger.push("rootOrgName", user.rootOrgName);
    logger.push("rootOrgId", user.rootOrgId);
    const uuidForEcs = localStorage.getItem("uuidForEcs");
    if (uuidForEcs) {
      logger.push("uuidForEcs", uuidForEcs);
    }
    for (let [k, v] of Object.entries(logs)) {
      logger.push(k, v);
    }
    const deviceInfos = getDeviceInfos();

    for (let [k, v] of Object.entries(deviceInfos)) {
      logger.push(k, v);
    }
    logger.push("clientDate", moment().format("YYYY-MM-DD HH:mm:ss.SSS"));
    logger.push("UA", navigator.userAgent);
    logger.logger();
  } catch (error) {
    console.log(error);
    window._hmt.push(["_trackEvent", "创建用户日志出错-1"]);
  }
}

export function createLog(logs) {
  try {
    const user = store.state.user;
    const uuidForEcs = localStorage.getItem("uuidForEcs");
    if (uuidForEcs) {
      logger.push("uuidForEcs", uuidForEcs);
    }
    if (user) {
      logger.push("userId", user.id);
    }
    for (let [k, v] of Object.entries(logs)) {
      logger.push(k, v);
    }
    logger.push("clientDate", moment().format("YYYY-MM-DD HH:mm:ss.SSS"));
    logger.logger();
  } catch (error) {
    console.log(error);
    window._hmt.push(["_trackEvent", "创建用户日志出错-2"]);
  }
}

export function createEncryptLog() {
  const isElectron = typeof nodeRequire != "undefined";
  // 非 electron 返回
  if (!isElectron) return;

  try {
    const user = store.state.user;
    const uuidForEcs = localStorage.getItem("uuidForEcs");
    if (uuidForEcs) {
      logger.push("uuidForEcs", uuidForEcs);
    } else {
      // 没有 uuidForEcs 日志没法查询
      return;
    }
    if (user) {
      logger.push("userId", user.id);
    }

    let log = null;
    try {
      let lastLogIndex = (localStorage.getItem("lastLogIndex") || 0) - 0;
      log = window.nodeRequire("electron-log");
      // const filePath = log.getFile().path;
      const filePath = log.transports.file.findLogPath();
      const fs = window.nodeRequire("fs");
      const content = fs.readFileSync(filePath, "utf-8");
      const ary = content.toString().split("\r\n").join("\n").split("\n");
      // 重复上传没有时间的行：跨过非时间戳的行; 错误识别：全部重新执行
      // let lastIndex = ary.findIndex(v => v === lastLog);
      // console.log({ lastIndex });
      if (ary.length < lastLogIndex) {
        lastLogIndex = 0;
      }

      let logLen = 10;
      const newAry = ary
        .slice(lastLogIndex, lastLogIndex + logLen)
        .filter((v) => v);
      // 如果没有上传的内容，则不修改lastLog, 也不上传
      if (!newAry.length) return;
      lastLogIndex = lastLogIndex + newAry.length;

      localStorage.setItem("lastLogIndex", lastLogIndex);
      logger.push("encryptLog", newAry.join("\n"));
    } catch (error) {
      console.debug(error);
      return;
    }

    logger.push("clientDate", moment().format("YYYY-MM-DD HH:mm:ss.SSS"));
    logger.logger();
  } catch (error) {
    console.log(error);
    window._hmt.push(["_trackEvent", "创建用户日志出错-3"]);
  }
}

// const postLog = body => {
//   const headers = new Headers();
//   headers.append("x-log-apiversion", "0.6.0");

//   fetch(`https://${project}.${host}/logstores/${logstore}`, {
//     method: "post",
//     headers,
//     body,
//   });
// };

// export function createEncryptLog() {
//   try {
//     const user = store.state.user;
//     const uuidForEcs = localStorage.getItem("uuidForEcs");
//     const singleLog = {};
//     const __logs__ = [singleLog];
//     if (uuidForEcs) {
//       singleLog.uuidForEcs = uuidForEcs;
//     } else {
//       // 没有 uuidForEcs 日志没法查询
//       return;
//     }
//     if (user) {
//       singleLog.userId = user.id;
//     }
//     const isElectron = typeof nodeRequire != "undefined";
//     let log = null;
//     if (isElectron) {
//       try {
//         log = window.nodeRequire("electron-log");
//         // const filePath = log.getFile().path;
//         const filePath = log.transports.file.findLogPath();
//         const fs = window.nodeRequire("fs");
//         const encryptLog = fs.readFileSync(filePath, "utf-8");
//         singleLog.encryptLog = encryptLog;

//         postLog(JSON.stringify({ __logs__ }));
//       } catch (error) {
//         console.debug(error);
//         return;
//       }
//     }
//     singleLog.clientDate = moment().format("HH:mm:ss.SSS");
//     postLog(__logs__);
//   } catch (error) {
//     console.log(error);
//     window._hmt.push(["_trackEvent", "创建用户日志出错-3"]);
//   }
// }
