package com.mortals.xhx.tts.UI;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.google.gson.Gson;
import com.mortals.xhx.common.utils.EncryptUtil;
import com.mortals.xhx.tts.bean.*;
import com.mortals.xhx.tts.utils.*;
import com.rabbitmq.client.*;
import javazoom.jl.player.Player;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.regex.Pattern;

/**
 * @author ZYW
 * @date 2024-07-25 9:26
 */
@Slf4j
public class MainWindow {
    String configPath = "F:\\\\config.prop";

    private static MainWindow instance = null;
    static JFrame frame;

    Gson gson = new Gson();

    String host = "192.168.0.98:11091";   //服务器地址
    private String register = "/m/api/register";     //register地址
    private String deviceInit = "/m/api/deviceInit";   //初始化信息获取地址
    private String deviceUpdate = "/m/api/deviceUpdate";  //手动注册地址
    private String checkVersion = "/m/api/checkVersion";  //升级地址
    private Integer delayTime = 0;   //启动延时
    private boolean english = false;    //英双语
    private boolean zang = false;   //藏双语
    private String speaker ="tb";   //播音员

    String deviceId = null;   //设备唯一编号

    String httpIndex = "http://";  //http 或 https访问

    boolean isOld = false;  //是否为利旧设备
    static int siteId = 0;  // 目前被选中的站点id
    static String siteCode = "";
    static String siteName = "";

    ConnectionFactory factory;
    // 联接信息
    Connection connection;
    // 频道
    Channel channel = null;

    static String rabbitHost = "";   //rabbitmq服务地址
    static String virtualHost = "";    //虚拟机地址
    static String downTopicFilter = "";  //消息队列
    static String username = "";  //rabbit账号
    static String password = "";  //rabbit密码
    static int port = 5672;  //rabbit端口
    int timeout = 86400000;   //消息时效  1天86400000
    static int enabled = 1;  //设备启用状态 (0.停止，1.启用)

    boolean isShow = true;   //判断本地是否有配置文件  有则设置窗口不可见

    String version = "1.0.0";

    static TextArea msgArea;   //rabbitmq消息显示区域
    static TextArea initArea;   //初始化消息显示区域
    static TextArea voiceArea;   //语音播报显示区域
    static JLabel noticeArea;    //底部提示消息区域

    static int msgIndex = 0;   //记录第几条rabbit消息  每1000条消息清空一次消息池区域

    static int voiceIndex = 0;   //记录第几条语音消息  每10条消息清空一次消息池区域

    BlockingDeque<FlowNumBean> flowNumBeanList = new LinkedBlockingDeque<FlowNumBean>();   //待播放的语音队列
    boolean isCalling = false;   //是否在播放语音  作为需要开始播放语音的标志

    Player player;

    //发音人
    String people;

    public static void main(String[] args) {
        //初始化窗口
        getInstance().initWindow(getInstance().configPath, getInstance().host, instance.version);
    }


    private MainWindow() {
    }

    public static MainWindow getInstance() {
        if (null == instance) {
            synchronized (MainWindow.class) {
                if (null == instance) {
                    instance = new MainWindow();
                }
            }
        }

        return instance;
    }

