package cn.hnthyy.thmz.Utils;

import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.*;
import java.io.*;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.ImageIcon;

import org.apache.commons.codec.binary.Base64;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class WindowsUtil {

    private static String file1 = "", file2 = "";

    /**
     * 给图片添加水印
     *
     * @param filePath 需要添加水印的图片的路径
     * @return
     * @author zhongweihai newwei2001@yahoo.com.cn
     */
    public boolean createMark(String filePath, String outFile,
                              List<Map<String, Object>> list, Boolean needPic) throws IOException {
        ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
        int width = theImg.getWidth(null);
        int height = theImg.getHeight(null);
        BufferedImage bimage = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        g.drawImage(theImg, 0, 0, null);
        for (int i = 0; i < list.size(); i++) {
            add(g, bimage, list.get(i));
        }
        if (needPic) {
            BufferedImage content = ImageIO.read(new File(ResourceUtils.getFile("classpath:images") + "\\tx\\tx1.jpg"));
            // byte[] outImage= makeColorTransparent(content, new Color(254, 254, 254));
            g.drawImage(content.getScaledInstance(150, 180, Image.SCALE_DEFAULT), 320, 50, null);
        }
        g.dispose();
        FileOutputStream out=null;
        try {
            out = new FileOutputStream(outFile);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
            param.setQuality(70f, true);
            encoder.encode(bimage, param);
        } catch (Exception e) {
            return false;
        } finally {
            out.close();
            imgIcon = null;
            theImg = null;
        }
        return true;
    }


    public void add(Graphics2D g, BufferedImage bimage, Map<String, Object> map) {
        String markContent = (String) map.get("text");
        g.setColor((Color) map.get("color"));
        g.setBackground(Color.white);

        AttributedString ats = new AttributedString(markContent);
        Font f = new Font((String) map.get("fontType"), Font.BOLD,
                (Integer) map.get("fontSize"));
        ats.addAttribute(TextAttribute.FONT, f, 0, markContent.length());
        AttributedCharacterIterator iter = ats.getIterator();

        g.drawString(iter, (Integer) map.get("x"), (Integer) map.get("y")); // 添加水印的文字和设置水印文字出现的内容
    }

    /**
     * 生成身份证正面照片
     * @param name
     * @param gender
     * @param nation
     * @param year
     * @param month
     * @param day
     * @param address
     * @param idNum
     * @return
     */
    public static boolean generateIdcodeZ(String name, String gender, String nation, String year, String month, String day, String address, String idNum) {
        boolean bool = false;
        try {
            WindowsUtil wm = new WindowsUtil();
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            Color color1 = new Color(30, 30, 30);
            map.put("text", name); // 姓名
            map.put("color", color1);
            map.put("x", 90);
            map.put("y", 48);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);

            map = new HashMap<>();
            map.put("text", gender); // 性别
            map.put("color", color1);
            map.put("x", 90);
            map.put("y", 94);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);

            map = new HashMap<>();
            map.put("text", nation); // 民族
            map.put("color", color1);
            map.put("x", 210);
            map.put("y", 94);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);

            map = new HashMap<>();
            map.put("text", year); // 年
            map.put("color", color1);
            map.put("x", 90);
            map.put("y", 136);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);

            map = new HashMap<>();
            map.put("text", month);// 月
            map.put("color", color1);
            map.put("x", 180);
            map.put("y", 136);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);

            map = new HashMap<>();
            map.put("text", day);// 日
            map.put("color", color1);
            map.put("x", 230);
            map.put("y", 136);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);

            String[] adds = new String[2];
            if (address.length() > 11) {
                adds[0] = address.substring(0, 11);
                adds[1] = address.substring(11);
            } else {
                adds[0] = address;
                adds[1] = "";
            }
            map = new HashMap<>();
            map.put("text", adds[0]); // 证件地址1
            map.put("color", color1);
            map.put("x", 90);
            map.put("y", 184);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);
            if (address.length() > 11) {
                map = new HashMap<>();
                map.put("text", adds[1]);// 证件地址2
                map.put("color", color1);
                map.put("x", 90);
                map.put("y", 210);
                map.put("fontType", "幼圆");
                map.put("fontSize", 18);
                list.add(map);
            }

            map = new HashMap<>();
            map.put("text", idNum); // 证件号码
            map.put("color", color1);
            map.put("x", 167);
            map.put("y", 296);
            map.put("fontType", "微软雅黑");
            map.put("fontSize", 24);
            list.add(map);
            file1 = ResourceUtils.getFile("classpath:images") + "\\sfzzm.jpg";
            String path = ResourceUtils.getFile("classpath:images") + "\\idcode";
            createDir(path);
            wm.createMark(file1, path + "\\idz.jpg", list, true);
            // Thread.sleep(200);
            //bool = generateIdcodeF(wm, ResourceUtils.getFile("classpath:images") + "\\idcode\\idf.jpg", "安仁县公安局");
        } catch (Exception e) {
            e.printStackTrace();
            bool = false;
        }
        return bool;
    }

    /**
     * 生成身份证反面
     *
     * @param wm
     * @param tager
     * @param ress
     * @return
     */
    public static boolean generateIdcodeF(WindowsUtil wm, String tager, String ress) {
        boolean bool = false;
        try {
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            Color color1 = new Color(30, 30, 30);
            map.put("text", ress);
            map.put("color", color1);
            map.put("x", 220);
            map.put("y", 263);
            map.put("fontType", "幼圆");
            map.put("fontSize", 18);
            list.add(map);
            map = new HashMap<>();
            map.put("text", "2015.03.03-2025.03.03");
            map.put("color", color1);
            map.put("x", 220);
            map.put("y", 310);
            map.put("fontType", "微软雅黑");
            map.put("fontSize", 18);
            list.add(map);
            wm.createMark(file2, tager, list, false);
            bool = true;
            System.out.println("证件反面照【" + tager + "】生成成功");
        } catch (Exception e) {
            e.printStackTrace();
            bool = false;
        }
        return bool;
    }


    public static int parseInt(String param, int dat) {
        if (param != null) {
            try {
                dat = Integer.parseInt(param);
            } catch (Exception e) {
                System.out.println(param + " 是非数字...默认给值 " + dat);
            }
        }
        return dat;
    }

    /**
     * 将白色背景色替换成透明
     *
     * @param imagePath
     * @param outFile
     * @throws IOException
     */
    public static void convert(String imagePath, String outFile){
        //指定某种单色为透明
        try {
            BufferedImage image = ImageIO.read(new File(imagePath));
            ImageIcon imageIcon = new ImageIcon(image);
            int w = imageIcon.getIconWidth();
            int h = imageIcon.getIconHeight();
            BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
            g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
            int alpha = 0;
            for (int i = bufferedImage.getMinX(); i < w; i++) {
                for (int j = bufferedImage.getMinY(); j < h; j++) {
                    int rgb = bufferedImage.getRGB(i, j);
                    //以白色为例
                    int RGB = Color.WHITE.getRGB();
                    int r = (rgb & 0xff0000) >> 16;
                    int g = (rgb & 0xff00) >> 8;
                    int b = (rgb & 0xff);
                    int R = (RGB & 0xff0000) >> 16;
                    int G = (RGB & 0xff00) >> 8;
                    int B = (RGB & 0xff);
                    if (Math.abs(R - r) < 15 && Math.abs(G - g) < 15 && Math.abs(B - b) < 15) {
                        alpha = 0;
                    } else
                        alpha = 255;
                    rgb = (alpha << 24) | (rgb & 0x00ffffff);
                    bufferedImage.setRGB(i, j, rgb);
                }
            }
            g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
            ImageIO.write(bufferedImage, "png", new File(outFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将base64位的头像转为头像
     * @param imgStr
     */
    public static void generateImage(String imgStr) {
        if (imgStr == null) {
            return;
        } // 图像数据为空
        OutputStream out = null;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            // Base64解码,对字节数组字符串进行Base64解码并生成图片
            imgStr = imgStr.replaceAll(" ", "+");
            byte[] b = decoder.decodeBuffer(imgStr.replace("data:image/jpeg;base64,", ""));
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            String filePath=ResourceUtils.getFile("classpath:images") + "\\tx";
            createDir(filePath);
            out = new FileOutputStream(filePath + "\\tx.jpg");
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 图片到byte数组
     * @param path
     * @return
     */
    public static byte[] image2byte(String path,String fileName){
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            createDir(path);
            input = new FileImageInputStream(new File(path+"\\"+fileName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        }
        catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        }
        catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }



    public static void createDir(String dir) {
        if (dir != null) {
            File file = new File(dir);
            if (!file.exists() || file.isFile()) {
                file.mkdirs();
            }
        }
    }







}
