package com.cf.imes.module.manage.service.voice;


import com.cf.imes.module.manage.config.VocieParameters;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.http.WebSocket;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Objects;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
@Slf4j
public class VoiceServiceImpl implements VoiceService{

    @Resource
    private VocieParameters vocieParameters;


//    static {
//        System.loadLibrary("jacob-1.18-x64");
//    }

    // 生成音频文件
    @Override
    public String voiceAnnouncements(String data) {


        // 音频保存的路径
        String path = vocieParameters.getPath();

        // 设置音频的质量（ 越大越好，目前最大好像 22，最小为 4 ）
        Long quality = vocieParameters.getQuality();;

        // 朗读声音大小
        Long soundSize = vocieParameters.getSoundSize();

        // 朗读速度
        Long readingSpeed = vocieParameters.getReadingSpeed();

        ActiveXComponent ax = null;
        Dispatch spFileStream = null;
        Dispatch spAudioFormat = null;
        Dispatch spVoice = null;
        try{
            ax = new ActiveXComponent("Sapi.SpFileStream");
            spFileStream = ax.getObject();

            ax = new ActiveXComponent("Sapi.SpAudioFormat");
            spAudioFormat = ax.getObject();

            spVoice = new ActiveXComponent("Sapi.SpVoice").getObject();
            // 设置音频流格式
            Dispatch.put(spAudioFormat, "Type", new Variant(quality));
            // 设置文件输出流格式
            Dispatch.putRef(spFileStream, "Format", spAudioFormat);
            // 随机数，控制文件的名字
            int randomInt = new Random(System.currentTimeMillis()).nextInt(900) + 100;// 生成100到999之间的随机数
            // 文件的路径
            String filePath = path + randomInt + ".mp3";

            // 调用输出文件流打开方法，创建一个.wav文件
            Dispatch.call(spFileStream, "Open", new Variant(filePath), new Variant(3), new Variant(true));
            // 设置声音对象的音频输出流为输出文件对象
            Dispatch.putRef(spVoice, "AudioOutputStream", spFileStream);
            // 设置音量  0 ~ 100
            Dispatch.put(spVoice, "Volume", new Variant(soundSize));
            // 设置朗读速度  -10 ~ +10
            Dispatch.put(spVoice, "Rate", new Variant(readingSpeed));

            Dispatch.call(spVoice, "Speak", new Variant(data));

            System.out.println("输出语音文件成功！");

            return filePath;

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            // 关闭输出文件
            Dispatch.call(Objects.requireNonNull(spFileStream), "Close");
            Dispatch.putRef(Objects.requireNonNull(spVoice), "AudioOutputStream", null);

            Objects.requireNonNull(spAudioFormat).safeRelease();
            spFileStream.safeRelease();
            spVoice.safeRelease();
            ax.safeRelease();
        }

        return null;
    }



    /**
     * 把生成的音频文件进行压缩
     * @param fileNames 需要压缩的文件名称列表(包含相对路径)
     * @param zipOutName 压缩后的文件名称
     **/
    @Override
    public void zipFiles(String fileNames, String zipOutName) throws IOException {
        ZipOutputStream zipOutputStream = null;
        WritableByteChannel writableByteChannel = null;
        ByteBuffer buffer = ByteBuffer.allocate(2048);
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutName));
            writableByteChannel = Channels.newChannel(zipOutputStream);
            File source = new File(fileNames);
            zipOutputStream.putNextEntry(new ZipEntry(source.getName()));
            FileChannel fileChannel = new FileInputStream(fileNames).getChannel();
            while (fileChannel.read(buffer) != -1) {
                //更新缓存区位置
                buffer.flip();
                while (buffer.hasRemaining()) {
                    writableByteChannel.write(buffer);
                }
                buffer.rewind();
            }
            fileChannel.close();

            System.out.println("文件压缩成功");


        } catch (Exception e) {
            log.error("batchZipFiles error  fileNames:");
        } finally {
            zipOutputStream.close();
            writableByteChannel.close();
            buffer.clear();
        }
    }


    // 删除生成的 mp3 文件
    @Override
    public void deleteFiles(String sourceFile) {

        // 检查文件路径是否为空
        if (sourceFile == null || sourceFile.isEmpty()) {
            System.out.println("文件路径为空");
        }

        File file = new File(sourceFile);

        // 检查文件是否存在
        if (!file.exists()) {
            System.out.println("文件不存在：" + sourceFile);
        }

        // 检查是否是文件
        if (!file.isFile()) {
            System.out.println("路径指向的不是文件：" + sourceFile);
        }

        // 尝试删除文件
        if (file.delete()) {
            System.out.println("文件删除成功：" + sourceFile);
        } else {
            System.out.println("文件删除失败：" + sourceFile);
        }
    }


}