    /**
     * 初始化窗口
     * @param path
     */
    public void initWindow(String path,String hostUrl,String version) {
        this.configPath = path;
        host = hostUrl;
        this.version = version;



        //1、创建窗口对象
        frame = new JFrame("tts语音播报系统" );

        Container c = frame.getContentPane();//获取窗体主容器
        c.setLayout(null);

        //左侧rabbitmq消息输出区域
        JPanel leftPanel = new JPanel();
        leftPanel.setBorder(BorderFactory.createTitledBorder("消息队列"));
        leftPanel.setBounds(10,0,660,490);

        msgArea = new TextArea();
        msgArea.setLocation(10,10);
        msgArea.setPreferredSize(new Dimension(650,460));
        Font font = new Font("宋体", Font.PLAIN, 14);
        msgArea.setFont(font);
        msgArea.setForeground(Color.black);
        msgArea.setVisible(true);
        msgArea.setEditable(false);
        leftPanel.add(msgArea);


        frame.add(leftPanel);


        //右侧初始化消息
        JPanel rightPanel = new JPanel();
        rightPanel.setBounds(680,0,300,240);
        rightPanel.setBorder(BorderFactory.createTitledBorder("初始化消息"));


        initArea = new TextArea();
        initArea.setLocation(690,10);
        initArea.setPreferredSize(new Dimension(280,210));
        initArea.setFont(font);
        initArea.setForeground(Color.black);
        initArea.setVisible(true);
        initArea.setEditable(false);
        rightPanel.add(initArea);

        frame.add(rightPanel);


        //右侧下方语音播报消息
        JPanel voicePanel = new JPanel();
        voicePanel.setBounds(680,250,300,240);
        voicePanel.setBorder(BorderFactory.createTitledBorder("语音播报"));


        voiceArea = new TextArea();
        voiceArea.setLocation(690,10);
        voiceArea.setPreferredSize(new Dimension(280,210));
        voiceArea.setFont(font);
        voiceArea.setForeground(Color.black);
        voiceArea.setVisible(true);
        voiceArea.setEditable(false);
        voicePanel.add(voiceArea);

        frame.add(voicePanel);



        //文字说明区
        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setBorder(BorderFactory.createTitledBorder("说明"));
        bottomPanel.setBounds(10,490,970,80);

        noticeArea = new JLabel();
        Font font1 = new Font("Serif", Font.PLAIN, 14);
        noticeArea.setFont(font1);
        noticeArea.setForeground(Color.black);
        noticeArea.setVisible(true);

        bottomPanel.add(noticeArea,BorderLayout.CENTER);

        frame.add(bottomPanel);

        //合适的窗口大小
        frame.pack();
        //禁止改变窗口大小
        frame.setResizable(false);
        //设置窗口关闭退出软件  默认 JFrame.EXIT_ON_CLOSE会关闭所有窗口   DISPOSE_ON_CLOSE仅关闭当前窗口
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        // 获取屏幕尺寸
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;
        //设置窗口的位置和大小
        frame.setBounds((screenWidth-1000)/2,(screenHeight-610)/2,1000,610);
        //设置窗口对象不可见
        frame.setVisible(isShow);

        frame.addWindowListener(new WindowListener() {
            @Override
            public void windowOpened(WindowEvent e) {
            }

            @Override
            public void windowClosing(WindowEvent e) {

            }

            @Override
            public void windowClosed(WindowEvent e) {
                if(player != null){
                    player.close();
                    player = null;
                }
            }

            @Override
            public void windowIconified(WindowEvent e) {
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
            }

            @Override
            public void windowActivated(WindowEvent e) {
                //界面重现时重新读取配置
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
            }
        });

        pushInitMsg("程序开始启动");
        readConfig();
        if (deviceId == null) {
            deviceId = ReadMacAdrss.getMacAddress();
        }

        //读取本地配置文件
        reloadMessage();
        people = "sound/"+speaker+"/";
        //检测语音文件
        scanVoice();
        //初始化mq等数据
        initData();

    }

