package com.m2pool.lease.aspect;

import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 用户账本日志服务类
 */
@Service
public class LedgerLogService {
    private static final String LOG_DIR = "/home/ubuntu/web/logs/ledger/";
    private static final DateTimeFormatter MONTH_FORMAT = DateTimeFormatter.ofPattern("yyyyMM");

    public void logOperation(String tag, String operation, String content) {
        String month = LocalDate.now().format(MONTH_FORMAT);
        String fileName = String.format("%s%s_%s.log", LOG_DIR, tag, month);

        try {
            Files.createDirectories(Paths.get(LOG_DIR));
            String logEntry = String.format("[%s] %s: %s%n",
                LocalDateTime.now(), operation, content);
            Files.write(Paths.get(fileName),
                logEntry.getBytes(StandardCharsets.UTF_8),
                StandardOpenOption.CREATE,
                StandardOpenOption.APPEND);
        } catch (IOException e) {
            System.out.println("创建用户日志文件失败"+e.getMessage());
        }
    }
}
