package com.zd.exam.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.zd.common.core.domain.R;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.StringUtils;
import com.zd.exam.domain.ElUserCert;
import com.zd.system.api.RemoteFileService;
import com.zd.system.api.domain.SysFile;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@Component
public class CertUtil {
    private static final Logger logger = LoggerFactory.getLogger(CertUtil.class);
    @Autowired
    private RemoteFileService remoteFileService;

    public String generateCert(ElUserCert elUserCert) {

        HttpURLConnection httpUrl = null;

        Font font = FontsUtil.getMsyh(16);
        Color color = new Color(49, 48, 48,255);
        try {
//            String backUrl = "http://192.168.1.7:9300//statics/2021/12/21/80b2a174-3497-4472-b98d-479b57dcb557.png";

            String backUrl = elUserCert.getCertUrl();


            httpUrl = (HttpURLConnection) new URL(backUrl).openConnection();
            httpUrl.connect();

            // 读取背景
            Image srcImg = ImageIO.read(httpUrl.getInputStream());
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);

            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.setColor(color);
            g.setFont(font);
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);


            int x = 885, y = 182;

            // 证书编号
            g.drawString(elUserCert.getCode(), x, y);

            font = FontsUtil.getMsyh(24);
            g.setFont(font);
            // 姓名
            x = 166; y = 370 ;
            g.drawString(elUserCert.getUserNickName(), x, y);

            // 学号
            x = 404;
            g.drawString(elUserCert.getUserName(), x, y);

            // 年月日
            x = 592;
            int year = DateUtil.year(elUserCert.getCreateTime());
            g.drawString(year+"", x, y);

            x = 706;
            int month = DateUtil.month(elUserCert.getCreateTime()) + 1;
            month = month == 13 ? 1 : month;
            g.drawString(month+"", x, y);

            x = 724; y = 660 ;
            int day = DateUtil.dayOfMonth(elUserCert.getCreateTime());
            g.drawString(year+"", x, y);
            x = 826;
            g.drawString(month+"", x, y);
            x = 902;
            g.drawString(day+"", x, y);

            // 有效期
            x = 260; y = 486 ;
            g.drawString(DateUtil.format(elUserCert.getCreateTime(),DateUtils.YYYYMMDD)
                    + "至" + DateUtil.format(elUserCert.getExpirationTime(),DateUtils.YYYYMMDD), x, y);

            g.dispose();

            // 输出图片
//            FileOutputStream outImgStream = new FileOutputStream("D:\\Temp\\11.png");
//            ImageIO.write(bufImg, "png", outImgStream);
//            outImgStream.flush();
//            outImgStream.close();

            // 文件服务存储
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //把BufferedImage写入ByteArrayOutputStream
            ImageIO.write(bufImg, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());

            //InputStream转成MultipartFile
            String fileName = IdUtil.fastSimpleUUID();
            MultipartFile file = new MockMultipartFile(fileName, fileName+ ".png", ContentType.APPLICATION_OCTET_STREAM.toString(), input);
            R<SysFile> fileResult = remoteFileService.upload(file);

            os.flush();
            input.close();
            os.close();

            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData())) {
                throw new ServiceException("文件服务异常，保存失败");
            }
            return fileResult.getData().getUrl();
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return null;
        }finally {
            if(httpUrl != null){
                httpUrl.disconnect();
            }

        }
    }

    public static void main(String[] args) {
        ElUserCert elUserCert = new ElUserCert();
        elUserCert.setCode("2021122165");
        elUserCert.setUserNickName("张大能");
        elUserCert.setUserName("99638521");
        elUserCert.setCreateTime(DateUtils.getNowDate());
        elUserCert.setExpirationTime(DateUtils.getNowDate());

        CertUtil certUtil = new CertUtil();
        certUtil.generateCert(elUserCert);
    }
}
