package org.jebot.util;

import cn.hutool.core.date.DateUtil;
import org.jebot.models.jebot.BotAccountBookHistory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

public class ImageUtil {

    public static void generateTableImage(Font chineseFont , List<BotAccountBookHistory> bookHistories, String outputPath) throws Exception {
        int rowHeight = 30;
        int tableWidth = 800;
        int tableHeight = (bookHistories.size() + 1) * rowHeight + 20;

        BufferedImage image = new BufferedImage(tableWidth, tableHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置背景颜色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, tableWidth, tableHeight);

        if (chineseFont==null){
            // 设置字体
            g2d.setFont(new Font("SansSerif", Font.PLAIN, 16));
            g2d.setColor(Color.BLACK);

        }else{
            // 设置字体
            g2d.setFont(chineseFont);
            g2d.setColor(Color.BLACK);
        }


        // 绘制表头
        String[] headers = {"金额", "更新前余额", "更新后余额", "更新时间", "更新人"};
        int[] columnWidths = {100, 150, 150, 250, 150};
        int x = 10;
        int y = 30;

        for (int i = 0; i < headers.length; i++) {
            g2d.drawString(headers[i], x, y);
            x += columnWidths[i];
        }

        // 绘制表格内容
        y += rowHeight;
        for (BotAccountBookHistory bookHistory : bookHistories) {
            x = 10;
            g2d.drawString(String.format("%.2f", bookHistory.getAmount()), x, y);
            x += columnWidths[0];
            g2d.drawString(String.format("%.2f", bookHistory.getBeforeBalance()), x, y);
            x += columnWidths[1];
            g2d.drawString(String.format("%.2f", bookHistory.getAfterBalance()), x, y);
            x += columnWidths[2];
            g2d.drawString(DateUtil.formatDateTime(bookHistory.getCreateTime()), x, y);
            x += columnWidths[3];
            g2d.drawString(bookHistory.getUserName(), x, y);
            y += rowHeight;
        }

        g2d.dispose();

        // 保存图片
        ImageIO.write(image, "png", new File(outputPath));
    }
}
