package tech.glinfo.enbao.modules.mq;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tech.glinfo.enbao.common.contants.AppContants;
import tech.glinfo.enbao.common.utils.ByteUtils;
import tech.glinfo.enbao.common.utils.FileUtils;
import tech.glinfo.enbao.common.utils.RedisUtils;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.modules.sh.form.Protocol;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;

import java.util.List;

@Component("speakerService")
public class SpeakerService {

    private final static Logger logger = LoggerFactory.getLogger(SpeakerService.class);

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MqProducer mqProducer;

    public void sendToDevice(String deviceno, String path, String fileName, String type) {
//        String path = "/opt/work/upload/music/"+name+".mp3";
        String name = path.substring(path.lastIndexOf("/")+1);
        List<Object> datas = null;
        if(redisUtils.hasKey(AppContants.FILE_KEY+name)) {
            logger.info("redis存在改key值：{}", AppContants.FILE_KEY+name);
            datas = redisUtils.lGetAll(AppContants.FILE_KEY+name);
        } else {
            datas = FileUtils.convertToHex1(path);
            if(type.equals("00")) {
                redisUtils.lSet(AppContants.FILE_KEY + name, datas);
            }
        }
        String fileLength = datas.get(0).toString();
        StringBuffer fileInfo = new StringBuffer();
        String _path = path.toLowerCase();
        if(_path.endsWith("mp3")) {
            fileInfo.append("01");
        } else if(_path.endsWith("wav")) {
            fileInfo.append("00");
        } else {
            logger.warn("文件格式错误：{}", _path);
            return ;
        }
        fileInfo.append(fileLength);
        if(fileName == null) {
            fileName = path.substring(path.lastIndexOf("/")+1);
        }
        fileInfo.append(StringUtils.appendString(ByteUtils.int2Hex(fileName.length()), 2, true, "0"));
        fileInfo.append(StringUtils.appendString(ByteUtils.asciiToHex(fileName), 50, false, "0"));
        fileInfo.append(type);

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(deviceno);
        protocol.setDeviceType("0F");
        protocol.setCmd("15");//下发音频文件信息
        protocol.setContent(fileInfo.toString());
        String fileInfoProtocol = JSON.toJSONString(protocol);

        int recnt = datas.size() - 1;
        redisUtils.set(AppContants.SPEAKER_FILE_SEND+deviceno+"-count", recnt, 1200);

        new Thread(new Runnable() {
            @Override
            public void run() {
                //下发文件信息，其他的等回复再下发
                mqProducer.sendT(fileInfoProtocol);
            }
        }).start();

        saveToRedis(deviceno, datas);
    }

    /**
     * 播放/删除音乐
     * @param deviceno
     * @param fileName
     */
    public void delOrPlayMusic(String deviceno, String fileName, String type) {
        StringBuffer fileInfo = new StringBuffer();
        String _path = fileName.toLowerCase();
        if(_path.endsWith("mp3")) {
            fileInfo.append("01");
        } else if(_path.endsWith("wav")) {
            fileInfo.append("00");
        } else {
            logger.warn("文件格式错误：{}", _path);
            return ;
        }
        fileInfo.append("00000000");
        fileInfo.append(StringUtils.appendString(ByteUtils.int2Hex(fileName.length()), 2, true, "0"));
        fileInfo.append(StringUtils.appendString(ByteUtils.asciiToHex(fileName), 50, false, "0"));
        fileInfo.append(type);//0：在线播放 1：本地曲库中播放2：存储歌曲3：删除指定的歌曲

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(deviceno);
        protocol.setDeviceType("0F");
        protocol.setCmd("15");//下发音频文件信息
        protocol.setContent(fileInfo.toString());
        String fileInfoProtocol = JSON.toJSONString(protocol);
        mqProducer.sendT(fileInfoProtocol);
    }

    public void sendFileToDevice1(String deviceno, List<Object> datas) {
        String fileLength = datas.get(0).toString();
        StringBuffer fileInfo = new StringBuffer();
        fileInfo.append("01");
        fileInfo.append(fileLength);
        String fileName = "weather.mp3";
        fileInfo.append(StringUtils.appendString(ByteUtils.int2Hex(fileName.length()), 2, true, "0"));
        fileInfo.append(StringUtils.appendString(ByteUtils.asciiToHex(fileName), 52, false, "0"));

        ProtocolContent protocol = new ProtocolContent();
        protocol.setReceiveId(deviceno);
        protocol.setDeviceType("0F");
        protocol.setCmd("15");//下发音频文件信息
        protocol.setContent(fileInfo.toString());
        String fileInfoProtocol = JSON.toJSONString(protocol);
        int recnt = datas.size() - 1;
        redisUtils.set(AppContants.SPEAKER_FILE_SEND+deviceno+"-count", recnt, 1200);
        //下发文件信息，其他的等回复再下发
        mqProducer.sendT(fileInfoProtocol);
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                //下发文件信息，其他的等回复再下发
                mqProducer.sendT(fileInfoProtocol);
            }
        }).start();*/

        saveToRedis(deviceno, datas);
    }

    private void saveToRedis(String deviceno, List<Object> datas) {
        int count = datas.size();
        int recnt = count - 1;
        String sum = StringUtils.appendString(ByteUtils.int2Hex(recnt), 4, true, "0");
//        redisUtils.set(AppContants.SPEAKER_FILE_SEND+deviceno+"-count", recnt, 300);

        //下发文件内容
        for(int i=1; i<count; i++) {
            Protocol protocol1 = new Protocol();
            protocol1.setReceiveId(ByteUtils.asciiToHex(deviceno));
            protocol1.setDeviceType("0F");
            protocol1.setCmd("16");//下发音频文件信息
            StringBuffer fileContent = new StringBuffer();
            fileContent.append(sum);//总包数
            fileContent.append(StringUtils.appendString(ByteUtils.int2Hex(i), 4, true, "0"));//当前包数
            fileContent.append("0400");//数据长度
            fileContent.append(StringUtils.appendString(datas.get(i).toString(), 2048, true, "0"));//当前包数
            protocol1.setContent(fileContent.toString());
//            mqProducer.sendT(JSON.toJSONString(protocol1));
            redisUtils.set(AppContants.SPEAKER_FILE_SEND+deviceno+":content-"+i, protocol1.getSendContent(), 1200);
        }
    }

}
