package com.cusc.nirvana.user.rnr.fp.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成默认的中文字体
 */
@Component
@Slf4j
public class ChineseFontComponent {

    private static Map<String, Font> chineseFontMap;

    /**
     * 创建中文字体
     *
     * @param key      字体类型的key
     * @param fontPath 字体路径
     */
    private static void createChineseFont(String key, String fontPath) throws Exception {
        log.info("初始化中文字体: {}, path: {}", key, fontPath);
        InputStream fisInJar = new ClassPathResource(fontPath).getInputStream();
        File file = File.createTempFile("Font-", ".ttf");
        //将jar包里的字体文件复制到操作系统的目录里
        OutputStream fosInOs = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int readLength = fisInJar.read(buffer);
        while (readLength != -1) {
            fosInOs.write(buffer, 0, readLength);
            readLength = fisInJar.read(buffer);
        }
        IOUtils.closeQuietly(fosInOs);
        IOUtils.closeQuietly(fisInJar);
        Font font;
        try {
            font = Font.createFont(Font.TRUETYPE_FONT, file);
            chineseFontMap.put(key, font);
        } catch (Exception e) {
            log.error("加载默认中文字体失败", e);
//            throw new CuscUserException("500", "加载默认中文字体失败: " + e.getMessage());
        }
        log.info("初始化中文字体完成: {}", key);
    }

    @PostConstruct
    private void initFont() throws Exception {
        chineseFontMap = new HashMap<>();
        String heiTiFontPath = "font/simhei.ttf";
        String kaiTiFontPath = "font/simkai.ttf";
        String songTiFontPath = "font/simsun.ttc";
        createChineseFont("HeiTi", heiTiFontPath);
        createChineseFont("KaiTi", kaiTiFontPath);
        createChineseFont("SongTi", songTiFontPath);
    }

    /**
     * 获取中文字体
     */
    public Font getChineseFont(String key) {
        Font font = chineseFontMap.get(key);
        return font == null ? chineseFontMap.get("SongTi") : font;
    }

}