package com.leromro.common.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyImgUtil {
    private static final Logger log = LoggerFactory.getLogger(MyImgUtil.class);

    public static void cutImage(String srcFile, String targetFile, int startAcross, int StartEndlong, int width, int hight) throws Exception {
        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = readers.next();
        InputStream source = new FileInputStream(srcFile);
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        Rectangle rect = new Rectangle(startAcross, StartEndlong, width, hight);
        param.setSourceRegion(rect);
        BufferedImage bi = reader.read(0, param);
        ImageIO.write(bi, targetFile.split("\\.")[1], new File(targetFile));
    }


    public static final void overlapImage(String bigPath, String smallPath, String outFile, int x, int y, int width, int height) {
        try {
            BufferedImage big = ImageIO.read(new File(bigPath));
            BufferedImage small = ImageIO.read(new File(smallPath));
            Graphics2D g = big.createGraphics();
            g.drawImage(small, x, y, width, height, (ImageObserver) null);
            g.dispose();
            ImageIO.write(big, outFile.split("\\.")[1], new File(outFile));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static final byte[] overlapImage(byte[] bigImgByte, byte[] smallImgByte, int x, int y, int width, int height) {
        try {
            InputStream bigIn = new ByteArrayInputStream(bigImgByte);
            BufferedImage big = ImageIO.read(bigIn);
            InputStream in = new ByteArrayInputStream(smallImgByte);
            BufferedImage small = ImageIO.read(in);
            Graphics2D g = big.createGraphics();
            g.drawImage(small, x, y, width, height, (ImageObserver) null);
            g.dispose();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(big, "png", baos);
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();
            return imageInByte;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void drawStringForImage(String filePath, String content, Color contentColor, float qualNum, String targetFile, int x, int y) {
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
        int width = theImg.getWidth((ImageObserver) null) == -1 ? 200 : theImg.getWidth((ImageObserver) null);
        int height = theImg.getHeight((ImageObserver) null) == -1 ? 200 : theImg.getHeight((ImageObserver) null);
        BufferedImage bimage = new BufferedImage(width, height, 1);
        Graphics2D g = bimage.createGraphics();
        g.setColor(contentColor);
        g.setBackground(Color.red);
        g.drawImage(theImg, 0, 0, (ImageObserver) null);
        g.setFont(new Font("微软雅黑", 1, 30));
        g.drawString(content, x, y);
        g.dispose();
        FileOutputStream out = null;
        try {
            try {
                String formatName = targetFile.substring(targetFile.lastIndexOf(".") + 1);
                ImageIO.write(bimage, formatName, new File(targetFile));
                if (0 != 0) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            } catch (Throwable th) {
                if (0 != 0) {
                    try {
                        out.close();
                    } catch (IOException e2) {
                        throw new RuntimeException(e2);
                    }
                }
                throw th;
            }
        } catch (Exception e3) {
            throw new RuntimeException(e3);
        }
    }

    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream inStream = conn.getInputStream();
            byte[] btImg = readInputStream(inStream);
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[6024];
        while (true) {
            int len = inStream.read(buffer);
            if (len != -1) {
                outStream.write(buffer, 0, len);
            } else {
                inStream.close();
                return outStream.toByteArray();
            }
        }
    }

    public static void buff2Image(byte[] b, String filePath) throws Exception {
        FileOutputStream fout = new FileOutputStream(filePath);
        fout.write(b);
        fout.close();
    }

    public static void deleteImg(String filePath) throws Exception {
        File file = new File(filePath);
        file.delete();
    }



    public static byte[] createPromoteQrcode(byte[] bigImgByte, byte[] smallImgByte, int x, int y, int width, int height) throws Exception {
        try {
            System.out.println("开始生成推广图片-----------");
            byte[] result = overlapImage(bigImgByte, smallImgByte, x, y, width, height);
            System.out.println("结束生成推广图片-----------");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] modifyImgSizeByUrl(String url, int with, int height) {
        try {
            log.info("url:" + url);
            URL img = new URL(url);
            log.info("img:" + img);
            BufferedImage image = ImageIO.read(img);
            BufferedImage newImage = resizeImage(image, with, height);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            ImageIO.write(newImage, "PNG", outStream);
            return outStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] modifyImg(String url, int radius) {
        try {
            log.info("url:" + url);
            URL img = new URL(url);
            log.info("img:" + img);
            BufferedImage image = ImageIO.read(img);
            BufferedImage newImage = setClip(image, radius);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            ImageIO.write(newImage, "PNG", outStream);
            return outStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] modifyImgSizeByByte(byte[] myByte, int with, int height) {
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(myByte);
            BufferedImage image = ImageIO.read(in);
            BufferedImage newImage = resizeImage(image, with, height);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            ImageIO.write(newImage, "PNG", outStream);
            return outStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
        Image resultingImage = originalImage.getScaledInstance(targetWidth, targetHeight, 16);
        BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, 1);
        outputImage.getGraphics().drawImage(resultingImage, 0, 0, (ImageObserver) null);
        return outputImage;
    }

    public static BufferedImage setClip(BufferedImage srcImage, int radius) {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, 2);
        Graphics2D gs = image.createGraphics();
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setClip(new RoundRectangle2D.Double(0.0d, 0.0d, width, height, radius, radius));
        gs.drawImage(srcImage, 0, 0, (ImageObserver) null);
        gs.dispose();
        return image;
    }

    public static byte[] imageToBytes(BufferedImage bImage) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(bImage, "png", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toByteArray();
    }

    private static BufferedImage bytesToBufferedImage(byte[] ImageByte) {
        ByteArrayInputStream in = new ByteArrayInputStream(ImageByte);
        BufferedImage image = null;
        try {
            image = ImageIO.read(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }



}