package com.engine.htsc.trip.util;

import weaver.general.BaseBean;
import weaver.general.GCONST;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志工具类
 */
public class LogUtil {

	static DateTimeFormatter newDf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	static BaseBean log = new BaseBean();
	private PrintWriter logPrint;
	private String logPath = "";
	private boolean systemLog = false;// 是否写系统日记

	public LogUtil() {

	}

	public LogUtil(String logPath, boolean systemLog) {
		this.logPath = logPath;
		this.systemLog = systemLog;
	}

	private String getLogFile() {
		// 获取当前系统路径
		String sysPath = GCONST.getRootPath();
		if (sysPath == null) {
			sysPath = System.getProperty("user.dir");
		}
		if (!"".equals(logPath)) {
			if (logPath.endsWith("/")) {
				sysPath += logPath + df.format(LocalDateTime.now()) + ".log";
			} else {
				sysPath += logPath + "/" + df.format(LocalDateTime.now()) + ".log";
			}
		} else {
			sysPath += "/debugLog/" + df.format(LocalDateTime.now()) + ".log";
		}
		return sysPath;
	}

	private void newLog() {
		String logFile = getLogFile();
		try {
			logPrint = new PrintWriter(new FileWriter(logFile, true), true);
		} catch (IOException e) {
			try {
				File file = new File(logFile);
				if (!file.getParentFile().exists()) {
					// 如果目标文件所在的目录不存在，则创建父目录
					if (file.getParentFile().mkdirs()) {
						boolean newFile = file.createNewFile();
					}
				}
				logPrint = new PrintWriter(new FileWriter(logFile, true), true);
			} catch (IOException ex) {
				log.writeLog("Log记录出错了", ex);
			}
		}
	}

	public void writeLog(Object msg) {
		if (systemLog) {
			log.writeLog(msg);
		}
		newLog();
		logPrint.println(newDf.format(LocalDateTime.now()) + ": " + msg);
		logPrint.flush();
		logPrint.close();
	}

	public void writeLog(String msg, Throwable e) {
		if (systemLog) {
			log.writeLog(msg, e);
		}
		newLog();
		logPrint.println(newDf.format(LocalDateTime.now()) + ": " + msg);
		e.printStackTrace(logPrint);
		logPrint.flush();
		logPrint.close();
	}

}
