package com.zd.laboratory.service.impl;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import com.zd.common.core.utils.FfmpegConsole;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.security.utils.SaveUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zd.laboratory.mapper.LabAudioSynthesisMapper;
import com.zd.laboratory.domain.LabAudioSynthesis;
import com.zd.laboratory.service.ILabAudioSynthesisService;

import javax.servlet.http.HttpServletRequest;

/**
 * 音乐合成Service业务层处理
 *
 * @author zd
 * @date 2022-07-19
 */
@Service
public class LabAudioSynthesisServiceImpl implements ILabAudioSynthesisService
{
    @Autowired
    private LabAudioSynthesisMapper labAudioSynthesisMapper;

    @Autowired
    private FileConfigUtils fileConfigUtils;

    private static final Logger log = LoggerFactory.getLogger(LabAudioSynthesisServiceImpl.class);


    /**
     * 查询音乐合成
     *
     * @param id 音乐合成主键
     * @return 音乐合成
     */
    @Override
    public LabAudioSynthesis selectLabAudioSynthesisById(Long id)
    {
        return labAudioSynthesisMapper.selectLabAudioSynthesisById(id);
    }

    /**
     * 查询音乐合成列表
     *
     * @param labAudioSynthesis 音乐合成
     * @return 音乐合成
     */
    @Override
    public List<LabAudioSynthesis> selectLabAudioSynthesisList(LabAudioSynthesis labAudioSynthesis)
    {
        return labAudioSynthesisMapper.selectLabAudioSynthesisList(labAudioSynthesis);
    }

    @Override
    public List<LabAudioSynthesis> getListByIds(List<Long> ids){
        if (ids.isEmpty()){
            new ArrayList <>();
        }
        return labAudioSynthesisMapper.getListByIds(ids);
    }

    /**
     * 新增音乐合成
     *
     * @param labAudioSynthesis 音乐合成
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLabAudioSynthesis(LabAudioSynthesis labAudioSynthesis, HttpServletRequest request)
    {
        //设置其他公共字段
        SaveUtil.setCommonAttr(labAudioSynthesis);
        String baseUrl=request.getServerName() ;
        String url="";
        if(baseUrl.contains("192.168")){
            url=fileConfigUtils.getLocalUrl();
        }else{
            url=fileConfigUtils.getRemoteUrl();
        }
        String newMusic = java.util.UUID.randomUUID()+".mp3";
//        labAudioSynthesis.setMusicUrl(labAudioSynthesis.getMusicUrl().substring(labAudioSynthesis.getMusicUrl().indexOf("/")+8));
//        labAudioSynthesis.setBgmusicUrl(labAudioSynthesis.getBgmusicUrl().substring(labAudioSynthesis.getBgmusicUrl().indexOf("/")+8));
        String localFilePath = "/home/upload"+labAudioSynthesis.getMusicUrl().substring(labAudioSynthesis.getMusicUrl().substring(1).indexOf("/")+1,labAudioSynthesis.getMusicUrl().substring(1).indexOf("/")+13)+newMusic;

        labAudioSynthesis.setMusicUrl(url+labAudioSynthesis.getMusicUrl());
        labAudioSynthesis.setBgmusicUrl(url+labAudioSynthesis.getBgmusicUrl());

        labAudioSynthesis.setNewMusicUrl(labAudioSynthesis.getMusicUrl().substring(0,labAudioSynthesis.getMusicUrl().lastIndexOf("/"))+"/"+newMusic);
        int flag = labAudioSynthesisMapper.insertLabAudioSynthesis(labAudioSynthesis);
        if(flag>0){

//            FfmpegConsole console = new FfmpegConsole();
            String cmd ="/usr/bin/ffmpeg -i "+labAudioSynthesis.getMusicUrl()+" -i "+labAudioSynthesis.getBgmusicUrl()+" -filter_complex \"[0:a]aformat=sample_fmts=fltp:channel_layouts=stereo,volume="+labAudioSynthesis.getMusicVolume()+"[a0]; [1:a]aformat=sample_fmts=fltp:channel_layouts=stereo,volume="+labAudioSynthesis.getBgmusicVolume()+",adelay=5000|5000|5000,apad[a1]; [a0][a1]amerge=inputs=2[aout]\" -shortest -map \"[aout]\" -ac 2 "+localFilePath+"";
            log.error("cmd："+cmd);
            try {
                new Thread(()->this.exec(cmd)).start();
            }catch (Exception e) {
                e.printStackTrace();
                flag = 0;
            }
        }
        return flag;
    }

    /**
     * 修改音乐合成
     *
     * @param labAudioSynthesis 音乐合成
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateLabAudioSynthesis(LabAudioSynthesis labAudioSynthesis)
    {
        return labAudioSynthesisMapper.updateLabAudioSynthesis(labAudioSynthesis);
    }

    /**
     * 批量删除音乐合成
     *
     * @param ids 需要删除的音乐合成主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteLabAudioSynthesisByIds(Long[] ids)
    {
        return labAudioSynthesisMapper.deleteLabAudioSynthesisByIds(ids);
    }

    /**
     * 删除音乐合成信息
     *
     * @param id 音乐合成主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteLabAudioSynthesisById(Long id)
    {
        return labAudioSynthesisMapper.deleteLabAudioSynthesisById(id);
    }




    private Runtime runtime;
    private Process pro;

    public void exec(String cmd) {
        try {
            System.out.println("系统开始执行命令：\n" + cmd);
            runtime = Runtime.getRuntime();
            log.error("cmdBegin:"+cmd);
            pro = runtime.exec(new String[]{"sh", "-c", cmd});
            log.error("cmdEnd:"+cmd);
            InputStream stream = pro.getErrorStream();
            output(stream);
            pro.waitFor();
            this.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //            Thread.sleep(1000*10);
            System.out.println("已经停止");
            //            Thread.sleep(1000*5);
        }
    }

    public void stop() throws IOException {
        OutputStream ostream = pro.getOutputStream();
        ostream.write("q\r\n".getBytes());
        ostream.flush();
        ostream.close();
    }

    public void output(InputStream stream) {
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(stream, "utf-8");
            br = new BufferedReader(isr);
            String str;
            // 通过readLine()方法按行读取字符串
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(br, isr, stream);
        }
    }
    public void close(AutoCloseable ... acs) {
        for(AutoCloseable ac : acs) {
            try {
                ac.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