    private void scanVoice(){
        ClassLoader classLoader = MainWindow.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(people+"0.mp3");
        if(inputStream != null){
            pushInitMsg("播音员（"+speaker+"）检测成功");
        }else {
            pushInitMsg("播音员（"+speaker+"）检测失败，文件不存在");
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        pushInitMsg("访问register接口");
        DeviceCodeBean cb = new DeviceCodeBean(deviceId, "1");
        String result =  HttpRequest.post(httpIndex+host+register).body(gson.toJson(cb)).execute().body();
        ResultBean rb = gson.fromJson(result,ResultBean.class);
        if(rb.getCode() == 1){
            pushInitMsg("register访问成功");
            try {
                ContentBean contentBean = gson.fromJson(gson.toJson(rb.getData()), ContentBean.class);
                String data = EncryptUtil.myReEnscrt(contentBean.getContent(),Constant.ORDERNUM,Constant.DESKEY,Constant.AESKEY);
                log.info(data);
                ResultRabbitBean rmb = gson.fromJson(data, ResultRabbitBean.class);
                RabbitMessBean rabbitMessBean = rmb.getRabbmitInfo();
                rabbitHost = rabbitMessBean.getHost();
                virtualHost = rabbitMessBean.getVirtualHost();
                downTopicFilter = rabbitMessBean.getDownTopicFilter();
                timeout = Integer.parseInt(rabbitMessBean.getMessageTtl());
                username = rabbitMessBean.getUsername();
                password = rabbitMessBean.getPassword();
                port = rabbitMessBean.getPort();
                enabled = rmb.getDeviceInfo().getEnabled();
                reloadMessage();
                if(enabled == 0){  //设备被禁用了
                    pushRabbitMsg("设备已被禁用");
                }else {
                    initMQ();
                }

            }catch (Exception e){
                e.printStackTrace();
                pushInitMsg("register返回数据解密失败："+result);
            }
        }else {
            log.info(result);
            pushInitMsg("register返回异常："+rb.getMsg());
        }




        while (true){
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            FlowNumBean flowNumBean = new FlowNumBean(6, "A00"+(msgIndex%100), "010", "010", System.currentTimeMillis());
            pushRabbitMsg("请"+flowNumBean.getFlownum()+"号到"+flowNumBean.getWindowfromnum()+"号窗口");
            test(flowNumBean);


        }
    }

    private void initMQ(){
        // 创建连接工厂
        factory = new ConnectionFactory();
        factory.setHost(rabbitHost);
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setVirtualHost(virtualHost);
        factory.setPort(port);
        // 关键所在，指定线程池
        ExecutorService service = Executors.newFixedThreadPool(10);
        factory.setSharedExecutor(service);
        // 设置自动恢复
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(2);// 设置 每10s ，重试一次
        factory.setTopologyRecoveryEnabled(false);// 设置不重新声明交换器，队列等信息。
        // 创建连接和通道
        try {
            connection = factory.newConnection();

            channel = connection.createChannel();
            Map<String, Object> argMap = new HashMap<>();
            // 设置消息存活时间
            argMap.put("x-message-ttl",timeout);     //消息时效性
            channel.queueDeclare(downTopicFilter, true, false, false, argMap);

            // 设置一条条的应答
            channel.basicQos(0, 1, false);

            // 创建队列消费者
            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    try {
                        RabbitMessageBean rb = gson.fromJson(message, RabbitMessageBean.class);
                        String type = rb.getHeaders().getData().getMessageType();
                        if(type.equals("call")){  //表示叫号消息
                            String data = EncryptUtil.base64ToString(rb.getData());
                            pushRabbitMsg(data);
                            handleVoiceMsg(data);
                        }
                    } catch (Exception e) {
                        pushRabbitMsg("异常消息："+message);
                        log.error("异常消息："+message);
                    }


                }
            };
            // 监听队列，autoAck参数为true表示自动确认
            channel.basicConsume(downTopicFilter, true, consumer);

            pushInitMsg("消息服务链接成功");
            pushInitMsg("初始化完成");
        }catch (Exception e){
            pushInitMsg("消息服务链接异常："+e.toString());
            e.printStackTrace();
        }

//        while (true){
//            String data = "{\"qid\":670313,\"flownum\":\"ZH00"+(msgIndex%100)+"\",\"windowfromnum\":\"A05\"}";
//            pushRabbitMsg(data);
//            handleVoiceMsg(data);
//
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//
//
//        }

    }

    /**
     * 刷新底部提示消息
     */
    private void reloadMessage(){
        noticeArea.setText("<html>&emsp软件版本 V"+version+"&emsp;&emsp;设备编号："+deviceId+"&emsp;&emsp;服务器："+host+
                "&emsp;&emsp;英双语："+(english?"开启":"关闭") +"&emsp;&emsp;藏双语："+(zang?"开启":"关闭") +
                "&emsp;&emsp;播音员："+speaker +"<br>&emsp;消息服务器："+rabbitHost+ "&emsp;&emsp;&emsp;&emsp;虚拟机："+virtualHost+
                "&emsp;&emsp;&emsp;&emsp;队列："+downTopicFilter+"&emsp;&emsp;&emsp;&emsp;本机ip："+MacAddressReader.getLocalIp()+
                "<br>&emsp;设备状态："+(enabled == 0?"禁用":"启用")+"&emsp;&emsp;&emsp;&emsp;设备来源："+(isOld?"利旧设备":"新设备")+
                "&emsp;&emsp;&emsp;&emsp;站点编码："+siteCode +"&emsp;&emsp;&emsp;&emsp;站点名称："+siteName);
    }

    /**
     * 给消息加上时间戳
     * @param mess
     * @return
     */
    private String addTimeStamp(String mess){
        return " "+mess+" -- "+ DateUtil.date().toString("HH:mm:ss")+"\n";
    }

    /**
     * 输出rabbitmq消息
     * @param msg
     */
    private void pushRabbitMsg(String msg){
        if(msgIndex < 1000){
            msgIndex++;
        }else {
            msgIndex = 0;
            msgArea.setText("");
        }
        msgArea.append(addTimeStamp(msgIndex+":"+msg));
    }

    /**
     * 输出初始化消息
     * @param msg
     */
    private void pushInitMsg(String msg){
        initArea.append(addTimeStamp(msg));
    }

    /**
     * 输出语音播报消息
     * @param msg
     */
    private void pushVoiceMsg(String msg){
        if(voiceIndex < 10){
            voiceIndex++;
        }else {
            voiceIndex = 0;
            voiceArea.setText("");
        }
        voiceArea.append(addTimeStamp(msg));
    }

    /**
     * 添加语音播报消息
     * @param data
     */
    private void handleVoiceMsg(String data){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FlowNumBean fnb = gson.fromJson(data, FlowNumBean.class);
                    flowNumBeanList.putLast(fnb);
                    if(!isCalling) {
                        isCalling = true;
                        calling();
                    }
                } catch (Exception e) {
                    pushVoiceMsg("添加语音队列失败："+data);
                    log.error("添加语音队列失败："+data);
                }
            }
        }).start();

    }


    private void test(FlowNumBean flowNumBean){
        try {
            flowNumBeanList.putLast(flowNumBean);
            if(!isCalling){
                isCalling = true;
                calling();
            }
        } catch (InterruptedException e) {
            pushVoiceMsg("添加语音队列失败："+gson.toJson(flowNumBean));
            log.error("添加语音队列失败："+e);
        }
    }



    /**
     * 读取本地文件配置
     */
    private  void readConfig(){
        File file = new File(configPath);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error( "创建文件失败" ); ;
            }
        }

        Scanner sc = null ;
        try
        {
            sc = new Scanner( file ) ;

            String jsonString = sc.next();
            ConfigBean jo = gson.fromJson(jsonString, ConfigBean.class);


            if(jo != null){
                isShow = true;
                pushInitMsg("读取配置文件成功");
                if(jo.getDeviceId() != null){
                    deviceId = jo.getDeviceId();
                }

                if(jo.getHttpIndex() != null){
                    httpIndex = jo.getHttpIndex();
                }

                if(jo.getHost() != null){
                    host = jo.getHost();
                }

                if(jo.getRegister() != null){
                    register = jo.getRegister();
                }

                if(jo.getDeviceInit() != null){
                    deviceInit = jo.getDeviceInit();
                }

                if(jo.getDeviceUpdate() != null){
                    deviceUpdate = jo.getDeviceUpdate();
                }
                if(jo.getCheckVersion() != null){
                    checkVersion = jo.getCheckVersion();
                }
                delayTime = jo.getDelayTime();
                english = jo.isEnglish();
                zang = jo.isZang();
                if(jo.getSpeaker() != null){
                    speaker = jo.getSpeaker();
                }
                isOld = jo.isOld();
                siteId = jo.getSiteId();
                if(jo.getSiteName() != null){
                    siteName = jo.getSiteName();
                }
                if(jo.getSiteCode() != null){
                    siteCode = jo.getSiteCode();
                }
            }else {
                isShow =false;
                pushInitMsg("读取配置文件失败->配置文件为空");
            }


        }
        catch( Exception e )
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
//                log.error( "读写关闭" ) ;
                sc.close();
            }
            catch ( Exception e )
            {

            }
        }
    }


    private void calling(){
        try {
            if(flowNumBeanList.size() > 0){
                FlowNumBean flowNumBean = flowNumBeanList.takeFirst();
                String flownum = flowNumBean.getFlownum();
                String windownum = flowNumBean.getWindowfromnum();
                //语音拼接
                List<String> audioList = new ArrayList<>();
                audioList.add(people+"qing.mp3");
                //拼接排队号
                if(flownum.length() > 0){
                    for (int i = 0; i < flownum.length(); i++) {
                        audioList.add(people+flownum.charAt(i)+".mp3");
                    }
                }
                audioList.add(people+"haodao.mp3");
                //拼接窗口号
                if(speaker.equals("en")){    //发音人为英文发音
                    if(windownum.length() > 0){
                        Pattern p = Pattern.compile(".*[a-zA-Z]+.*");
                        if(p.matcher(windownum).matches()){  //窗口号中有字母
                            for (int i = 0; i < windownum.length(); i++) {
                                audioList.add(people+windownum.charAt(i)+".mp3");
                            }
                        }else {    //窗口号为纯数字
                            int num = Integer.parseInt(windownum);
                            if(num <= 20){
                                audioList.add(people+num+".mp3");
                            }else if(num < 100){
                                audioList.add(people+(num/10)+"0.mp3");
                                if(num%10 > 0){
                                    audioList.add(people+(num%10)+".mp3");
                                }
                            }else if(num <= 100){
                                audioList.add(people+"1.mp3");
                                audioList.add(people+"bai.mp3");
                            }
                            else if (num < 1000){
                                audioList.add(people+(num/100)+".mp3");
                                audioList.add(people+"bai.mp3");
                                audioList.add(people+"and.mp3");
                                if((num%100)/10 > 0){
                                    if(num%100 <= 20){
                                        audioList.add(people+num%100+".mp3");
                                    }else {
                                        audioList.add(people+((num%100)/10)+"0.mp3");
                                    }
                                }
                                audioList.add(people+(num%100%10)+".mp3");
                            }else {
                                if(windownum.length() > 0){
                                    for (int i = 0; i < windownum.length(); i++) {
                                        audioList.add(people+windownum.charAt(i)+".mp3");
                                    }
                                }
                            }
                        }
                    }
                }else {
                    if(windownum.length() > 0){
                        Pattern p = Pattern.compile(".*[a-zA-Z]+.*");
                        if(p.matcher(windownum).matches()){  //窗口号中有字母
                            for (int i = 0; i < windownum.length(); i++) {
                                audioList.add(people+windownum.charAt(i)+".mp3");
                            }
                        }else {    //窗口号为纯数字
                            int num = Integer.parseInt(windownum);
                            if(num < 10){
                                audioList.add(people+num+".mp3");
                            }else if(num < 100){
                                audioList.add(people+(num/10)+".mp3");
                                audioList.add(people+"shi.mp3");
                                if(num%10 > 0){
                                    audioList.add(people+(num%10)+".mp3");
                                }
                            }else if (num < 1000){
                                audioList.add(people+(num/100)+".mp3");
                                audioList.add(people+"bai.mp3");
                                if((num%100)/10 > 0){
                                    audioList.add(people+((num%100)/10)+".mp3");
                                    audioList.add(people+"shi.mp3");
                                }else {
                                    audioList.add(people+"0.mp3");
                                }
                                audioList.add(people+(num%100%10)+".mp3");
                            }else {
                                if(windownum.length() > 0){
                                    for (int i = 0; i < windownum.length(); i++) {
                                        audioList.add(people+windownum.charAt(i)+".mp3");
                                    }
                                }
                            }
                        }
                    }
                    audioList.add(people+"haochuangkou.mp3");
                }
                audioList.add(people+"kk.mp3");

                String url = SpliceMp3Util.heBingMp3(audioList);

                if(url != null){
                    if(speaker.equals("en")){
                        pushVoiceMsg("(英)请"+flownum+"号到"+windownum+"号窗口");
                    }else {
                        pushVoiceMsg("请"+flownum+"号到"+windownum+"号窗口");
                    }
                    FileInputStream fis = new FileInputStream(url);
                    BufferedInputStream bis = new BufferedInputStream(fis);

                    player = new Player(bis);
                    player.play();


                    isCalling = true;
                    if(english || zang){
                        callOtherLangage(flownum,windownum);
                    }else {
                        calling();
                    }


                }else {
                    isCalling = true;
                    calling();
                    pushVoiceMsg("语音包提取失败:"+url);
                }
            }else {
                isCalling = false;
                if(player != null){
                    player.close();
                    player = null;
                }
            }

        } catch (Exception e) {
            //如果异常  则放弃这条语音  继续循环
            isCalling = true;
            calling();
            pushVoiceMsg("语音播报异常:"+e.toString());
        }
    }

    private void callOtherLangage(String flownum,String windownum){
        try {
            //语音拼接
            List<String> audioList = new ArrayList<>();
            String englishPeople = "sound/en/";
            String zangPeople = "sound/zang/";

            if(english){  //英双语
                audioList.add(englishPeople+"qing.mp3");
                //拼接排队号
                if(flownum.length() > 0){
                    for (int i = 0; i < flownum.length(); i++) {
                        audioList.add(englishPeople+flownum.charAt(i)+".mp3");
                    }
                }
                audioList.add(englishPeople+"haodao.mp3");

                if(windownum.length() > 0){
                    Pattern p = Pattern.compile(".*[a-zA-Z]+.*");
                    if(p.matcher(windownum).matches()){  //窗口号中有字母
                        for (int i = 0; i < windownum.length(); i++) {
                            audioList.add(englishPeople+windownum.charAt(i)+".mp3");
                        }
                    }else {    //窗口号为纯数字
                        int num = Integer.parseInt(windownum);
                        if(num <= 20){
                            audioList.add(englishPeople+num+".mp3");
                        }else if(num < 100){
                            audioList.add(englishPeople+(num/10)+"0.mp3");
                            if(num%10 > 0){
                                audioList.add(englishPeople+(num%10)+".mp3");
                            }
                        }else if(num <= 100){
                            audioList.add(englishPeople+"1.mp3");
                            audioList.add(people+"bai.mp3");
                        }
                        else if (num < 1000){
                            audioList.add(englishPeople+(num/100)+".mp3");
                            audioList.add(englishPeople+"bai.mp3");
                            audioList.add(englishPeople+"and.mp3");
                            if((num%100)/10 > 0){
                                if(num%100 <= 20){
                                    audioList.add(englishPeople+num%100+".mp3");
                                }else {
                                    audioList.add(englishPeople+((num%100)/10)+"0.mp3");
                                }
                            }
                            audioList.add(englishPeople+(num%100%10)+".mp3");
                        }else {
                            if(windownum.length() > 0){
                                for (int i = 0; i < windownum.length(); i++) {
                                    audioList.add(englishPeople+windownum.charAt(i)+".mp3");
                                }
                            }
                        }
                    }
                }
            }else {
                audioList.add(zangPeople+"qing.mp3");
                //拼接排队号
                if(flownum.length() > 0){
                    for (int i = 0; i < flownum.length(); i++) {
                        audioList.add(zangPeople+flownum.charAt(i)+".mp3");
                    }
                }
                audioList.add(zangPeople+"haodao.mp3");

                if(windownum.length() > 0){
                    Pattern p = Pattern.compile(".*[a-zA-Z]+.*");
                    if(p.matcher(windownum).matches()){  //窗口号中有字母
                        for (int i = 0; i < windownum.length(); i++) {
                            audioList.add(zangPeople+windownum.charAt(i)+".mp3");
                        }
                    }else {    //窗口号为纯数字
                        int num = Integer.parseInt(windownum);
                        if(num < 10){
                            audioList.add(zangPeople+num+".mp3");
                        }else if(num < 100){
                            audioList.add(zangPeople+(num/10)+".mp3");
                            audioList.add(zangPeople+"shi.mp3");
                            if(num%10 > 0){
                                audioList.add(zangPeople+(num%10)+".mp3");
                            }
                        }else if (num < 1000){
                            audioList.add(zangPeople+(num/100)+".mp3");
                            audioList.add(zangPeople+"bai.mp3");
                            if((num%100)/10 > 0){
                                audioList.add(zangPeople+((num%100)/10)+".mp3");
                                audioList.add(zangPeople+"shi.mp3");
                            }else {
                                audioList.add(zangPeople+"0.mp3");
                            }
                            audioList.add(zangPeople+(num%100%10)+".mp3");
                        }else {
                            if(windownum.length() > 0){
                                for (int i = 0; i < windownum.length(); i++) {
                                    audioList.add(zangPeople+windownum.charAt(i)+".mp3");
                                }
                            }
                        }
                    }
                }
                audioList.add(zangPeople+"haochuangkou.mp3");
            }
            audioList.add(people+"kk.mp3");

            String url = SpliceMp3Util.heBingMp3(audioList);

            if(url != null){
                if(english){
                    pushVoiceMsg("(英)请"+flownum+"号到"+windownum+"号窗口");
                }else {
                    pushVoiceMsg("(藏)请"+flownum+"号到"+windownum+"号窗口");
                }

                FileInputStream fis = new FileInputStream(url);
                BufferedInputStream bis = new BufferedInputStream(fis);

                player = new Player(bis);
                player.play();

//                    pushVoiceMsg("播放完毕");
                isCalling = true;
                calling();

            }else {
                isCalling = true;
                calling();
                pushVoiceMsg("语音包提取失败:"+url);
            }
        }catch (Exception e) {
            //如果异常  则放弃这条语音  继续循环
            isCalling = true;
            calling();
            pushVoiceMsg("语音播报异常:"+e.toString());
        }



    }

}
