package com.qmth.teachcloud.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qmth.teachcloud.common.contant.SystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: 图片轨迹坐标生成
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/11/2
 */
public class ImageTrajectoryUtil {
    private final static Logger log = LoggerFactory.getLogger(ImageTrajectoryUtil.class);
    private final static String FONT_FORMAT = "微软雅黑";
    private final static int FONT_SIZE = 30;

    /**
     * 生成图片
     *
     * @param imgFile
     * @param targetFile
     * @param jsonArray
     * @throws IOException
     */
    public static void createImage(File imgFile, File targetFile, JSONArray jsonArray) throws IOException {
        FileOutputStream output = null;
        try {
            BufferedImage image = ImageIO.read(new FileInputStream(imgFile));
            image = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_sRGB), null).filter(image, null);
            Graphics2D g = image.createGraphics();// 得到图形上下文
            g.setColor(Color.red); // 设置画笔颜色
            // 设置字体
            g.setFont(new Font(FONT_FORMAT, Font.LAYOUT_LEFT_TO_RIGHT, FONT_SIZE));// 写入签名
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                JSONArray contentJsonArray = (JSONArray) jsonObject.get("content");
                StringJoiner stringJoiner = new StringJoiner(",");
                for (int k = 0; k < contentJsonArray.size(); k++) {
                    stringJoiner.add(contentJsonArray.get(k).toString());
                }
                g.drawString(stringJoiner.toString(), (Integer) jsonObject.get("left"), (Integer) jsonObject.get("top"));
            }
            g.dispose();

            output = new FileOutputStream(targetFile);
            ImageIO.write(image, "jpg", output);
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
        } finally {
            if (Objects.nonNull(output)) {
                output.flush();
                output.close();
            }
        }
    }
}
