package com.huimv.receive.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Date;

@Component
public class UploadImage {

    @Value("${img.basePath}")
    private   String basePath;

    @Value("${img.ip}")
    private    String ip ;
//    private   String ip = "36.134.209.211";
//    private   String ip = "192.168.0.13";

    @Value("${img.user}")
    private  String user ;

//    private   String password = "!Hm537e@1";

    @Value("${img.password}")
    private   String password ;

    @Value("${img.port}")
    public   Integer port ;

    @Value("${img.url}")
    public   String url ;




    /**
     * 判断文件大小
     *
     * @param len
     *            文件长度
     * @param size
     *            限制大小
     * @param unit
     *            限制单位（B,K,M,G）
     * @return
     */
    public 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;
    }


    /**
     * 利用JSch包实现SFTP上传文件
     * @param bytes  文件字节流
     * @param fileName  文件名
     * @throws Exception
     */
    public   void sshSftp(byte[] bytes,String path,String fileName) throws Exception{

        // 服务器保存路径
        String filepath = basePath +path ;
        Session session = null;
        Channel channel = null;

        JSch jSch = new JSch();

        if(port <=0){
            //连接服务器，采用默认端口
            session = jSch.getSession(user, ip);
        }else{
            //采用指定的端口连接服务器
            session = jSch.getSession(user, ip ,port);
        }

        //如果服务器连接不上，则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }

        //设置登陆主机的密码
        session.setPassword(password);//设置密码
        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("userauth.gssapi-with-mic","no");
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);

        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;

            //进入服务器指定的文件夹
            sftp.cd(basePath);

            SftpATTRS attrs = null;
            try {
                attrs = sftp.stat(filepath);
            } catch (Exception e) {
                // TODO: handle exception
            }
            if (attrs == null) {
                sftp.mkdir(filepath);
                System.out.println(("创建子目录：" + filepath));
            }
            sftp.cd(filepath);

            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换一下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
            System.out.println("上传成功!");
        }
    }

    //上传压缩的图片
    public  String getImageCom(MultipartFile image) throws IOException {
        //获取文件输入流
        InputStream inputStream = image.getInputStream();
        String originalFilename = image.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String path = DateUtil.format(new Date(), "yyyy-MM");

        try {
            // 把图片读入到内存中
            BufferedImage bufImg = ImageIO.read(inputStream);
            // 压缩代码,存储图片文件byte数组
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            //防止图片变红,这一步非常重要
            BufferedImage bufferedImage = new BufferedImage(bufImg.getWidth(), bufImg.getHeight(), BufferedImage.TYPE_INT_RGB);
            bufferedImage.createGraphics().drawImage(bufImg,0,0, Color.WHITE,null);
            //先转成jpg格式来压缩,然后在通过OSS来修改成源文件本来的后缀格式
            ImageIO.write(bufferedImage,"jpg",bos);
            byte[] bytes = bos.toByteArray();
            String imgname = UUID.randomUUID() + "." + "jpg";
            sshSftp(bytes, path, imgname);
            return url+ path + "/" + imgname;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        } finally {
            inputStream.close();
        }
    }


    //上传原图
    public  String uploadImg( MultipartFile image ) {
        String originalFilename = image.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String path = DateUtil.format(new Date(), "yyyy-MM");
        try {
            InputStream inputStream = image.getInputStream();
            BufferedInputStream in = new BufferedInputStream(inputStream);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

            byte[] temp = new byte[1024];
            int size = 0;
            while ((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            in.close();
            byte[] content = out.toByteArray();
            String imgname = UUID.randomUUID() + "." + filenameExtension;
            sshSftp(content, path, imgname);
            return url + path + "/" + imgname;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

    //上传压缩的视频
    public  String getVideoCom(MultipartFile video) throws IOException {
        String originalFilename = video.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String path = DateUtil.format(new Date(), "yyyy-MM");
        try {
            InputStream inputStream = video.getInputStream();
            BufferedInputStream in = new BufferedInputStream(inputStream);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

            byte[] temp = new byte[1024];
            int size = 0;
            while ((size = in.read(temp)) != -1) {
                out.write(temp, 0, size);
            }
            in.close();
            byte[] content = out.toByteArray();
            String videoName = UUID.randomUUID() + "." + filenameExtension;
            sshSftp(content, path, videoName);
            return url + path + "/" + videoName;
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }

//        //获取文件输入流
//        InputStream inputStream = image.getInputStream();
//        String originalFilename = image.getOriginalFilename();
//        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
//        String path = DateUtil.format(new Date(), "yyyy-MM");
//
//        try {
//
//            File tempFile = new File("tempVideo.mp4");
//            image.transferTo(tempFile);
////
////            // 使用FFmpegFrameGrabber读取视频信息
////            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(tempFile);
////            grabber.start();
////
////            // 创建输出文件
////            File compressedFile = new File("compressedVideo.mp4");
////
////            // 使用FFmpegFrameRecorder进行压缩
////            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(compressedFile, grabber.getImageWidth(), grabber.getImageHeight(), grabber.getAudioChannels());
////            recorder.setInterleaved(true);
////            recorder.setVideoOption("preset", "ultrafast"); // 设置压缩速度，可以根据需要调整
////            recorder.setVideoOption("crf", "40"); // 设置视频质量，范围通常是0-51，值越大压缩率越高，质量越低
////            recorder.setVideoCodec(findH264Encoder(recorder)); // 查找并设置H.264编解码器
////            recorder.setFormat("mp4");
////            recorder.setFrameRate(grabber.getFrameRate());
////            recorder.setSampleRate(grabber.getSampleRate());
////            recorder.setAudioBitrate(grabber.getAudioBitrate());
////            recorder.setVideoBitrate(grabber.getVideoBitrate() / 2); // 压缩一半的视频比特率
////
////            // 开始录制并压缩视频
////            recorder.start();
////            Frame frame;
////            while ((frame = grabber.grabFrame()) != null) {
////                recorder.record(frame);
////            }
////            recorder.stop();
////            grabber.stop();
////
////            // 读取压缩后的视频为字节数组
////            byte[] compressedVideoBytes = Files.readAllBytes(compressedFile.toPath());
////
////            // 删除临时文件
////            tempFile.delete();
////            compressedFile.delete();
////
//            String imgname = UUID.randomUUID() + "." + filenameExtension;
//            sshSftp(image, path, imgname);
//            return url+ path + "/" + imgname;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "上传失败";
//        } finally {
//            inputStream.close();
//        }
    }

//    private int findH264Encoder(FFmpegFrameRecorder recorder) {
//        AVCodec codec = null;
//
//        AVCodec.avcodec_register_all(); // 注册所有编解码器
//        for (AVCodec.AVCodecDescriptor desc : AVCodec.avcodec_descriptor_get(null)) {
//            if (desc.type() == AVCodec.AVMEDIA_TYPE_VIDEO &&
//                    desc.id() != AVCodec.AV_CODEC_ID_NONE &&
//                    desc.name().equals("libx264")) { // libx264是H.264的常用编码器名称
//                codec = AVCodec.avcodec_find_encoder(desc.id());
//                break;
//            }
//        }
//        if (codec == null) {
//            throw new RuntimeException("H.264 encoder not found");
//        }
//        return codec.id();
//    }


}



