package log

import (
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

func Init(debug bool, maxSize, maxBackups, maxAge int32, level string) {
	// 格式配置
	jsonConfig := zapcore.EncoderConfig{
		MessageKey:     "M",
		LevelKey:       "L",
		TimeKey:        "T",
		NameKey:        "N",
		CallerKey:      "C",
		FunctionKey:    zapcore.OmitKey,
		StacktraceKey:  "S",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeTime:     zapcore.TimeEncoderOfLayout("01-02 15:04:05.000"),
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
		EncodeName: func(loggerName string, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendString("[" + loggerName + "]")
		},
		ConsoleSeparator: " ",
	}

	// 日志输出到控制台和文件
	writeSyncer := []zapcore.WriteSyncer{zapcore.AddSync(os.Stdout)}
	if !debug {
		writeSyncer = append(writeSyncer, zapcore.AddSync(&lumberjack.Logger{
			Filename:   "./logs/log.log", // 日志文件位置
			MaxSize:    int(maxSize),     // 最大文件大小（MB）
			MaxBackups: int(maxBackups),  // 保留旧文件的最大个数
			MaxAge:     int(maxAge),      // 保留旧文件的最大天数
			Compress:   false,            // 是否压缩/归档旧文件
			LocalTime:  true,
		}))
	}

	var encoder zapcore.Encoder
	if debug {
		encoder = zapcore.NewConsoleEncoder(jsonConfig)
	} else {
		encoder = zapcore.NewJSONEncoder(jsonConfig)
	}
	logger := zap.New(zapcore.NewCore(
		encoder,
		zapcore.NewMultiWriteSyncer(writeSyncer...),
		zap.NewAtomicLevelAt(GetLogLevel(level)),
	))
	if debug {
		logger = logger.WithOptions(
			zap.AddCaller(),
			zap.AddCallerSkip(1),
			zap.AddStacktrace(zapcore.ErrorLevel),
		)
	}
	SetLogger(logger.Sugar())
}
