package com.yh.saas.plugin.yiliangyiyun.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yh.saas.plugin.yiliangyiyun.entity.LogoConfig;
import lombok.Getter;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

public final class MatrixToImageWriter {


    @Getter
    @Value("${oss.endpoint.internal:}")
    private String baseUrl;
    @Getter
    @Value("${oss.bucket.name:}")
    private String bucket;
    @Autowired
    private OSSClient ossClient;
    @Getter
    @Value("${oss.endpoint.default:}")
    private String endpoint;

    private String host;

    //    @Override
    public void afterPropertiesSet() throws Exception {
        host = "http://" + bucket + "." + endpoint;
    }


    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private MatrixToImageWriter() {
    }


    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }


    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }


    public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }


    /**
     * 给二维码图片添加Logo
     *
     * @param qrPic
     * @param logoPic
     */
    public static void addLogo_QRCode(File qrPic, File logoPic, LogoConfig logoConfig) {
        try {
            if (!qrPic.isFile() || !logoPic.isFile()) {
                System.out.print("file not find !");
                System.exit(0);
            }

            /**
             * 读取二维码图片，并构建绘图对象
             */
            BufferedImage image = ImageIO.read(qrPic);
            Graphics2D g = image.createGraphics();

            /**
             * 读取Logo图片
             */
            BufferedImage logo = ImageIO.read(logoPic);

            int widthLogo = image.getWidth() / logoConfig.getLogoPart();
            //    int    heightLogo = image.getHeight()/logoConfig.getLogoPart();
            int heightLogo = image.getWidth() / logoConfig.getLogoPart(); //保持二维码是正方形的

            // 计算图片放置位置
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;


            //开始绘制图片
            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
            g.setStroke(new BasicStroke(logoConfig.getBorder()));
            g.setColor(logoConfig.getBorderColor());
            g.drawRect(x, y, widthLogo, heightLogo);

            g.dispose();

//            ImageIO.write(image, "jpeg", new File("D:/" + name + ".jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    /**
//     * @param pressText 文字
//     * @param newImg    带文字的图片
//     * @param targetImg 需要添加文字的图片
//     * @param fontStyle
//     * @param color
//     * @param fontSize
//     * @param width
//     * @为图片添加文字
//     */
//    public static void pressText(String pressText, String newImg, String targetImg, int fontStyle, Color color, int fontSize, int width, int height) {
//
//        //计算文字开始的位置
//        //x开始的位置：（图片宽度-字体大小*字的个数）/2
//        int startX = (width-(fontSize*pressText.length()))/2;
//        //y开始的位置：图片高度-（图片高度-图片宽度）/2
//        int startY = height-(height-width)/2;
//
//        try {
//            File file = new File(targetImg);
//            Image src = ImageIO.read(file);
//            int imageW = src.getWidth(null);
//            int imageH = src.getHeight(null);
//            BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
//            Graphics g = image.createGraphics();
//            g.drawImage(src, 0, 0, imageW, imageH, null);
//            g.setColor(color);
//            g.setFont(new Font(null, fontStyle, fontSize));
//            g.drawString(pressText, startX, startY);
//            g.dispose();
//
//            FileOutputStream out = new FileOutputStream(newImg);
//            ImageIO.write(image, "JPEG", out);
//            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//            encoder.encode(image);
//            out.close();
//            System.out.println("image press success");
//        } catch (Exception e) {
//            System.out.println(e);
//        }
//    }
    public String logoWriter(String content, String type, String name) {
        try {
            //二维码表示的内容
//            String content = "http://www.cnblogs.com/";

            //存放logo的文件夹
            String path = "D:/QRCodeImage";

            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();

            @SuppressWarnings("rawtypes")
            Map hints = new HashMap();

            //设置UTF-8， 防止中文乱码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置二维码四周白色区域的大小
            hints.put(EncodeHintType.MARGIN, 1);
            //设置二维码的容错性
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            //width:图片完整的宽;height:图片完整的高
            //因为要在二维码下方附上文字，所以把图片设置为长方形（高大于宽）
            int width = 100;
            int height = 100;

            //画二维码，记得调用multiFormatWriter.encode()时最后要带上hints参数，不然上面设置无效
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            //qrcFile用来存放生成的二维码图片（无logo，无文字）
            File qrcFile = new File(path, name + "123.jpg");
            //logoFile用来存放带有logo的二维码图片（二维码+logo，无文字）
            File logoFile = new File(path, "DSC_7907.jpg");

            //开始画二维码
            MatrixToImageWriter.writeToFile(bitMatrix, "jpg", qrcFile);

            //在二维码中加入图片
            LogoConfig logoConfig = new LogoConfig(); //LogoConfig中设置Logo的属性
//            addLogo_QRCode(qrcFile, logoFile, logoConfig, name);
//            MultipartFile multipartFile = new MockMultipartFile( ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
//            String result = QRCodeUtil.upload(multipartFile,name);
//            file.delete();
//            return result;
            return "success";

        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    /**
     * 后台通过服务器间接传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file, String sendCarNo) throws IOException {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, "QRCode/" + sendCarNo + ".png", file.getInputStream(), objectMetadata);
        ossClient.putObject(putObjectRequest);
        return baseUrl + "QRCode/" + sendCarNo + ".png";
    }


}
