package tech.glinfo.enbao.modules.mq;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tech.glinfo.enbao.common.contants.AppContants;
import tech.glinfo.enbao.common.contants.Constants;
import tech.glinfo.enbao.common.utils.*;
import tech.glinfo.enbao.modules.service.BaiduApiService;
import tech.glinfo.enbao.modules.sh.entity.ShDeviceEntity;
import tech.glinfo.enbao.modules.sh.entity.ShInstructionParsingEntity;
import tech.glinfo.enbao.modules.sh.entity.ShSpeakerSongEntity;
import tech.glinfo.enbao.modules.sh.form.ProtocolContent;
import tech.glinfo.enbao.modules.sh.service.OtherShDeviceService;
import tech.glinfo.enbao.modules.sh.service.ShSpeakerSongService;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

//智能音箱
@Component("speakerParse")
public class SpeakerParse implements IParse {

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

    @Autowired
    private OtherShDeviceService otherShDeviceService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private SpeakerService speakerService;

    @Autowired
    private BaiduApiService baiduApiService;

    @Autowired
    private SpeechSynthesizerRestful speechSynthesizerRestful;

    @Autowired
    private AliyunChatbotUtils aliyunChatbotUtils;

    @Autowired
    private ShSpeakerSongService shSpeakerSongService;

    private static String uploadFolder = "/opt/work/upload/";

    @Value("${baidu.chatId}")
    private String chatId;

