const log4js = require("log4js");
const moment = require("moment");
const fs = require("fs");
const path = require("path");

export function returnLogFilePath() {
  const today = moment(new Date()).format("YYYY-MM-DD");
  const low_path = process.cwd();
  let log_dir = path.join(low_path, "logs");
  if (!fs.existsSync(log_dir)) {
    fs.mkdirSync(log_dir); // 创建日志文件夹
  }
  const dir = path.join(low_path, `/logs/${today}`);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
  }
  return path.join(dir, "api.log");
}

//日志对象
const logger = (name) => {
  const logFilePath = returnLogFilePath();
  log4js.configure({
    appenders: {
      out: { type: "console" }, //在控制台输出日志
      cheese: {
        type: "file",
        filename: logFilePath,
        maxLogSize: 1024 * 1000 * 10, //10M
      },
    },
    categories: {
      //需要在控制台输出日志时：appenders: ['cheese', 'out']
      default: { appenders: ["cheese"], level: log4js.levels.DEBUG },
    },
  });
  return log4js.getLogger(name);
};

//添加日志
const addFormatLog = function(req, res, data) {
  const now = new Date();
  const resTime = now - req._startTime;

  const token = req.headers["jwt-token"];
  const {
    ip,
    headers,
    method,
    url,
    body,
    httpVersion,
    res: { statusCode, _headers },
  } = req;
  let logInfo = {
    ip,
    host: headers.host,
    resTime,
    method,
    url,
    token,
    body,
    httpVersion,
    statusCode,
    contentLength: _headers["content-length"],
    userAgent: headers["user-agent"],
    data: data[0],
  };
  // ${JSON.stringify(logInfo)}
  logger("log").info(` 
    时间：${moment(new Date()).format("YYYY-MM-DD HH:mm:ss")}
    ip : ${logInfo.ip}
    host : ${logInfo.host}
    响应时间 : ${logInfo.resTime / 1000} s 
    method ：${logInfo.method}
    url ：${logInfo.url} 
    token ：${logInfo.token || ""}
    body ：${JSON.stringify(logInfo.body)}
    状态码 ：${logInfo.statusCode}
    data ：${JSON.stringify(logInfo.data)} 
   `);
};

//日志中间件
export const logMiddleWare = () => {
  return function(req, res, next) {
    req._startTime = new Date();

    const oldSend = res.send;
    res.send = function() {
      oldSend.apply(res, arguments);
      if (typeof [...arguments][0] === "object") {
        res.once("finish", () => addFormatLog(req, res, arguments));
      }
    };

    return next();
  };
};
