package cn.wise.sc.acquisition.business.util;


import cn.hutool.core.codec.Base64;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.wise.sc.acquisition.business.entity.TSampleLaboratorysheet;
import cn.wise.sc.acquisition.business.entity.TSampleList;
import cn.wise.sc.acquisition.business.enumation.ProjectEnum;
import cn.wise.sc.acquisition.business.model.query.TSampleListQuery;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Author renchao
 * 文件上传下载转化工具类，二维码生成
 */
public class ImageUtil {

    /**
     * 将文件转化为字节
     */
    public static byte[] transformByte(MultipartFile file) {
        if (file == null) throw new RuntimeException("transformByte method:file is null");
        try {
            byte[] pictureData = new byte[(int) file.getSize()];
            InputStream inputStream = file.getInputStream();
            inputStream.read(pictureData);
            inputStream.close();
            return pictureData;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("file transform picture is failed");
        }
    }

    /**
     * 将字节转化为文件,并下载
     */
    public static void transformImage(byte[] data, final HttpServletResponse response) {
        if (data.length == 0) throw new RuntimeException("transformImage method:byte[] data is null");
        if (response == null) throw new RuntimeException("transformImage method:HttpServletResponse response is null");
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream;
        try {
            outputSream = response.getOutputStream();
            outputSream.write(data);
            outputSream.flush();
            outputSream.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("picture download is failed");
        }
    }


    /**
     * 将多个文件转化为字节
     */
    public static byte[] transformByteMore(MultipartFile[] files) {
        if (files == null || files.length == 0) throw new RuntimeException("transformByteMore method:files is null");
        try {
            //创建字节流数组
            List<byte[]> bytes = new ArrayList<>();
            InputStream inputStream = null;
            //循环读取文件
            for (MultipartFile file : files) {
                byte[] pictureData = new byte[(int) file.getSize()];
                inputStream = file.getInputStream();
                inputStream.read(pictureData);
                bytes.add(pictureData);
            }
            //关流
            if (inputStream != null) {
                inputStream.close();
            }
            //将数组转化为字节
            byte[] data = JSON.toJSONString(bytes, true).getBytes();
            return data;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("files transform picture is failed");
        }
    }


    /**
     * 将字节转化为文件,并下载
     */
    public static void transformImageMore(byte[] data, final HttpServletResponse response) {
        if (data == null || data.length == 0)
            throw new RuntimeException("transformImageMore method:byte[] data is null");
        if (response == null)
            throw new RuntimeException("transformImageMore method:HttpServletResponse response is null");
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = null;
        try {
            List<byte[]> bytes = JSON.parseObject(new String(data), new TypeReference<List<byte[]>>() {
            });
            outputSream = response.getOutputStream();
            for (byte[] picture : bytes) {
                outputSream.write(picture);
            }
            outputSream.flush();
            if (outputSream != null) {
                outputSream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("files transform picture is failed");
        }
    }

    /**
     * 根据obj类型获取图片
     */
    public static void getImage(Integer imageType, Object obj, final HttpServletResponse response) {
        if (imageType == null || imageType.intValue() == 0)
            throw new RuntimeException("getImage method:imageType is null");
        if (obj == null) throw new RuntimeException("getImage method:Object obj is null");
        if (response == null) throw new RuntimeException("getImage method:HttpServletResponse response is null");

        byte[] data = null;
//        if (obj instanceof TSampleList) {
//            TSampleList tSampleList = (TSampleList) obj;
//            //判断获取二维码还是记录形式
//            if (ProjectEnum.ImageType.getLabel(imageType).equals(ProjectEnum.ImageType.RECORD_CODE.getLabel())) {
//                data = tSampleList.getRecordCode();
//            }
//            if (ProjectEnum.ImageType.getLabel(imageType).equals(ProjectEnum.ImageType.QR_CODE.getLabel())) {
//                data = tSampleList.getQRCode();
//            }
//
//        } else
        if (obj instanceof TSampleLaboratorysheet) {
            TSampleLaboratorysheet tSampleLaboratorysheet = (TSampleLaboratorysheet) obj;
            data = tSampleLaboratorysheet.getQRCode();
        }
        if (data != null) {
            //下载图片
            ImageUtil.transformImage(data, response);
        }
        return;
    }

    /**
     * 根据类型保存并转化文件为图片 需要请求参数ImageType  保存的实体TSampleList  以及file
     */
    public static void setImage(Integer imageType, Object obj, MultipartFile file) {
        if (imageType == null || imageType.intValue() == 0)
            throw new RuntimeException("getImage method:imageType is null");
        if (obj == null) throw new RuntimeException("getImage method:Object obj is null");
        if (file == null) throw new RuntimeException("getImage method:MultipartFile file is null");

//        if (obj instanceof TSampleList) {
//            TSampleList tSampleList = (TSampleList) obj;
//            //判断保存二维码还是记录形式
//            if (ProjectEnum.ImageType.getLabel(imageType).equals(ProjectEnum.ImageType.RECORD_CODE.getLabel())) {
//                tSampleList.setRecordCode(transformByte(file));
//            }
//            if (ProjectEnum.ImageType.getLabel(imageType).equals(ProjectEnum.ImageType.QR_CODE.getLabel())) {
//                tSampleList.setQRCode(transformByte(file));
//            }
//        } else
        if (obj instanceof TSampleLaboratorysheet) {
            TSampleLaboratorysheet tSampleLaboratorysheet = (TSampleLaboratorysheet) obj;
            tSampleLaboratorysheet.setQRCode(transformByte(file));
        }

    }

    /**
     * 二维码生成工具类
     *
     * @param content
     */
    public static byte[] QRCodeGenerator(String content) {
        if (StringUtils.isEmpty(content)) throw new RuntimeException("QRCodeGenerator method:String content is null");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        BufferedImage bufferedImage = QrCodeUtil.generate(content, 200, 200);
        try {
            ImageIO.write(bufferedImage, "png", stream);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //String encode = Base64.encode(stream.toByteArray());
        return stream.toByteArray();
    }


    /**
     * 判断图片大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
//        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }


}

