package com.sqx.modules.file.utils;

import org.apache.commons.lang3.StringUtils;
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.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 图片工具
 */
@Component
public class ImageUtil {

    public static MultipartFile addWatermark(String textWatermark,String imageWatermark,MultipartFile file,String midu){
        // 读取原图片信息 得到文件
        File srcImgFile = null;
        try {
            srcImgFile = multipartFileToFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //File srcImgFile =new File("E:\\data\\123.png");
        //将文件对象转化为图片对象
        Image srcImg = null;
        try {
            srcImg = ImageIO.read(srcImgFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        delteTempFile(srcImgFile);
        //获取图片的宽
        int srcImgWidth = srcImg.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImg.getHeight(null);

        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        // 加水印
        //创建画笔
        Graphics2D graphics2D = bufImg.createGraphics();
        //绘制原始图片
        graphics2D.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);

        //如果文字水印有值，就将其绘制在图的中间
        if(StringUtils.isNotEmpty(textWatermark)){
            addTextWatermark(graphics2D,srcImgWidth,srcImgHeight,textWatermark,midu);
        }
        if(StringUtils.isNotEmpty(imageWatermark)){
            //如果图片水印有值，就将其绘制在图的右下角
            addImageWatermark(graphics2D,srcImgWidth,srcImgHeight,imageWatermark,4);
        }

        //待存储的地址--测试用的
        //String tarImgPath="E:/data/test.png";
         //输出图片
        //FileOutputStream outImgStream = null;
        ByteArrayOutputStream os = null;
        MultipartFile multipartFile = null;
        try {
            //outImgStream = new FileOutputStream(tarImgPath);
            //ImageIO.write(bufImg, "png", outImgStream);

            //创建一个ByteArrayOutputStream
            os = new ByteArrayOutputStream();
            //把BufferedImage写入ByteArrayOutputStream
            //此处要写PNG否则可能会出现遮罩层
            ImageIO.write(bufImg, "png", os);
            //ByteArrayOutputStream转成InputStream
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            multipartFile =new MockMultipartFile("file", "file.png", "text/plain", input);
        } catch (Exception  e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
//                if (null != outImgStream) {
//                    outImgStream.flush();
//                    outImgStream.close();
//                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return multipartFile;
    }

    public static void addTextWatermark(Graphics2D graphics2D,int srcImgWidth,int srcImgHeight,String textWatermark,String midu){
        //-------------------------文字水印 start----------------------------
        //根据图片的背景设置水印颜色
        graphics2D.setColor(new Color(0,0,0));
        //设置字体  画笔字体样式为微软雅黑，加粗，文字大小为60pt
        graphics2D.setFont(new Font("黑体", Font.ITALIC, 30));
        graphics2D.rotate(Math.toRadians(315),(double)srcImgWidth/2, (double)srcImgHeight/2);
        //设置水印的坐标(为原图片中间位置)
        //textWatermark为水印内容
        /*int x=(srcImgWidth - getWatermarkLength(textWatermark, graphics2D)) / 2;
        int y=srcImgHeight / 10;*/
        //画出水印 第一个参数是水印内容，第二个参数是x轴坐标，第三个参数是y轴坐标
//        graphics2D.drawString(textWatermark, x, y);
        int width=35;
        if(textWatermark.length()>0){
            width=width*textWatermark.length();
        }
        int miduNum = 80;
        if(StringUtils.isNotEmpty(midu)){
            try {
                miduNum = Integer.parseInt(midu);
            }catch (Exception e){
                e.printStackTrace();
            }
        }


        for (int i = -200; i <= srcImgWidth+200; i += width) {
            for (int j = -200; j <= srcImgHeight+200; j += miduNum) {
                graphics2D.drawString(textWatermark, i, j);
            }
        }
        graphics2D.dispose();
        //-------------------------文字水印 end----------------------------
    }
    //水印方法重构 暂时不用
    public static void addTextWatermark2(Graphics2D graphics2D,int srcImgWidth,int srcImgHeight,String textWatermark){
        //-------------------------文字水印 start----------------------------
        //根据图片的背景设置水印颜色
        graphics2D.setColor(new Color(0,0,0));
        //设置字体  画笔字体样式为微软雅黑，加粗，文字大小为60pt
        graphics2D.setFont(new Font("黑体", Font.ITALIC, 40));
        graphics2D.rotate(Math.toRadians(315),(double)srcImgWidth/2, (double)srcImgHeight/2);
        //i为x坐标 j为y坐标 通过设置坐标来控制水印的位置 positionWidth和positionHeight 设置密度
        // 水印横向间隔
        int positionWidth = (int)(srcImgWidth * 0.1);
        // 水印竖向间隔
        int positionHeight  = (int)(srcImgHeight * 0.03);
        for(int i = -400; i <= srcImgWidth * 3 ; i += positionWidth){
            for (int j = -400; j <= srcImgHeight * 3 ; j += positionHeight){
                graphics2D.drawString(textWatermark, i, j);
            }
        }
        graphics2D.dispose();
        //-------------------------文字水印 end----------------------------
    }
    public static void addImageWatermark(Graphics2D graphics2D,int srcImgWidth,int srcImgHeight,String imageWatermark,int type){
        //-------------------------图片水印 start----------------------------
        //水印文件
        //创建一个URL对象,获取网络图片的地址信息（网络图片）
        URL url = null;
        //将URL对象输入流转化为图片对象 (url.openStream()方法，获得一个输入流)
        Image srcWaterMark = null;
        try {
            url = new URL(imageWatermark);
            srcWaterMark = ImageIO.read(url.openStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置 alpha 透明度：alpha 必须是范围 [0.0, 1.0] 之内（包含边界值）的一个浮点数字
        graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
        //x,y为章需要合成到A图片上的位置坐标，w,h为将章缩小到多少长宽比例
        //注意这行代码:graphics2D.drawlmage(img, x, y, w, h, null);
        //绘制水印图片 坐标为自己选择
        int x = 0;
        int y = 0;
        int width = (int)(srcImgWidth*0.1);
        int height = (int)(srcImgWidth*0.1);
        if (type == 1) {
            //覆盖图片位于左上角
            x = 0;
            y = 0;
        } else if (type == 2) {
            //覆盖图片位于右上角
            x = srcImgWidth - width;
            y = 0;
        } else if (type == 3) {
            //覆盖图片位于左下角
            x = 0;
            y = srcImgHeight - height;
        } else if (type == 4) {
            //覆盖图片位于右下角
            x = srcImgWidth - width;
            y = srcImgHeight - height;
        } else if (type == 5 ){
            //覆盖图片位于中间
            x = (srcImgWidth - width) / 2;
            y = (srcImgWidth - height) / 2;
        }
        graphics2D.drawImage(srcWaterMark, x, y ,width, height, null);
        // 水印文件结束
        graphics2D.dispose();
        //-------------------------图片水印 end----------------------------
    }

    /**
     * 获取水印文字的长度
     * @param waterMarkContent
     * @param graphics2D
     * @return
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D graphics2D) {
        return graphics2D.getFontMetrics(graphics2D.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }


    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}