/** 该文件是用于处理日志文件的类 
 * 等级为: 
  error: 0, 
  warn: 1, 
  info: 2, 
  verbose: 3, 
  debug: 4, 
  silly: 5 
 * 
*/

var temp = '';
var realLog = '';
var pointLog = '';
var logPath = 'log/';
var names = '';
var logger = null;
var KtLog = {
  init(appName, filePath, isDebug) {
    if (Object.prototype.toString.call(isDebug) != '[object Boolean]') {
      isDebug = false;
    }
    if (appName == '') {
      names = 'unknow';
    } else {
      names = appName;
    }
    if (filePath != '') {
      logPath = filePath;
    }
    namesCurrent = names;
    filePathCurrent = logPath;
    const { createLogger, format, transports } = require('winston');
    const winston = require('winston');
    const moment = require('moment');
    require('winston-daily-rotate-file');
    const { combine, timestamp, label, printf } = format;
    const myFormat = printf(({ level, message, timestamp }) => {
      return `${moment().format(
        'YYYY-MM-DD HH:mm:ss.SSS'
      )} [${level}]: ${message}`;
    });
    const dailyRotateTransport = new winston.transports.DailyRotateFile({
      dirname: logPath,
      filename: `${names}-%DATE%.log`,
      datePattern: 'YYYY-MM-DD',
      level: 'VERBOSE',
      // zippedArchive: false,
      // maxSize: '20m',
      // maxFiles: '14d'
    });
    //"{"emerg":0,"alert":1,"crit":2,"error":3,"warning":4,"notice":5,"info":6,"debug":7}"
    //"{"seat":-1,"error":0,"warn":1,"info":2,"http":3,"verbose":4,"debug":5,"silly":6}"
    const levels = Object.assign({ seat: -1 }, winston.config.npm.levels);
    for (var level in levels) {
      levels[level.toUpperCase()] = levels[level];
      delete levels[level];
    }
    let transportsArray = [dailyRotateTransport]; //new transports.File({ filename: logPath + names + "-" + moment().format("YYYY-MM-DD") + '.log', level: 'VERBOSE' })
    if (isDebug) {
      transportsArray.push(new transports.Console({ level: 'DEBUG' }));
    }
    logger = createLogger({
      levels: levels,
      format: combine(timestamp(), myFormat),
      transports: transportsArray,
    });
  },
  checkLogRepeat(log) {
    if (log == temp) {
      pointLog = pointLog + '.';
      return false;
    } else {
      if (pointLog != '') {
        logger.INFO(pointLog);
      }
      temp = log;
      realLog = log;
      pointLog = '';
      return true;
    }
  },
  d(log) {
    logger.DEBUG(log);
  },
  v(log) {
    if (KtLog.checkLogRepeat(log)) {
      logger.VERBOSE(realLog);
    } else {
      logger.DEBUG(log);
    }
  },
  i(log) {
    if (KtLog.checkLogRepeat(log)) {
      logger.INFO(realLog);
    } else {
      logger.DEBUG(log);
    }
  },
  w(log) {
    if (KtLog.checkLogRepeat(log)) {
      logger.WARN(realLog);
    } else {
      logger.DEBUG(log);
    }
  },
  e(log) {
    if (KtLog.checkLogRepeat(log)) {
      logger.ERROR(realLog);
    } else {
      logger.DEBUG(log);
    }
  },
  seat: function (log) {
    logger.log('SEAT', log);
  },
};

module.exports = KtLog;
