package com.kmall.common.utils.file;

import com.kmall.common.fileserver.util.FileManager;
import com.kmall.common.utils.R;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.*;
import java.nio.file.Files;

/**
 * @author huangyq
 * @version 1.0
 * 2019-04-29 14:50
 */
public class FileUploadUtil {

    public static String getUploadUrl(String mapToXml, String token, Integer id){

        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+ token);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
            StringEntity entity = new StringEntity(mapToXml);
            entity.setContentType("image/png");

            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            InputStream inputStream = response.getEntity().getContent();

            String fileName = System.currentTimeMillis() + "_" + id +".png";
            String dirName = "\\upload";
            File dirFile = new File(dirName);
            //删除之前的图片文件夹
            deleteFile(dirFile);
            if(!dirFile.exists()){
                dirFile.mkdirs();
            }

            File file = new File(dirName, fileName);// 可以是任何图片格式.jpg,.png等
            FileOutputStream fos = new FileOutputStream(file);
            if (inputStream != null) {
                try {
                    byte[] b = new byte[1024];
                    int nRead = 0;
                    while ((nRead = inputStream.read(b)) != -1) {
                        fos.write(b, 0, nRead);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false,
                    file.getName(), (int) file.length(), file.getParentFile());
            try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream();) {
                IOUtils.copy(input, os);
                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                String url = FileManager.upload(multipartFile);
//                compressPic(url, url);
                return url;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }
    public static boolean compressPic(String srcFilePath, String descFilePath) throws IOException {
        File file = null;
        BufferedImage src = null;
        FileOutputStream out = null;
        ImageWriter imgWrier;
        ImageWriteParam imgWriteParams;

        // 指定写图片的方式为 jpg
        imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
        imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(
                null);
        // 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
        imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
        // 这里指定压缩的程度，参数qality是取值0~1范围内，
        imgWriteParams.setCompressionQuality((float)1);
        imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
        ColorModel colorModel = ImageIO.read(new File(srcFilePath)).getColorModel();// ColorModel.getRGBdefault();
        // 指定压缩时使用的色彩模式
//        imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
//                colorModel, colorModel.createCompatibleSampleModel(16, 16)));
        imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
                colorModel, colorModel.createCompatibleSampleModel(16, 16)));

        try {
            if (isBlank(srcFilePath)) {
                return false;
            } else {
                file = new File(srcFilePath);
                System.out.println(file.length());
                src = ImageIO.read(file);
                out = new FileOutputStream(descFilePath);

                imgWrier.reset();
                // 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何
                // OutputStream构造
                imgWrier.setOutput(ImageIO.createImageOutputStream(out));
                // 调用write方法，就可以向输入流写图片
                imgWrier.write(null, new IIOImage(src, null, null),
                        imgWriteParams);
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0 || string.trim().equals("")) {
            return true;
        }
        return false;
    }

    private static void deleteFile(File dirFile){
        if(dirFile.exists()){
            if(dirFile.isFile()){
                dirFile.delete();
            }else {
                for(File file:dirFile.listFiles()){
                    deleteFile(file);
                }
            }
        }
    }
}
