package com.mortals.xhx.tts.UI;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mortals.xhx.tts.bean.*;
import com.mortals.xhx.tts.utils.MacAddressReader;
import com.mortals.xhx.tts.utils.ReadMacAdrss;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


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

    private static SettingWindow 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 = "";

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


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


    private SettingWindow() {
    }

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

        return instance;
    }

    //初始化菜单
    public void SystemTrayInitial() {
        if (!SystemTray.isSupported()) {//判断系统是否支持托盘
            log.info("系统不支持托盘");
            return;
        }
        try {
            String title = "tts语音服务";//系统栏通知标题
            String company = "";//系统通知栏内容
            SystemTray systemTray = SystemTray.getSystemTray();//获取系统默认托盘

            ClassPathResource classPathResource = new ClassPathResource("img/icon.png");
            Image image = ImageIO.read(classPathResource.getInputStream());
//            Image image = Toolkit.getDefaultToolkit().getImage("img/icon.png");


            // Image image = Toolkit.getDefaultToolkit().getImage(absolutePath);//系统栏图标
            TrayIcon trayIcon = new TrayIcon(image, title + "\n" + company, createMenu());//添加图标,标题,内容,菜单
            trayIcon.setImageAutoSize(true);//设置图像自适应
//            trayIcon.addMouseListener(new MouseAdapter() {
//                @Override
//                public void mouseClicked(MouseEvent e) {
//                    super.mouseClicked(e);
//                    if(e.getClickCount() == 2){  //双击操作
//                    }
//                }
//            });
            systemTray.add(trayIcon);//添加托盘
            trayIcon.displayMessage(title, company, TrayIcon.MessageType.INFO);//弹出一个info级别消息框
        } catch (Exception e) {
            log.error("系统托盘图标加载失败", e);
        }
    }

    //托盘中的菜单
    private  PopupMenu createMenu() {
        PopupMenu menu = new PopupMenu();//创建弹出式菜单
        MenuItem exitItem = new MenuItem("exit");//创建菜单项
        exitItem.addActionListener(new ActionListener() {//给菜单项添加事件监听器，单击时退出系统
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        MenuItem settingItem = new MenuItem("setting");//创建菜单项
        settingItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //设置窗口对象可见
                if(frame != null){
                    frame.setVisible(true);
                }

            }
        });

        menu.add(settingItem);
        menu.add(exitItem);//添加退出系统菜单
        return menu;
    }



    /**
     * 初始化窗口
     * @param path
     */
    public void initWindow(String path,String hostUrl) {
        SystemTrayInitial();

        this.configPath = path;
        host = hostUrl;

//        log.info(path+"==="+url);

        readConfig();
        if(deviceId == null){
            deviceId = ReadMacAdrss.getMacAddress();
            writeConfig();
        }


        //AWT中接口LayoutManager有五个实现类：GridLayout（网格布局）、FlowLayout（流式布局）、CardLayout（卡片布局）、
        // GridBagLayout（网格包布局）和BorderLayout（边框布局）。为了简化开发，Swing引入了一个新的布局管理器BoxLayout。
        //1、创建窗口对象
        frame = new JFrame("配置窗口（设备编号："+deviceId+"）" );

        // 创建FlowLayout布局管理器并设置间距
        FlowLayout layout = new FlowLayout(FlowLayout.CENTER,5,15);

        frame.setLayout(layout);

        //http 或https访问设置
        JPanel radioPanel1 = new JPanel(new GridLayout(1,2,10,10));
        JLabel textArea1 = new JLabel("访问前缀");
        radioPanel1.add(textArea1);

        ButtonGroup httpGroup = new ButtonGroup();
        JRadioButton httpRadio = new JRadioButton("http://",httpIndex.equals("http://"));
        JRadioButton httpsRadio = new JRadioButton("https://",httpIndex.equals("https://"));
        httpRadio.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                httpIndex = "http://";
            }
        });
        httpsRadio.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                httpIndex = "https://";
            }
        });
        httpGroup.add(httpRadio);
        httpGroup.add(httpsRadio);
        radioPanel1.add(httpRadio);
        radioPanel1.add(httpsRadio);
        frame.add(radioPanel1);

        //访问地址
        JPanel JPanel2 = new JPanel(new FlowLayout());
        JLabel ipLabel = new JLabel("服务器IP:");
        JTextField jt = new JTextField();
        jt.setText(host);
        jt.setColumns(18);//设置文本框长度

        JButton jb = new JButton("测试链接");
        jb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    HttpUtil.get(httpIndex+jt.getText(),5000);
                    host = jt.getText();
                    JOptionPane.showMessageDialog(frame, "连接成功");
                }catch (Exception e1){
                    JOptionPane.showMessageDialog(frame, "服务器连接失败，请检查ip配置是否正确");
                }


            }
        });
        JPanel2.add(ipLabel);
        JPanel2.add(jt);
        JPanel2.add(jb);
        frame.add(JPanel2);

        //register地址
        JPanel JPanel3 = new JPanel(new FlowLayout());
        JLabel jLabel3 = new JLabel("注册地址:");
        JTextField jTextField3 = new JTextField();
        jTextField3.setText(register);
        jTextField3.setColumns(18);//设置文本框长度
        JPanel3.add(jLabel3);
        JPanel3.add(jTextField3);
        frame.add(JPanel3);


        //初始化地址
        JPanel JPanel4 = new JPanel(new FlowLayout());
        JLabel jLabel4 = new JLabel("初始化地址:");
        JTextField jTextField4 = new JTextField();
        jTextField4.setText(deviceInit);
        jTextField4.setColumns(18);//设置文本框长度
        JPanel4.add(jLabel4);
        JPanel4.add(jTextField4);
        frame.add(JPanel4);

        //手动注册地址
        JPanel JPanel5 = new JPanel(new FlowLayout());
        JLabel jLabel5 = new JLabel("手动注册地址:");
        JTextField jTextField5 = new JTextField();
        jTextField5.setText(deviceUpdate);
        jTextField5.setColumns(18);//设置文本框长度
        JPanel5.add(jLabel5);
        JPanel5.add(jTextField5);
        frame.add(JPanel5);

        //升级地址
        JPanel JPanel6 = new JPanel(new FlowLayout());
        JLabel jLabel6 = new JLabel("升级地址:");
        JTextField jTextField6 = new JTextField();
        jTextField6.setText(checkVersion);
        jTextField6.setColumns(18);//设置文本框长度
        JPanel6.add(jLabel6);
        JPanel6.add(jTextField6);
        frame.add(JPanel6);

        //启动延时
        JPanel JPanel7 = new JPanel(new FlowLayout());
        JLabel jLabel7 = new JLabel("启动延时（秒）:");
        JTextField jTextField7 = new JTextField();
        jTextField7.setText(delayTime+"");
        jTextField7.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
                String key="0123456789";
                if(key.indexOf(e.getKeyChar())<0){
                    e.consume();//如果不是数字则取消
                }
            }

            @Override
            public void keyPressed(KeyEvent e) {

            }

            @Override
            public void keyReleased(KeyEvent e) {

            }
        });
        jTextField7.setColumns(6);//设置文本框长度
        JPanel7.add(jLabel7);
        JPanel7.add(jTextField7);
        frame.add(JPanel7);


        //英双语
        JLabel jLabel8 = new JLabel("英双语:");
        JComboBox<String> jComboBox1 = new JComboBox<String>();//创建一个下拉列表框
        jComboBox1.setPreferredSize(new Dimension(80,21));        //设置坐标
        jComboBox1.addItem("是");
        jComboBox1.addItem("否");
        if(english){
            jComboBox1.setSelectedIndex(0);
        }else {
            jComboBox1.setSelectedIndex(1);
        }
        jComboBox1.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(jComboBox1.getSelectedIndex() == 0){
                    english = true;
                }else {
                    english = false;
                }
            }
        });
        frame.add(jLabel8);
        frame.add(jComboBox1);

        //藏双语
        JLabel jLabel9 = new JLabel("藏双语:");
        JComboBox<String> jComboBox2 = new JComboBox<String>();//创建一个下拉列表框
        jComboBox2.setPreferredSize(new Dimension(80,21));        //设置坐标
        jComboBox2.addItem("是");
        jComboBox2.addItem("否");
        if(zang){
            jComboBox2.setSelectedIndex(0);
        }else {
            jComboBox2.setSelectedIndex(1);
        }
        jComboBox2.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(jComboBox2.getSelectedIndex() == 0){
                    zang = true;
                }else {
                    zang = false;
                }
            }
        });
        frame.add(jLabel9);
        frame.add(jComboBox2);

        //播音员
        JLabel jLabel10 = new JLabel("播音员:");
        JComboBox<String> jComboBox3 = new JComboBox<String>();//创建一个下拉列表框
        jComboBox3.setPreferredSize(new Dimension(80,21));        //设置坐标
        jComboBox3.addItem("en");
        jComboBox3.addItem("tb");
        jComboBox3.addItem("xr");
        jComboBox3.addItem("xx");
        jComboBox3.addItem("xy");
        jComboBox3.addItem("yy");
        jComboBox3.addItem("zang");
        if(speaker.equals("en")){
            jComboBox3.setSelectedIndex(0);
        }
        if(speaker.equals("tb")){
            jComboBox3.setSelectedIndex(1);
        }
        if(speaker.equals("xr")){
            jComboBox3.setSelectedIndex(2);
        }
        if(speaker.equals("xx")){
            jComboBox3.setSelectedIndex(3);
        }
        if(speaker.equals("xy")){
            jComboBox3.setSelectedIndex(4);
        }
        if(speaker.equals("yy")){
            jComboBox3.setSelectedIndex(5);
        }
        if(speaker.equals("zang")){
            jComboBox3.setSelectedIndex(6);
        }
        jComboBox3.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if(jComboBox3.getSelectedIndex() == 0){
                    speaker = "en";
                }
                if(jComboBox3.getSelectedIndex() == 1){
                    speaker = "tb";
                }
                if(jComboBox3.getSelectedIndex() == 2){
                    speaker = "xr";
                }
                if(jComboBox3.getSelectedIndex() == 3){
                    speaker = "xx";
                }
                if(jComboBox3.getSelectedIndex() == 4){
                    speaker = "xy";
                }
                if(jComboBox3.getSelectedIndex() == 5){
                    speaker = "yy";
                }
                if(jComboBox3.getSelectedIndex() == 6){
                    speaker = "zang";
                }

            }
        });
        frame.add(jLabel10);
        frame.add(jComboBox3);


        //保存本地配置按钮
        JButton jb1 = new JButton("保存本地配置");
        jb1.setPreferredSize(new Dimension(460,30));
        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                writeConfig();
                JOptionPane.showMessageDialog(frame,"保存成功！");
            }
        });

        frame.add(jb1);






        //利旧设备
        JPanel radioPanel2 = new JPanel(new GridLayout(1,2,10,10));
        JLabel textArea2 = new JLabel("利旧设备");
        radioPanel2.add(textArea2);

        ButtonGroup buttonGroup2 = new ButtonGroup();
        JRadioButton radioButton1 = new JRadioButton("是",isOld);
        JRadioButton radioButton2 = new JRadioButton("否",!isOld);
        radioButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isOld = true;
            }
        });
        radioButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                isOld =false;
            }
        });
        buttonGroup2.add(radioButton1);
        buttonGroup2.add(radioButton2);
        radioPanel2.add(radioButton1);
        radioPanel2.add(radioButton2);
        frame.add(radioPanel2);

        //站点列表
        JPanel jPanel7 = new JPanel();
        JLabel siteLabel = new JLabel("站点列表:");
        jPanel7.add(siteLabel);
        try {
            String siteString =  HttpUtil.get(httpIndex+host+deviceInit,30000);
            log.info(siteString);
            ResultBean siteResult = gson.fromJson(siteString,ResultBean.class);
            if(siteResult.getCode() == 1){
                Type type = new TypeToken<DeviceInitBean>(){}.getType();
                DeviceInitBean deviceInitBean = gson.fromJson(gson.toJson(siteResult.getData()),type);
                ArrayList<SiteListBean> siteList = deviceInitBean.getSiteList();

                //站点列表

                JComboBox<String> siteBox = new JComboBox<String>();//创建一个下拉列表框
                siteBox.setPreferredSize(new Dimension(220,21));        //设置坐标
                int selectedIndex = 0;
                for (int i = 0; i < siteList.size(); i++) {
                    SiteListBean siteBean = siteList.get(i);
                    siteBox.addItem(siteBean.getSiteName());

                    if(siteId == siteBean.getSiteId()){
                        selectedIndex = i;
                    }

                }

                siteBox.setSelectedIndex(selectedIndex);
//            siteId = siteList.get(siteBox.getSelectedIndex()).getId();
//            siteName = siteList.get(siteBox.getSelectedIndex()).getSiteName();
                siteBox.addItemListener(new ItemListener() {
                    @Override
                    public void itemStateChanged(ItemEvent e) {
                        if (e.getStateChange() == ItemEvent.SELECTED) {
                            siteId = siteList.get(siteBox.getSelectedIndex()).getSiteId();
                            siteName = siteList.get(siteBox.getSelectedIndex()).getSiteName();
                            siteCode = siteList.get(siteBox.getSelectedIndex()).getSiteCode();
                            log.info("选中站点为:"+siteName);
                        }
                    }
                });
                jPanel7.add(siteBox);
                if(siteId == 0){  //初始化查到siteid为0 则传入站点列表第一个站点id
                    siteId = siteList.get(siteBox.getSelectedIndex()).getSiteId();
                }

            }else {
                JOptionPane.showMessageDialog(frame, "站点列表接口（"+httpIndex+host+deviceInit+"）访问失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        frame.add(jPanel7);

        //上传站点信息
        JButton jb2 = new JButton("上传站点信息");
        jb2.setPreferredSize(new Dimension(460,30));
        jb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    DeviceUpdateBean db = new DeviceUpdateBean();
                    db.setDeviceCode(deviceId);
                    db.setSiteId(siteId);
                    db.setSiteCode(siteCode);
                    db.setSiteName(siteName);
                    db.setProductId(4);   //集中屏id为4
                    db.setSource(isOld?0:1);   //1为新设备  0为利旧设备
                    String result =  HttpRequest.post(httpIndex+host+deviceUpdate).body(gson.toJson(db)).execute().body();
                    log.info(result);
                    ResultBean rb = gson.fromJson(result,ResultBean.class);
                    if(rb.getCode() == 1){
                        writeConfig();
                        JOptionPane.showMessageDialog(frame, "上传成功,重启软件生效");
                    }else {
                        JOptionPane.showMessageDialog(frame, rb.getMsg());
                    }

                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        });

        frame.add(jb2);


        //合适的窗口大小
        frame.pack();
        //禁止改变窗口大小
        frame.setResizable(false);
        //设置窗口关闭退出软件  默认 JFrame.EXIT_ON_CLOSE会关闭所有窗口   DISPOSE_ON_CLOSE仅关闭当前窗口
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        //设置窗口的位置和大小
        frame.setBounds(660,340,600,400);
        //设置窗口对象不可见
        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) {
                //窗口关闭释放摄像头资源

            }

            @Override
            public void windowIconified(WindowEvent e) {
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
            }

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

            @Override
            public void windowDeactivated(WindowEvent 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 = false;
                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 = true;
                log.info( "配置文件为空" ); ;
            }


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

            }
        }
    }

    /**
     * 修改本地文件配置
     */
    private  void writeConfig(){

        ConfigBean cb = new ConfigBean();
        cb.setDeviceId(deviceId);
        cb.setHttpIndex(httpIndex);
        cb.setHost(host);
        cb.setRegister(register);
        cb.setDeviceInit(deviceInit);
        cb.setDeviceUpdate(deviceUpdate);
        cb.setDelayTime(delayTime);
        cb.setEnglish(english);
        cb.setZang(zang);
        cb.setSpeaker(speaker);
        cb.setCheckVersion(checkVersion);
        cb.setOld(isOld);
        cb.setSiteId(siteId);
        cb.setSiteCode(siteCode);
        cb.setSiteName(siteName);

        File file = new File(configPath);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
            }
        }

        FileWriter fileWriter = null ;
        BufferedWriter bufferedWriter = null ;  //FileWriter和BufferedWriter的初始化需要监听，此处只定义不初始化

        try
        {
            fileWriter = new FileWriter( file ) ;
            bufferedWriter = new BufferedWriter( fileWriter ) ;

            bufferedWriter.write( gson.toJson(cb) ) ;

        }
        catch( Exception e )
        {
           e.printStackTrace();
        }
        finally
        {
            try
            {

                if(bufferedWriter != null){
                    bufferedWriter.close(); //随手关闭文件,此处注意关闭顺序不能错误
                }
                if(fileWriter != null){
                    fileWriter.close();
                }
            }
            catch( IOException ioe )
            {

            }

        }

    }

}
