/** 该文件是用于处理日志文件的类
 * 等级为:
  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 measure_temp = null;
var measure_volts = 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 }) => {
      if (process.platform == "win32") {
        return `${moment().format(
            'YYYY-MM-DD HH:mm:ss.SSS'
        )} [${level}]: ${message}`;
      } else {
        if (level == 'SEAT' && (measure_temp || measure_volts)) {
          return `${moment().format(
              'YYYY-MM-DD HH:mm:ss.SSS'
          )} [${level}][${measure_temp},${measure_volts}]: ${message}`;
        } else {
          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, aes: -2 }, 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,
    });
  },
  d(log) {
    logger.DEBUG(log);
  },
  v(log) {
    logger.VERBOSE(log);
  },
  i(log) {
    logger.INFO(log);
  },
  w(log) {
    logger.WARN(log);
  },
  e(log) {
    logger.ERROR(log);
  },
  seat: function (log) {
    if (process.platform == "linux") {
      const process = require('child_process');
      process.exec('lsb_release -a',function (error, stdout) {
        if (error !== null) {
          console.log('查询系统版本脚本出错:' + error)
        } else {
          if (stdout.search("Raspbian") !== -1) {
            KtLog.getRaspberryPiTemp();
            KtLog.getRaspberryPiVolts();
          }
        }
      })
    }
    logger.log('SEAT', log);
  },
  aes(log) {
    const moment = require('moment');
    logger.log('AES', KtLog.encrypt(log, 'keytop7012345689keytop7012345689', moment().format('YYYY-MM-DD HH:mm')));
  },
  /**
   * AES-256-CBC 加密函数
   * @param text 加密的文本
   * @param key 密钥 默认：keytop7012345689keytop7012345689
   * @param iv 初始化向量 默认：输出日期（年-月-日 时:分）
   * @returns {*} 密文编码，base64
   */
  encrypt: function(text, key, iv) {
    const CryptoJS = require('crypto-js');
    const encrypted = CryptoJS.AES.encrypt(text, CryptoJS.enc.Utf8.parse(key), {
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC, // 加密模式
      padding: CryptoJS.pad.Pkcs7 // 填充方式
    });
    return encrypted.toString();
  },
  /**
   * 获取当前树莓派系统温度
   */
  getRaspberryPiTemp: function () {
    const process = require('child_process');
    process.exec('vcgencmd measure_temp',
        function (error, stdout) {
          if (error !== null) {
            console.log('获取当前树莓派系统温度出错:' + error);
          } else {
            measure_temp = stdout.replace('temp=','').replace(/[\r\n]/g,"");
          }
        })
  },
  /**
   * 获取当前树莓派系统电压
   */
  getRaspberryPiVolts: function () {
    const process = require('child_process');
    process.exec('for id in core sdram_c sdram_i sdram_p; do echo "$(vcgencmd measure_volts $id)";done',
        function (error, stdout) {
          if (error !== null) {
            console.log('获取当前树莓派系统电压出错:' + error);
          } else {
            measure_volts = stdout.replace(/volt=/g,'').split(/[\r\n]/g,4);
          }
        })
  }
};

module.exports = KtLog;