    @Override
    public Map<String, String> run(Object o, Map<String, String> datas) {
        ShDeviceEntity device = (ShDeviceEntity) o;
        Map<String, String> ws = new HashMap<>();
        String content = datas.get("content");

        if ("92".equals(datas.get("cmd")) && "00".equals(datas.get("content").substring(0, 2))) {//登录包
            //下发使用期限成功删除
            redisUtils.delete("device:sendcmd:" + device.getNumbering());
        } else
            //数据上报
            if ("01".equals(datas.get("cmd"))) {
                //校验设备时钟
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        logger.info("start checkDeviceTime");
                        checkDeviceTime(device.getNumbering(), content);
                    }
                }).start();
            } else if ("02".equals(datas.get("cmd"))) {//上报文件信息
//            redisUtils.deletes(AppContants.SPEAKER_FILE_RECEIVE+device.getNumbering()+"*");
                String fileType = content.substring(0, 2);
                int fileSize = Integer.valueOf(content.substring(2, 10), 16);
                int fileNameLength = Integer.valueOf(content.substring(10, 12), 16);
                String fileName = ByteUtils.hexToAscii(content.substring(12));
                logger.info("fileType:{},fileSize:{},fileNameLength:{},fileName:{}", fileType, fileSize, fileNameLength, fileName);
//            redisUtils.set(AppContants.SPEAKER_FILE_SEND + device.getNumbering() + "-stopsend", 1, 2);
            } /*else if("03".equals(datas.get("cmd"))) {//上报文件信息
            parseVoiceContent(device.getNumbering(), content);
//            redisUtils.set(AppContants.DEVICE_RECEIVE_EXPIRED + device.getNumbering(), 1, 1);
            return null;
        }*/ else if ("95".equals(datas.get("cmd"))) {//文件信息下发回复
//            startSendFile(device.getNumbering());
                String result = content.substring(0, 2);//0：OK  1：ERROR 2：BUSY
                if (result.equals("00")) {
                    if (content.length() > 4 && "03".equals(content.substring(2, 4))) {
                        //删除歌曲
                        String name = ByteUtils.hexToAscii(content.substring(4));
                        logger.info("###########删除歌曲：{}", name);
                        try {
                            Integer id = Integer.valueOf(name.substring(0, name.indexOf(".")));
                            ShSpeakerSongEntity songEntity = shSpeakerSongService.getById(id);
                            File file = new File(uploadFolder + "device" + songEntity.getDeviceId() + File.separator + songEntity.getName());
                            if (file.exists()) {
                                file.delete();
                            }
                            shSpeakerSongService.removeById(id);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    } else {
                        redisUtils.set(AppContants.SPEAKER_FILE_SEND + device.getNumbering() + "-cansend", "1", 240);
                    }
                }
                return null;
            } else if ("96".equals(datas.get("cmd")) && "01".equals(content)) {//出错了，停止下发
//            nextSendFile(device.getNumbering());
                redisUtils.set(AppContants.SPEAKER_FILE_SEND + device.getNumbering() + "-stopsend", 1, 5);
                return null;
            } else if ("00".equals(datas.get("cmd"))) {//解析后的中文
                parseText(device.getId(), device.getNumbering(), device.getSpareTwo(), content, null, device.getUserId());
                return null;
            }else if("998".equals(datas.get("cmd"))) {//文件下发后状态
                ShSpeakerSongEntity song = shSpeakerSongService.getById(content);
                if(song != null) {
                    ws = datas;
                    ws.put("id", content);
                    ws.put("name", song.getName());//歌曲名称
                    song.setStatus(1);
                    shSpeakerSongService.updateById(song);
                    return ws;
                }
                return null;
            }

        //查询解析指令集
        List<ShInstructionParsingEntity> cmds = otherShDeviceService.getDeviceInstructionList(device.getProductId(), datas.get("cmd"));
        if (cmds != null && cmds.size() > 0) {
            int length = 0;
            //解析设备报文内容
            Map<String, Object> map = new HashMap<>();
            for (ShInstructionParsingEntity cmd : cmds) {
                String hex = content.substring(length, length + cmd.getLength());
                String hex1;
                if (cmd.getType() == 1 || cmd.getType() == 2) {
                    hex1 = String.valueOf(Integer.valueOf(hex, 16));

                } else {
                    hex1 = ByteUtils.signHex2IntString(hex);
                }
                map.put(cmd.getName(), hex1);
                ws.put(cmd.getName(), hex1);
                length += cmd.getLength();
            }
            otherShDeviceService.updateDeviceData(JSON.toJSONString(map), device.getId());
        } else {
            ws = datas;
        }
        return ws;
    }

    /**
     * IoT语音解析后的中文处理
     *
     * @param deviceNo 设备编号
     * @param cityCode 音箱所致城市编号
     * @param result1  解析后的中文
     */
    private void parseText(Integer deviceId, String deviceNo, String cityCode, String result1, Integer relatHouse, Integer userId) {
        if (result1.indexOf("天气") > -1) {//查询天气
            if (StringUtils.isBlank(cityCode)) {
                String tips = "当前音箱还未设置位置哦，请先设置后再试试吧";
                logger.info("播放语音：{}", tips);
                sendCommonMsg(deviceNo, tips, "nolocation");
                return;
            }
            String weatherData = WeatherUtils.getWeatherData(cityCode);//城市编号，如广州市黄埔区：440112
            if (weatherData != null) {
                logger.info("天气信息：{}", weatherData);
                byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(weatherData);
                if (bytes1 != null) {
                    List<Object> datas = FileUtils.getDatas(bytes1);
                    speakerService.sendFileToDevice1(deviceNo, datas);
                }
            }
        } else if (result1.indexOf("音量") > -1) {//音量
            //回复好的
//            sendFileToDevice(deviceNo, "ok");
            sendCommonMsg(deviceNo, "好的", "ok");

            String content = null;
            if (result1.indexOf("增大") > -1 || result1.indexOf("调大") > -1) {
                content = "00";
            } else if (result1.indexOf("减小") > -1 || result1.indexOf("调小") > -1) {
                content = "01";
            } else if (result1.indexOf("最大") > -1) {
                content = "02";
            } else if (result1.indexOf("最小") > -1) {
                content = "03";
            }
            if (content != null) {
                ProtocolContent protocol = new ProtocolContent();
                protocol.setReceiveId(deviceNo);
                protocol.setDeviceType("0F");
                protocol.setContent(content);
                protocol.setCmd("14");
                mqProducer.sendT(JSON.toJSONString(protocol));
            }
        } else if (result1.indexOf("播放") > -1) {//播放音乐
//            String jsons = redisUtils.get(AppContants.SPEAKER_MUSIC_LIST + deviceNo);
            List<ShSpeakerSongEntity> list = shSpeakerSongService.list(new QueryWrapper<ShSpeakerSongEntity>().eq("device_id", deviceId).eq("status", 1).orderByDesc("id"));
            boolean flag = false;
            Integer id = null;
            String name = null;
            if (list != null && !list.isEmpty()) {
//                logger.info("当前设备歌曲列表：{}", jsons);
//                JSONArray objects = JSON.parseArray(jsons);
                String result = result1.replace("播放", "").trim();
                if (result.length() > 0) {//避免空字符串匹配成功bug
                    String _result = chineseNumber2Int(result);
                    for (ShSpeakerSongEntity song : list) {
//                        com.alibaba.fastjson.JSONObject o = (com.alibaba.fastjson.JSONObject) object;
                        String name1 = song.getName();
                        String _name1 = chineseNumber2Int(name1);
                        if (name1.contains(result) || name1.contains(_result) || _name1.contains(_result)) {
                            logger.info("匹配到歌曲：{}", name1);
                            id = song.getId();
                            name = song.getName();
                            flag = true;
                            break;
                        }
                    }
                    //如果是播放音乐，则随机播放一首歌曲
                    if(!flag && (result.contains("音乐") || result.contains("歌曲"))) {
                        ShSpeakerSongEntity songEntity = list.get(new Random().nextInt(list.size()));
                        id = songEntity.getId();
                        name = songEntity.getName();
                        flag = true;
                        logger.info("随机播放一首音乐：{}", name);
                    }
                } else {
                    String songName = "播放什么呢，没听清楚哦！请再说一次";
                    logger.info("播放语音：{}", songName);
//                    byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(songName);
//                    if(bytes1 != null) {
//                        List<Object> datas = FileUtils.getDatas(bytes1);
//                        speakerService.sendFileToDevice1(deviceNo, datas);
//                    }
                    sendCommonMsg(deviceNo, songName, "playblank");
                    return;
                }
            }
            if (flag) {
                String songName = "好的，开始播放" + name.substring(0, name.indexOf("."));
                logger.info("播放语音：{}", songName);
                byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(songName);
                if (bytes1 != null) {
                    List<Object> datas = FileUtils.getDatas(bytes1);
                    speakerService.sendFileToDevice1(deviceNo, datas);
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                while (redisUtils.hasKeys(AppContants.SPEAKER_FILE_SEND + deviceNo + "-starting-*")) {
                    logger.warn("当前有待下发完成的线程，休眠50毫秒之后重试！");
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //开始下发播放歌曲
                StringBuffer fileInfo = new StringBuffer();
                String _name = name.toLowerCase();
                if (_name.endsWith("mp3")) {
                    fileInfo.append("01");
                } else if (_name.endsWith("wav")) {
                    fileInfo.append("00");
                } else {
                    logger.warn("文件格式错误：{}", _name);
                    return;
                }
                String fileType = name.substring(name.lastIndexOf("."));
                String fileName = StringUtils.appendString(id + "", 4, true, "0") + fileType;

                ProtocolContent protocol = new ProtocolContent();
                protocol.setCmd("15");
                protocol.setDeviceType("0F");
                protocol.setReceiveId(deviceNo);
                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("01");//1：本地曲库中播放
                protocol.setContent(fileInfo.toString());
                String fileInfoProtocol = JSON.toJSONString(protocol);
                mqProducer.sendT(fileInfoProtocol);
            } else {
//                sendFileToDevice(deviceNo, "nosong");
                sendCommonMsg(deviceNo, "当前音箱音乐列表中没找到该歌曲哦", "nosong");
            }
        } else {//设备控制
            deviceController(deviceId, deviceNo, relatHouse, result1, userId);
        }
    }

    private void deviceController(Integer deviceId, String deviceNo, Integer relatHouse, String result1, Integer userId) {
        List<ShDeviceEntity> list = otherShDeviceService.getDeviceByFlag(userId);
        List<Map<String, Object>> list1 = new ArrayList<>();
        List<Map<String, Object>> list2 = new ArrayList<>();

        List<ShDeviceEntity> switchList = new ArrayList<>();
        try{
            String result2 = result1.replace('一', '1').replace('二', '2').replace('三', '3')
                    .replace('四', '4').replace('五', '5').replace('六', '6').replace('七', '7').replace('八', '8').replace('九', '9');

            for (ShDeviceEntity deviceEntity : list) {
                if (result1.contains(deviceEntity.getNumberingFlag()) || result2.contains(deviceEntity.getNumberingFlag())) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", deviceEntity.getId());
                    map.put("numbering", deviceEntity.getNumbering());
                    map.put("onlineStatus", deviceEntity.getOnlineStatus());
                    map.put("numberingFlag", deviceEntity.getNumberingFlag());
//                map.put("spareOne", deviceEntity.getSpareOne());
                    map.put("flag", 1);
                    list1.add(map);
                }
                if (deviceEntity.getNumbering().substring(0, 3).equals("002")) {
                    switchList.add(deviceEntity);
                    if (StringUtils.isNotBlank(deviceEntity.getSpareOne()) && (result1.contains(deviceEntity.getSpareOne()) || result2.contains(deviceEntity.getSpareOne()))) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", deviceEntity.getId());
                        map.put("numbering", deviceEntity.getNumbering());
                        map.put("onlineStatus", deviceEntity.getOnlineStatus());
                        map.put("numberingFlag", deviceEntity.getSpareOne());
//                    map.put("spareOne", deviceEntity.getSpareOne());
                        map.put("flag", 2);
                        list1.add(map);
                    }
                }

            }
            if (list1.size() > 0) {
                list1.sort((o1, o2) -> {
                    String numberingFlag1 = (String) o1.get("numberingFlag");
                    String numberingFlag2 = (String) o2.get("numberingFlag");
                    if (numberingFlag1.length() > numberingFlag2.length()) {
                        return 1;
                    } else if (numberingFlag1.length() < numberingFlag2.length()) {
                        return -1;
                    }
                    return 0;
                });
                list2.add(list1.get(list1.size() - 1));
                String numberingFlag1 = (String) list1.get(list1.size() - 1).get("numberingFlag");
                for (int i = 0; i < list1.size() - 1; i++) {
                    String numberingFlag2 = (String) list1.get(i).get("numberingFlag");
                    if (numberingFlag1.equals(numberingFlag2)) {
                        list2.add(list1.get(i));
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }



        if (list2.size() > 0) {
            for (Map<String, Object> deviceEntity : list2) {

                String keywords = redisUtils.get(Constants.DEVICE_KEYWORD_ONE);
                boolean one = false, two = false;
                int flag = 1;
                String keyword1;
                String keyword2 = null;
                if (keywords != null) {
                    JSONArray objects = JSON.parseArray(keywords);
                    for (Object object : objects) {
                        com.alibaba.fastjson.JSONObject o = (com.alibaba.fastjson.JSONObject) object;
                        String numbering = (String) deviceEntity.get("numbering");
                        if (o.getString("keyword").contains(numbering.substring(0, 3))) {
                            one = true;
                            logger.info("匹配到keyword:{}, id:{}", o.getString("keyword"), o.getInteger("id"));
                            String keywords1 = redisUtils.get(Constants.DEVICE_KEYWORD_ONE + "-" + o.getInteger("id"));
                            JSONArray objects1 = JSON.parseArray(keywords1);
                            boolean flag1 = false;
                            boolean flag2 = false;
                            com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();

                            if (numbering.substring(0, 3).equals("002")) {
                                flag1 = true;
                                flag2 = true;
                            }

                            if (!flag1) {
                                //匹配分号
                                for (Object value : objects1) {
                                    com.alibaba.fastjson.JSONObject o1 = (com.alibaba.fastjson.JSONObject) value;
                                    String keyword = o1.getString("keyword");
                                    if (keyword.contains(";")) {
                                        String[] split1 = keyword.split(";");
                                        flag1 = true;
                                        for (String s : split1) {
                                            if (!result1.contains(s)) {
                                                flag1 = false;
                                                break;
                                            } else {
                                                keyword2 = keyword;
                                            }
                                        }
                                        if (flag1) {
                                            logger.info("在分号匹配到keyword");
                                            jsonObject = o1;
                                            break;
                                        }
                                    }

                                }
                            }

                            //分号没匹配到则匹配逗号
                            if (!flag1) {
                                for (Object value : objects1) {
                                    com.alibaba.fastjson.JSONObject o1 = (com.alibaba.fastjson.JSONObject) value;
                                    String keyword = o1.getString("keyword");
                                    if (keyword.contains(",")) {
                                        String[] split1 = keyword.split(",");
                                        for (String s : split1) {
                                            if (result1.contains(s)) {
                                                jsonObject = o1;
                                                flag1 = true;
                                                keyword2 = keyword;
                                                break;
                                            }
                                        }
                                        if (flag1) {
                                            logger.info("在逗号匹配到keyword");
                                            break;
                                        }
                                    }

                                }
                            }
                            //分号、逗号没匹配到则匹配单个
                            if (!flag1) {
                                for (Object value : objects1) {
                                    com.alibaba.fastjson.JSONObject o1 = (com.alibaba.fastjson.JSONObject) value;
                                    String keyword = o1.getString("keyword");
                                    if (!keyword.contains(",") && !keyword.contains(";")) {
                                        if (result1.contains(keyword)) {
                                            logger.info("匹配到keyword");
                                            jsonObject = o1;
                                            keyword2 = keyword;
                                            flag1 = true;
                                        }
                                    }

                                }
                            }

                            if (flag1) {
                                if ((Integer) deviceEntity.get("onlineStatus") != 2) {
                                    sendCommonMsg(deviceNo, "设备不在线哦", "deviceOffline");
                                    flag = 2;
                                    break;
                                }
                                sendCommonMsg(deviceNo, "好的", "ok");
//                                redisUtils.set("reply" + numbering, deviceNo + "-" + "好的", 60);
                                if (flag2) { // 开关
                                    String cmd = null;
                                    if (result1.contains("开") && (Integer)deviceEntity.get("flag") == 1) {
                                        cmd = "{\"cmd\":\"18\",\"content\":\"0100000000000001\",\"deviceType\":\"02\",\"receiveId\":\"%s\"}";
                                    }else if (result1.contains("开") && (Integer)deviceEntity.get("flag") == 2) {
                                        cmd = "{\"cmd\":\"18\",\"content\":\"0001000000000002\",\"deviceType\":\"02\",\"receiveId\":\"%s\"}";
                                    }else if (result1.contains("关") && (Integer)deviceEntity.get("flag") == 1) {
                                        cmd = "{\"cmd\":\"18\",\"content\":\"0000000000000001\",\"deviceType\":\"02\",\"receiveId\":\"%s\"}";
                                    }else if (result1.contains("关") && (Integer)deviceEntity.get("flag") == 2) {
                                        cmd = "{\"cmd\":\"18\",\"content\":\"0000000000000002\",\"deviceType\":\"02\",\"receiveId\":\"%s\"}";
                                    }
                                    if (cmd == null) {
                                        break;
                                    }
                                    logger.info("匹配到指令1：{}", cmd);
                                    String cmd1 = String.format(cmd, numbering);
                                    logger.info("匹配到指令：{}", cmd1);
                                    mqProducer.sendT(cmd1);//发送到MQ转发到IoT下发设备
                                } else {
                                    JSONObject jsonObj = new JSONObject(jsonObject.getString("cmd"));
                                    String cmd = String.format(jsonObject.getString("cmd"), numbering);
                                    logger.info("匹配到指令：{}", jsonObj.toString());
                                    mqProducer.sendT(cmd);//发送到MQ转发到IoT下发设备
                                }

                                two = true;
                                break;
                            }
                            break;
                        }
                    }
                }
                if (flag == 1) {
                    if (!one || !two) {
                        logger.warn("当前语音无法匹配设备操作指令：{}", result1);
//                sendFileToDevice(deviceNo, "nocmd");
                        //交给AI对话处理
//                String chatbot = aliyunChatbotUtils.chatbot(result1);
                        String chatbot = baiduApiService.chat(result1, chatId);
                        if (chatbot != null) {
                            byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(chatbot);
                            if (bytes1 != null) {
                                List<Object> datas = FileUtils.getDatas(bytes1);
                                speakerService.sendFileToDevice1(deviceNo, datas);
                            }
                        }
                    }
                }

            }
        } else {
            //检查开关有没电视、空调红外指令匹配
            if ((result1.contains("电视") || result1.contains("空调")) && switchList.size() > 0) {
                String protocolJson = null;//发送协议JSON字符串
                boolean tv = result1.contains("电视");
//                boolean air = result1.contains("空调");
                boolean open = result1.contains("打开") || result1.contains("开启");
                boolean close = result1.contains("关闭") || result1.contains("停止");
                for (ShDeviceEntity deviceEntity : switchList) {
                    if(deviceEntity.getOnlineStatus() != 2) {
//                        logger.info("该设备不在线：{}", deviceEntity.getNumbering());
                        continue;
                    }
//                    logger.info("该设备在线：{}， {}", deviceEntity.getNumbering(), deviceEntity.getId());
                    if(tv) {
                        if(redisUtils.hasKey(AppContants.INFRARED_TV_KEY + deviceEntity.getId())) {
                            protocolJson = redisUtils.get(AppContants.INFRARED_TV_KEY + deviceEntity.getId());
                            break;//只匹配一个即可
                        }
                    } else {
                        if(redisUtils.hasKey(AppContants.INFRARED_AIR_KEY + deviceEntity.getId())) {
                            protocolJson = redisUtils.get(AppContants.INFRARED_AIR_KEY + deviceEntity.getId());
                            break;//只匹配一个即可
                        } else {
                            if(open && redisUtils.hasKey(AppContants.INFRARED_AIR_KEY + deviceEntity.getId() + "_1")) {
                                protocolJson = redisUtils.get(AppContants.INFRARED_AIR_KEY + deviceEntity.getId() + "_1");
                                break;//只匹配一个即可
                            } else if(close && redisUtils.hasKey(AppContants.INFRARED_AIR_KEY + deviceEntity.getId() + "_2")) {
                                protocolJson = redisUtils.get(AppContants.INFRARED_AIR_KEY + deviceEntity.getId() + "_2");
                                break;//只匹配一个即可
                            }
                        }
                    }
                }
                if(protocolJson != null) {
                    sendCommonMsg(deviceNo, "好的", "ok");
                    mqProducer.sendT(protocolJson);
                    logger.info("匹配到开关红外发送指令：{} =》 {}", result1, protocolJson);
                } else {
                    String chatbot = baiduApiService.chat(result1, chatId);
                    if (chatbot != null) {
                        byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(chatbot);
                        if (bytes1 != null) {
                            List<Object> datas = FileUtils.getDatas(bytes1);
                            speakerService.sendFileToDevice1(deviceNo, datas);
                        }
                    }
                }
            } else {
                logger.warn("当前语音无法匹配设备操作指令：{}", result1);
//                sendFileToDevice(deviceNo, "nocmd");
                //交给AI对话处理
//                String chatbot = aliyunChatbotUtils.chatbot(result1);
                String chatbot = baiduApiService.chat(result1, chatId);
                if (chatbot != null) {
                    byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(chatbot);
                    if (bytes1 != null) {
                        List<Object> datas = FileUtils.getDatas(bytes1);
                        speakerService.sendFileToDevice1(deviceNo, datas);
                    }
                }
            }

        }


    }

    private String getCmds(String[] datas, String frequency) {
        List<String> samples = new ArrayList<>();
        Map<String, String> samplesIndex = new HashMap<>();
        for (String code : datas) {
            if(!samplesIndex.containsKey(code)) {
                int i = new BigDecimal(Integer.valueOf(code) / 4).setScale(0, RoundingMode.HALF_UP).intValue();
                samples.add(ByteUtils.int2Hex(i, 4));
                samplesIndex.put(code, Integer.toHexString(samples.size()));
            }
        }
        while (samples.size()<16) {
            samples.add("0000");
        }
        //样版
//        StringBuffer samp = new StringBuffer("0324");
        StringBuffer samp = new StringBuffer();
        samp.append(ByteUtils.int2Hex(Integer.valueOf(frequency), 4));
        for (String s : samples) {
            samp.append(s);
        }
        int length1 = datas.length;
        if(length1%2 != 0) {
            length1++;
        }
        samp.append(ByteUtils.int2Hex(Integer.valueOf(length1), 4));
//        System.out.print(splitT(samp.toString()));

        //长度
        StringBuffer sbdata = new StringBuffer(samp);
        //循环查找数据所在位置
        for (String code : datas) {
            sbdata.append(samplesIndex.get(code));
        }
        int length = sbdata.length();

        if(length%2 != 0) {
            sbdata.append("0");
        }

        return sbdata.toString();
    }

    /**
     * 发送常用固定文字，用于缓存
     *
     * @param deviceNo
     * @param tips
     * @param key
     */
    private void sendCommonMsg(String deviceNo, String tips, String key) {
        List<Object> datas = null;
        if (redisUtils.hasKey(AppContants.FILE_KEY + key)) {
            logger.info("redis存在改key值：{}", AppContants.FILE_KEY + key);
            datas = redisUtils.lGetAll(AppContants.FILE_KEY + key);
        } else {
            byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(tips);
            if (bytes1 != null) {
                datas = FileUtils.getDatas(bytes1);
                redisUtils.delete(AppContants.FILE_KEY + key);
                redisUtils.lSet(AppContants.FILE_KEY + key, datas);
            }
        }
        if (datas != null) {
            speakerService.sendFileToDevice1(deviceNo, datas);
        }
    }

    /**
     * 发送常用固定文字
     *
     * @param deviceNo
     * @param tips
     */
    private void sendCommonMsg1(String deviceNo, String tips) {
        List<Object> datas;
        byte[] bytes1 = speechSynthesizerRestful.processPOSTRequest(tips);
        if (bytes1 != null) {
            datas = FileUtils.getDatas(bytes1);
            speakerService.sendFileToDevice1(deviceNo, datas);
        }
    }

    private void sendFileToDevice(String deviceno, String name) {
        String path = "/opt/work/upload/music/" + name + ".mp3";
        speakerService.sendToDevice(deviceno, path, null, "00");
    }

    //00000000000000006407E50A0B112433
    private void checkDeviceTime(String numbering, String content) {
        String hex = content.substring(18, 22);
        String year = String.valueOf(Integer.valueOf(hex, 16));
        String hex1 = content.substring(22, 24);
        String month = StringUtils.appendString(String.valueOf(Integer.valueOf(hex1, 16)), 2, true, "0");
        String hex2 = content.substring(24, 26);
        String day = StringUtils.appendString(String.valueOf(Integer.valueOf(hex2, 16)), 2, true, "0");
        String hex3 = content.substring(26, 28);
        String hour = StringUtils.appendString(String.valueOf(Integer.valueOf(hex3, 16)), 2, true, "0");
        String hex4 = content.substring(28, 30);
        String minute = StringUtils.appendString(String.valueOf(Integer.valueOf(hex4, 16)), 2, true, "0");
        String hex5 = content.substring(30, 32);
        String second = StringUtils.appendString(String.valueOf(Integer.valueOf(hex5, 16)), 2, true, "0");
        String date = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        logger.info("device-time : " + date);
        Date date1 = DateUtils.stringToDate(date, DateUtils.DATE_TIME_PATTERN);
        long diff = new Date().getTime() - date1.getTime();//这样得到的差值是毫秒级别
        long min = diff / (1000 * 60);
        //校验相差20分钟
        if (min > 10 || min < -10) {
            logger.info("upate-time : {}", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
            ProtocolContent protocol = new ProtocolContent();
            protocol.setCmd("11");
            protocol.setDeviceType("0F");
            protocol.setReceiveId(numbering);
            protocol.setContent(getContent((new Date())));
            mqProducer.sendT(JSON.toJSONString(protocol));
        }
    }

    private String getContent(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);                    //放入Date类型数据
        StringBuffer sb = new StringBuffer();
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.YEAR)));//获取年份
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.MONTH) + 1));                    //获取月份
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.DATE)));                    //获取日

//        sb.append(calendar.get(Calendar.HOUR));					//时（12小时制）
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.HOUR_OF_DAY)));                //时（24小时制）
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.MINUTE)));                    //分
        sb.append(ByteUtils.int2Hex(calendar.get(Calendar.SECOND)));                    //秒
        return sb.toString();
    }

    private String chineseNumber2Int(String str) {
        for (int i = 0; i < 10; i++) {
            str = str.replace("零一二三四五六七八九".charAt(i), (char) ('0' + i));
        }
        return str;
    }
}
