package com.yfd.platform.component.voiceserver;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class VoicePacketHandler extends SimpleChannelInboundHandler<VoicePacket> {
    public static List<DataGroup> dataGroups = new ArrayList<>();
    boolean flag = false;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, VoicePacket voicePacket) throws Exception {
        // 处理接收到的数据包
        dataGroups.add(voicePacket.getDataGroup());
    }

    private VoicePacket parseVoicePacket(ByteBuf buf) throws Exception {
        if (buf == null) {
            return null;
        }
        System.out.println("字节长度" + buf.readableBytes());
        VoicePacket packet = new VoicePacket();
        byte[] headBytes = new byte[4];
        buf.readBytes(headBytes);
        String head = new String(HexUtil.encodeHex(headBytes, false));
        if (!"FCFCFCFC".equals(head)) {
            System.out.println("不符合声纹和巡视主机的通讯协议！");
        }
        packet.setHead(head);
        packet.setVersion(buf.readByte());
        packet.setSize(buf.readInt());
        System.out.println("size" + packet.getSize());
        packet.setTimestamp(buf.readLong());
        packet.setBasicInfo(readBytes(buf, 6));
        packet.setId(readBytes(buf, 6));
        packet.setFirmware(readBytes(buf, 3));
        packet.setHardware(buf.readByte());
        packet.setProtocol(buf.readShort());
        packet.setFlag(readBytes(buf, 3));

        DataGroup dataGroup = new DataGroup();
        dataGroup.setSType(buf.readByte());
        dataGroup.setSampleRate(buf.readShort());
        dataGroup.setBits(buf.readByte());
        dataGroup.setChannel(buf.readByte());
        dataGroup.setData(readBytes(buf, buf.readableBytes() - 3)); // 减去CRC和End
        packet.setDataGroup(dataGroup);

        packet.setCrc(buf.readShort());
        packet.setEnd(buf.readByte());

        return packet;
    }

    private byte[] readBytes(ByteBuf buf, int length) {
        byte[] bytes = new byte[length];
        buf.readBytes(bytes);
        return bytes;
    }

    private void processVoicePacket(VoicePacket packet) throws IOException {

        //        byte bits = dataGroup.getBits();
        //        byte channel = dataGroup.getChannel();
        //        short sampleRate = dataGroup.getSampleRate();
        //        // 保存为 WAV 文件
        //        saveAsWav(dataGroup.getData(), sampleRate, channel, bits, "D:\\output.wav");
        //        System.out.println("WAV 文件生成成功");

    }

    /**
     * 生成模拟音频数据（PCM 格式）
     *
     * @param sampleRate    采样率
     * @param channels      声道数
     * @param bitsPerSample 位深
     * @return 模拟的音频数据
     */
    public static byte[] generateAudioData(int sampleRate, int channels, int bitsPerSample) {
        int duration = 2; // 音频时长（秒）
        int frameSize = channels * (bitsPerSample / 8); // 每帧的字节数
        int dataSize = sampleRate * duration * frameSize; // 总数据大小

        byte[] audioData = new byte[dataSize];
        for (int i = 0; i < dataSize; i++) {
            audioData[i] = (byte) (Math.random() * 256 - 128); // 随机生成 PCM 数据
        }
        return audioData;
    }

    /**
     * 解析声纹数据并保存为 WAV 文件
     *
     * @param audioData     音频数据（PCM 格式）
     * @param sampleRate    采样率（如 48000）
     * @param channels      声道数（如 2 表示双声道）
     * @param bitsPerSample 位深（如 16）
     * @param outputFile    输出文件路径（如 "output.wav"）
     */
    public static void saveAsWav(byte[] audioData, int sampleRate, int channels, int bitsPerSample, String outputFile) {
        try {
            // 创建音频格式
            AudioFormat format = new AudioFormat(sampleRate, bitsPerSample, channels, true, false);

            // 将字节数组转换为音频输入流
            ByteArrayInputStream bais = new ByteArrayInputStream(audioData);
            AudioInputStream audioInputStream = new AudioInputStream(bais, format,
                    audioData.length / format.getFrameSize());

            // 保存为 WAV 文件
            AudioSystem.write(audioInputStream, javax.sound.sampled.AudioFileFormat.Type.WAVE, new File(outputFile));
            System.out.println("Saved audio data to: " + outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
