package com.hr.repository.service.impl;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author yaoy
 * @createTime 2025/10/17 15:21
 **/

@Component
@Slf4j
public class FontManager {
    @Autowired
    private ResourceLoader resourceLoader;
    private volatile Font cachedFont;
    private final Object lock = new Object();

    @PostConstruct
    public void init() {
        // 应用启动时预加载字体
        getFont(12f); // 预加载默认大小的字体
    }

    /**
     * 获取字体对象，带缓存机制
     */
    public Font getFont(float size) {
        if (cachedFont == null) {
            synchronized (lock) {
                if (cachedFont == null) {
                    cachedFont = loadBaseFont();
                }
            }
        }
        return cachedFont.deriveFont(size);
    }

    /**
     * 加载基础字体（只加载一次）
     */
    private Font loadBaseFont() {

//        ClassPathResource resource = new ClassPathResource("fonts/simsun.ttf");
//        try {
//            InputStream fontStream = resource.getInputStream();
//            Font f= Font.createFont(Font.TRUETYPE_FONT, fontStream);
//            log.info("字体加载成功");
//            return f;
//        }catch (Exception e) {
//            log.error("加载字体失败:{}",e.getMessage(),e);
//            return new Font("SansSerif", Font.PLAIN, 12);
//        }
        try {
            ClassPathResource resource = new ClassPathResource("fonts/simsun.ttf");
            log.info("尝试加载字体文件: {}", resource.getPath());
            log.info("资源存在: {}", resource.exists());

            if (!resource.exists()) {
                log.error("字体文件不存在: fonts/simsun.ttf");
                return new Font("SansSerif", Font.PLAIN, 12);
            }

            try (InputStream is = resource.getInputStream()) {
                if (is == null) {
                    log.error("字体文件输入流为 null");
                    return new Font("SansSerif", Font.PLAIN, 12);
                }

                byte[] fontData = StreamUtils.copyToByteArray(is);
                log.info("字体文件大小: {} bytes", fontData.length);

                if (fontData.length == 0) {
                    log.error("字体文件为空");
                    return new Font("SansSerif", Font.PLAIN, 12);
                }

                Font font = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(fontData));
                Font derivedFont = font.deriveFont(12f);

                log.info("字体加载成功: {} (family: {}, name: {})",
                        derivedFont.getFontName(), derivedFont.getFamily(), derivedFont.getName());

                return derivedFont;

            }
        } catch (Exception e) {
            log.error("加载字体失败", e);
            try {
                Font defaultFont = new Font("Dialog", Font.PLAIN, 12);
                log.info("使用默认字体: {}", defaultFont.getName());
                return defaultFont;
            } catch (Exception ex) {
                log.error("创建默认字体也失败", ex);
                return Font.decode(null);
            }
        }

    }

    /**
     * 清除缓存（很少需要调用）
     */
    public void clearCache() {
        synchronized (lock) {
            cachedFont = null;
        }
    }
}
