package com.yfd.platform.utils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.yfd.platform.modules.patroltask.domain.TaskTodo;
import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipOutputStream;

public class TestUdpUtil {

    public static void main(String[] args) throws Exception {
        String inputFilePath = "D:\\ffmpeg\\bin\\input.mp4"; // 输入视频文件路径
        String outputRTPUrl = "rtp://192.168.22.237:5083"; // RTP输出URL

        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFilePath);
        FFmpegFrameRecorder recorder = null;

        try {
            grabber.start();

            // 设置输出参数
            recorder = new FFmpegFrameRecorder(outputRTPUrl, grabber.getImageWidth(), grabber.getImageHeight());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); // 设置H.264编码
            recorder.setFormat("rtp"); // 设置输出格式为RTP（注意：这里的格式设置可能需要根据实际情况调整）
            recorder.setFrameRate(grabber.getFrameRate());
            recorder.setAudioChannels(2);
            recorder.start();

            Frame frame;
            while ((frame = grabber.grab()) != null) {
                // 在这里可以对frame进行处理（如果需要的话）
                recorder.record(frame);
            }

            grabber.stop();
            recorder.stop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (grabber != null) {
                    grabber.release();
                }
                if (recorder != null) {
                    recorder.release();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    public static byte[] unlong2H4bytes(long n) {
        byte[] b = new byte[2];
        b[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        return b;
    }

    public static String byte2Hex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xff & bytes[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    private static void updateTaskTodo(TaskTodo taskTodo) {
        taskTodo.setTaskState("1");
    }

    /**
     * 压缩单文件
     *
     * @param file
     * @param zos
     * @param buffer
     */
    public static void compressSingleFile(File file, ZipOutputStream zos, byte[] buffer) {
        int len;
        try (FileInputStream fis = new FileInputStream(file)) {
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
                zos.flush();
            }
            zos.closeEntry();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**********************************
     * 用途说明: 发送一个文件
     * 参数说明
     * 返回值说明: void
     ***********************************/
    public static void sendFile(String localHost, int sendPort, int receivePort) {
        try {
            System.out.println("--------------------开始发送---------------------");
            //创建socket，设置发送端端口号
            DatagramSocket clientSocket = new DatagramSocket(sendPort);
            //要传输的文件路径
            File source = new File("D:\\测试.txt");
            InputStream inputstream = new FileInputStream(source);
            byte[] bytes = new byte[1024];
            if (inputstream.read(bytes) != -1) {
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(localHost), receivePort);
                //datagramPacket.setAddress(InetAddress.getLocalHost());
                System.out.println(InetAddress.getLocalHost());
                InetSocketAddress unresolved = InetSocketAddress.createUnresolved(localHost, receivePort);
                System.out.println(unresolved);
                //设置目的端口号
                //datagramPacket.setPort(receivePort);
                //存入数据到packet
                datagramPacket.setData(bytes);
                //发送数据
                clientSocket.send(datagramPacket);
            }
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**********************************
     * 用途说明: 解析二维码
     * 参数说明 file
     * 返回值说明: java.lang.String
     ***********************************/
    public static String resolveCodeByFile(String path) {
        String content = null;
        BufferedImage image;
        try {
            image = ImageIO.read(new File(path));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
            System.out.println("图片中内容：  ");
            System.out.println("content： " + result.getText());
            content = result.getText();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            //这里判断如果识别不了带LOGO的图片，重新添加上一个属性
            try {
                image = ImageIO.read(new File(path));
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map<DecodeHintType, Object> hints = new HashMap<>();
                //设置编码格式
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                //设置优化精度
                hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
                //设置复杂模式开启（我使用这种方式就可以识别微信的二维码了）
                hints.put(DecodeHintType.PURE_BARCODE, Boolean.TYPE);
                Result result = new MultiFormatReader().decode(binaryBitmap, hints);//解码
                System.out.println("图片中内容：  ");
                System.out.println("content： " + result.getText());
                content = result.getText();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        return content;
    }

}
