package com.jeequan.jeepay.bizcommons.manage.qrshell;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.google.zxing.WriterException;
import com.jeequan.jeepay.components.oss.config.OssYmlConfig;
import com.jeequan.jeepay.components.oss.model.OssFileConfig;
import com.jeequan.jeepay.core.utils.FileKit;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/***
 * 抽象类：  模板生成器
 *
 * @author terrfly
 * @date 2022/1/18 12:33
 */
public abstract class AbstractGenerator {

    public static final String DEFAULT_FONT = "微软雅黑"; // 微软雅黑   宋体

    @Autowired
    private OssYmlConfig ossYmlConfig;

    /**
     * 功能描述:生成图片的 BufferedImage
     *
     * @param configModelStr 自行转换
     * @param qrUrlContent   二维码内容
     * @param qrcId          码牌ID
     * @param isViewFlag     是否预览模式（将等比例缩小图片）
     * @Return: java.awt.image.BufferedImage
     * @Author: terrfly
     * @Date: 2022/1/18 15:52
     */

    public abstract BufferedImage genQrImgBuffer(String configModelStr, String qrUrlContent, Long qrcId, String mchStoreName, boolean isViewFlag) throws IOException, WriterException;


    protected BufferedImage getStaticImg(String img) throws IOException {
        return ImageIO.read(new ClassPathResource("static/images/qrshell" + img).getInputStream()); //
    }

    /**
     * 下载文件进行缓存 & 获取图片
     **/
    protected File downloadAndGetCacheFile(String url) {

        // 下载地址为空
        if (StringUtils.isEmpty(url)) {
            return null;
        }

        String filePath = ossYmlConfig.getOss().getFilePublicPath() + File.separator + OssFileConfig.BIZ_TYPE.QRC + File.separator + FileKit.getUrlFileName(url);

        // 存在
        if (new File(filePath).exists()) {
            return new File(filePath);
        }

        // 下载
        HttpUtil.downloadFile(url, filePath);
        return new File(filePath);
    }


    public static String convertImgBase64(BufferedImage bufferedImage) throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(bufferedImage, "jpg", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        String imgBase64 = Base64.encode(bytes);
        return imgBase64.replace("\n", "").replace("\r", "");//删除 \r\n
    }

    public static ByteArrayInputStream convertInputStream(BufferedImage bufferedImage) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", os);
        return new ByteArrayInputStream(os.toByteArray());
    }

}
