package fr.zng.xxzx.main;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle;

import org.jdesktop.application.SingleFrameApplication;

import fr.zng.xxzx.biz.WebSessionDto;
import fr.zng.xxzx.common.cacheData.ZngCacheData;
import fr.zng.xxzx.common.dao.CityWeatherDao;
import fr.zng.xxzx.common.dao.EquipDao;
import fr.zng.xxzx.common.dao.MqttConfigDao;
import fr.zng.xxzx.common.dao.impl.CityWeatherDaoImpl;
import fr.zng.xxzx.common.dao.impl.EquipDaoImpl;
import fr.zng.xxzx.common.dao.impl.MqttConfigDaoImpl;
import fr.zng.xxzx.common.entity.EquipEntity;
import fr.zng.xxzx.common.entity.MqttConfigEntity;
import fr.zng.xxzx.common.util.CommUtil;
import fr.zng.xxzx.common.util.DesUtil;
import fr.zng.xxzx.mqtt2.CheckMqttServer2;
import fr.zng.xxzx.mqtt2.Server2;
import fr.zng.xxzx.netty.InboundHandler;
import fr.zng.xxzx.netty.OutboundHandler;
import fr.zng.xxzx.netty.dispatcher.InboundDispatcher;
import fr.zng.xxzx.util.StringUtil;
import fr.zng.xxzx.util.WebServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
/**
 * 
 */
public class XmtApplication extends SingleFrameApplication {
	private JPanel jPanel1;
	private JScrollPane jScrollPane1;
	private JButton upgrade_jb;
	private JScrollPane jScrollPane2;
	private JButton clearjb;
	private JButton clearWeb;
	private JTextArea unoJta;
	private JButton local;
	private JButton ver;
	private JButton open;
	private JPanel jPanel4;
	private JComboBox<String> online_jcb = null;
	private JPanel jPanel2;
	ChannelFuture f;
	private JButton apk;
	private JButton sp;
	private JButton pcd;
	private JButton ucd;
	private JTextArea msgJta;
	private JButton cleareq;
	private JButton clearws;
	private JComboBox lockty;
	static int isClose;

	@Override
	protected void startup() {
		{
			getMainFrame().setSize(987, 768);
		}
		{
			jPanel1 = new JPanel();
			getMainFrame().getContentPane().add(jPanel1);
			BorderLayout jPanel1Layout = new BorderLayout();
			jPanel1.setLayout(jPanel1Layout);
			{
				jPanel2 = new JPanel();
				GroupLayout jPanel2Layout = new GroupLayout((JComponent) jPanel2);
				jPanel1.add(jPanel2, BorderLayout.CENTER);
				jPanel2.setLayout(jPanel2Layout);
				jPanel2.setName("contentPanel");
				{
					jScrollPane1 = new JScrollPane();
					jScrollPane1.setName("jScrollPane1");
					{
						unoJta = new JTextArea();
						jScrollPane1.setViewportView(unoJta);
						// 自动换行
						unoJta.setLineWrap(true);
						unoJta.setName("unoJta");
//						unoJta.setPreferredSize(new java.awt.Dimension(969, 298));
					}
				}
				{
					jScrollPane2 = new JScrollPane();
					jScrollPane2.setName("jScrollPane2");
					{
						msgJta = new JTextArea();
						jScrollPane2.setViewportView(msgJta);
						msgJta.setName("msgJta");
						msgJta.setPreferredSize(new java.awt.Dimension(969, 472));
					}
				}
				{
					jPanel4 = new JPanel();
					jPanel4.setLayout(null);
					{
						online_jcb = new JComboBox<String>();
						jPanel4.add(online_jcb);
						online_jcb.setName("online_jcb");
						online_jcb.setBounds(5, 10, 157, 21);
					}
					{
						upgrade_jb = new JButton();
						jPanel4.add(upgrade_jb);
						upgrade_jb.setName("flash");
						upgrade_jb.setBounds(172, 9, 73, 32);
						upgrade_jb.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {

								ComboBoxModel<String> jbimeiModel = null;
								if (ZngCacheData.sessionDeviceStatus.isEmpty()) {
									jbimeiModel = new DefaultComboBoxModel<String>(new String[] { "" });
								} else {
									Set<String> st = ZngCacheData.sessionDeviceStatus.keySet();
									String[] strings = new String[st.size()];
									jbimeiModel = new DefaultComboBoxModel<String>(st.toArray(strings));
								}
								online_jcb.setModel(jbimeiModel);

							}
						});
					}
					{
						open = new JButton();
						jPanel4.add(open);
						open.setBounds(375, 9, 71, 32);
						open.setName("open");
						open.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								// 获取当前时间的时间戳
								long time = System.currentTimeMillis() / 1000;
								// 时间戳加密
								String enTime = DesUtil.encryptDES(time + "000000", InboundDispatcher.PASSWORD);

								String equipno = online_jcb.getSelectedItem().toString();
								EquipDao dao = new EquipDaoImpl();

								EquipEntity en = new EquipEntity();
								en.setImei(equipno);
								List<EquipEntity> list = dao.searchByno(en);

								String loctyp = lockty.getSelectedItem().toString();

								// 用户ID 00000010
								String replyData = CommUtil.doMakeData("2001", list.get(0).getVer(), equipno,
										String.valueOf(time), enTime, loctyp + "00000010");
								// 回复
								Channel ch = ZngCacheData.sessionMap.get(ZngCacheData.sessionCodeIP.get(equipno))
										.getChannel();
								ch.writeAndFlush(replyData);
								ch.flush();
								CommUtil.doPrint(msgJta, "", " 发送数据 .." + replyData);
							}
						});
					}

					{
						ver = new JButton();
						jPanel4.add(ver);
						ver.setBounds(461, 9, 64, 32);
						ver.setName("ver");
						ver.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {

								String equipno = online_jcb.getSelectedItem().toString();

								String ipAddr = ZngCacheData.sessionCodeIP.get(equipno);

								ZngCacheData.sessionMap.get(ipAddr).setHeardRet("10");
							}
						});
					}
					{
						local = new JButton();
						jPanel4.add(local);
						local.setBounds(535, 9, 62, 32);
						local.setName("local");
						local.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {

								String equipno = online_jcb.getSelectedItem().toString();

								String ipAddr = ZngCacheData.sessionCodeIP.get(equipno);

								ZngCacheData.sessionMap.get(ipAddr).setHeardRet("11");
							}
						});
					}
					{
						clearjb = new JButton();
						jPanel4.add(clearjb);
						clearjb.setBounds(608, 9, 80, 32);
						clearjb.setName("clearjb");
						clearjb.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								msgJta.setText("");
							}
						});
					}
					{
						clearWeb = new JButton();
						jPanel4.add(clearWeb);
						;
						clearWeb.setBounds(698, 9, 88, 32);
						clearWeb.setName("clearWeb");
						clearWeb.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								unoJta.setText("");
							}
						});
					}
					{
						ComboBoxModel locktyModel = new DefaultComboBoxModel(new String[] { "01", "02", "03" });
						lockty = new JComboBox();
						jPanel4.add(lockty);
						lockty.setModel(locktyModel);
						lockty.setBounds(262, 10, 95, 31);
					}
					{
						clearws = new JButton();
						jPanel4.add(clearws);
						clearws.setName("jButton1");
						clearws.setBounds(796, 9, 68, 32);
						clearws.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								String code = online_jcb.getSelectedItem().toString();

								String ip = ZngCacheData.sessionWebCodeIPDevice.get(code);
								if (ip == null) {
									return;
								}
								// 获取web对象
								WebSessionDto wsd = ZngCacheData.sessionWebMap.get(ip);
								if (wsd != null) {
									wsd.getChannel().close();
								}
								ZngCacheData.sessionWebMap.remove(ip);
								ZngCacheData.sessionWebIPCodeDevice.remove(ip);
								ZngCacheData.sessionWebCodeIPDevice.remove(code);
								ZngCacheData.sessionWebCodeUsed.remove(code);
								try {
									finalize();
								} catch (Throwable e1) {
									e1.printStackTrace();
								}
							}
						});
					}
					{
						cleareq = new JButton();
						jPanel4.add(cleareq);
						cleareq.setName("jButton1");
						cleareq.setBounds(874, 9, 68, 32);
						cleareq.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								String code = online_jcb.getSelectedItem().toString();

								if (!StringUtil.isEmpty(code) && !"null".equals(code)) {
									String ip = ZngCacheData.sessionCodeIP.get(code);
									if (!StringUtil.isEmpty(ip)) {
										// ip + 设备号
										ZngCacheData.sessionIPCode.remove(ip);
									}
									// 设备号 + ip
									ZngCacheData.sessionCodeIP.remove(code);

									// 设备号 + 状态
									ZngCacheData.sessionDeviceStatus.remove(code);
									// 设备号 + 版本号
									ZngCacheData.sessionCodeVersion.remove(code);
									// 设备号 + 是否正在使用
									ZngCacheData.sessionWebCodeUsed.remove(code);
								}
								try {
									finalize();
								} catch (Throwable e1) {
									e1.printStackTrace();
								}
							}
						});
					}
					{
						ucd = new JButton();
						jPanel4.add(ucd);
						ucd.setBounds(108, 51, 105, 23);
						ucd.setName("ucd");
						ucd.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								// TODO Auto-generated method stub

								String equipno = online_jcb.getSelectedItem().toString();

								String ipAddr = ZngCacheData.sessionCodeIP.get(equipno);

								ZngCacheData.sessionMap.get(ipAddr).setHeardRet("12");
							}
						});
					}
					{
						pcd = new JButton();
						jPanel4.add(pcd);
						pcd.setBounds(234, 51, 105, 23);
						pcd.setName("pcd");
						pcd.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								// TODO Auto-generated method stub

								String equipno = online_jcb.getSelectedItem().toString();

								String ipAddr = ZngCacheData.sessionCodeIP.get(equipno);

								ZngCacheData.sessionMap.get(ipAddr).setHeardRet("13");
							}
						});
					}
					{
						sp = new JButton();
						jPanel4.add(sp);
						sp.setBounds(354, 51, 105, 23);
						sp.setName("sp");
						sp.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {
								// TODO Auto-generated method stub

								String equipno = online_jcb.getSelectedItem().toString();

								String ipAddr = ZngCacheData.sessionCodeIP.get(equipno);

								ZngCacheData.sessionMap.get(ipAddr).setHeardRet("14");
							}
						});
					}
					{
						apk = new JButton();
						jPanel4.add(apk);
						apk.setBounds(485, 51, 105, 23);
						apk.setName("apk");
						apk.addActionListener(new ActionListener() {

							@Override
							public void actionPerformed(ActionEvent e) {

								String equipno = online_jcb.getSelectedItem().toString();

								String ipAddr = ZngCacheData.sessionCodeIP.get(equipno);

								ZngCacheData.sessionMap.get(ipAddr).setHeardRet("15");
							}
						});
					}
				}
				jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup()
						.addComponent(jScrollPane1, GroupLayout.Alignment.LEADING, 0, 971, Short.MAX_VALUE)
						.addComponent(jScrollPane2, GroupLayout.Alignment.LEADING, 0, 971, Short.MAX_VALUE)
						.addComponent(jPanel4, GroupLayout.Alignment.LEADING, 0, 971, Short.MAX_VALUE));
				jPanel2Layout.setVerticalGroup(jPanel2Layout.createSequentialGroup()
						.addComponent(jPanel4, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)
						.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 293, GroupLayout.PREFERRED_SIZE)
						.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
						.addComponent(jScrollPane2, 0, 462, Short.MAX_VALUE).addContainerGap());
			}
			{

			}
		}
		show(jPanel1);
//		doStartService();
		// 开启WEBSERVER
//		new WebServer().stratHttpServer();
		// 天气预报
//		getWeather();

//		// 开启mqtt服务端
//		MqttConfigDao config = new MqttConfigDaoImpl();
//		MqttConfigEntity en = config.getConfigDetail();
//		if(en==null) {
//			CommUtil.doPrint(unoJta, "MQTT:", "MQTT参数表未配置");
//			changeConnectState(0);
//		} else {
//			if(setServerConfig(en)) {
//				new CheckMqttServer(unoJta).start();
//			} else {
//				CommUtil.doPrint(unoJta, "MQTT:", "MQTT参数表未配置完全,无法连接MQTT服务器");
//				changeConnectState(0);
//			}
//		}
		// 开启mqtt服务端
		MqttConfigDao config = new MqttConfigDaoImpl();
		MqttConfigEntity en = config.getConfigDetail();
		if (en == null) {
			CommUtil.doPrint(unoJta, "MQTT:", "MQTT参数表未配置");
			changeConnectState(0);
		} else {
			if (setServerConfig(en)) {
				new CheckMqttServer2(unoJta,en).start();
			} else {
				CommUtil.doPrint(unoJta, "MQTT:", "MQTT参数表未配置完全,无法连接MQTT服务器");
				changeConnectState(0);
			}
		}

		/*
		 * new Thread(new Runnable() {
		 * 
		 * @Override public void run() { int port = 443; String sslMode = "CA"; String
		 * sPro = "WS"; try { new WebSocketServerSSL(unoJta,port, sslMode, sPro).run();
		 * } catch (Exception e) { e.printStackTrace(); } // WebSocketServer ws = new
		 * WebSocketServer(unoJta); // ws.run(); } }).start();
		 */
	}

	private boolean setServerConfig(MqttConfigEntity en) {
		boolean isConfig = true;
		if (StringUtil.isEmpty(en.getHost()) || "null".equals(en.getHost())) {
			isConfig = false;
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到服务器地址和端口号");
		} else {
			Server2.HOST = en.getHost();
			CommUtil.doPrint(unoJta, "MQTT:", "服务器地址和端口号:" + Server2.HOST);
		}
		if (StringUtil.isEmpty(en.getSubscribeTopic()) || "null".equals(en.getSubscribeTopic())) {
			isConfig = false;
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到订阅主题");
		} else {
			Server2.SUBSCRIBETOPIC = en.getSubscribeTopic();
			CommUtil.doPrint(unoJta, "MQTT:", "订阅主题:" + Server2.SUBSCRIBETOPIC);
		}
		if (StringUtil.isEmpty(en.getSubscribeTopic2()) || "null".equals(en.getSubscribeTopic2())) {
//			isConfig = false;
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到订阅主题2");
		} else {
			Server2.SUBSCRIBETOPIC2 = en.getSubscribeTopic2();
			CommUtil.doPrint(unoJta, "MQTT:", "订阅主题:" + Server2.SUBSCRIBETOPIC2);
		}
		if (StringUtil.isEmpty(en.getSubscribeTopic3()) || "null".equals(en.getSubscribeTopic3())) {
//			isConfig = false;
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到订阅主题3");
		} else {
			Server2.SUBSCRIBETOPIC3 = en.getSubscribeTopic3();
			CommUtil.doPrint(unoJta, "MQTT:", "订阅主题:" + Server2.SUBSCRIBETOPIC3);
		}
		
		if (StringUtil.isEmpty(en.getType()) || "null".equals(en.getType())) {
			isConfig = false;
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到协议配置");
		} else {
			if(en.getType() == 0) {
				CommUtil.doPrint(unoJta, "MQTT:", "当前协议:磅秤"+en.getType() );	
			} else {
				CommUtil.doPrint(unoJta, "MQTT:", "当前协议:垃圾桶"+en.getType() );
			}
		}
		
		if (StringUtil.isEmpty(en.getClientid()) || "null".equals(en.getClientid())) {
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到clientid,本次连接不使用clientid");
		} else {
			Server2.clientid = en.getClientid();
			CommUtil.doPrint(unoJta, "MQTT:", "clientid:" + Server2.clientid);
		}
		if (StringUtil.isEmpty(en.getConnectionTimeout()) || "null".equals(en.getConnectionTimeout())) {
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到连接超时设置,采用默认设置10秒");
		} else {
			Server2.connectTimeOut = en.getConnectionTimeout();
			CommUtil.doPrint(unoJta, "MQTT:", "连接超时设置:" + Server2.connectTimeOut);
		}
		if (StringUtil.isEmpty(en.getKeepAliveInterval()) || "null".equals(en.getKeepAliveInterval())) {
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到会话心跳时间设置,采用默认设置20秒");
		} else {
			Server2.keepAlive = en.getKeepAliveInterval();
			CommUtil.doPrint(unoJta, "MQTT:", "会话心跳时间设置：" + Server2.keepAlive);
		}
		if (StringUtil.isEmpty(en.getPublicTopic()) || "null".equals(en.getPublicTopic())) {
//			CommUtil.doPrint(unoJta, "MQTT:", "未获取到发布主题设置,本次启动不发布主题");
		}
		if (StringUtil.isEmpty(en.getUsername()) || "null".equals(en.getUsername())) {
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到连接用户名,本次启动不使用用户名连接");
		} else {
			Server2.userName = en.getUsername();
			CommUtil.doPrint(unoJta, "MQTT:", "连接用户名：" + Server2.userName);
		}
		if (StringUtil.isEmpty(en.getPassword()) || "null".equals(en.getPassword())) {
			CommUtil.doPrint(unoJta, "MQTT:", "未获取到连接密码,本次启动不使用密码连接");
		} else {
			Server2.passWord = en.getPassword();
			CommUtil.doPrint(unoJta, "MQTT:", "连接密码：" + Server2.passWord);
		}

		return isConfig;
	}

	/**
	 * 修改连接状态
	 * 
	 * @param args
	 */
	public static void changeConnectState(int connectState) {
		MqttConfigDao config = new MqttConfigDaoImpl();
		MqttConfigEntity en = new MqttConfigEntity();
		en.setIsConnect(connectState);
		config.updateConnectState(en);
	}

	public static void main(String[] args) {
		launch(XmtApplication.class, args);
	}

	// 定时获取天气预报
	private void getWeather() {
		long PERIOD_DAY = 24 * 60 * 60 * 1000;
		CityWeatherDao cw = new CityWeatherDaoImpl();
		final List<String> city = cw.getCityWeather();
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 1); // 凌晨1点
		calendar.set(Calendar.MINUTE, 30);
		calendar.set(Calendar.SECOND, 0);
		Date date = calendar.getTime(); // 第一次执行定时任务的时间
		// 如果第一次执行定时任务的时间 小于当前的时间
		// 此时要在 第一次执行定时任务的时间加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
		if (date.before(new Date())) {
			date = this.addDay(date, 1);
		}
		TimerTask task = new TimerTask() {
			public void run() {
				HttpClient.doUpdateWeather(city);
			}
		};
		Timer timer = new Timer();
		// 安排指定的任务在指定的时间开始进行重复的固定延迟执行。
		timer.schedule(task, date, PERIOD_DAY);
	}

	// 增加或减少天数
	public Date addDay(Date date, int num) {
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		startDT.add(Calendar.DAY_OF_MONTH, num);
		return startDT.getTime();
	}

	/**
	 * 开启服务 netty
	 */
	private void doStartService() {
		new Thread(new Runnable() {
			public void run() {
				isClose = 0;
				// FrLoggerUtil.info("监听启动：", "启动");
				EventLoopGroup bossGroup = new NioEventLoopGroup();
				EventLoopGroup workerGroup = new NioEventLoopGroup();
				try {
					ServerBootstrap b = new ServerBootstrap();
					b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
							.childHandler(new ChannelInitializer<SocketChannel>() {
								@Override
								public void initChannel(final SocketChannel ch) throws Exception {
									ChannelPipeline pipeline = ch.pipeline();
									pipeline.addLast(new OutboundHandler(msgJta));
									pipeline.addLast(new InboundHandler(msgJta));
								}
							}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true)
							.childOption(ChannelOption.TCP_NODELAY, true);
					f = b.bind(Integer.parseInt("7000")).sync();

					msgJta.append(StringUtil.connectString("成功启动端口：", "7000", StringUtil.LINE_SPEAR_LF));
					f.channel().closeFuture().sync();

				} catch (Exception ex) {
					if (isClose != 1) {
						msgJta.append(StringUtil.connectString("端口异常：", ex.getMessage(), StringUtil.LINE_SPEAR_LF));
					}
				} finally {
					workerGroup.shutdownGracefully();
					bossGroup.shutdownGracefully();
					// FrLoggerUtil.closeLogger();
				}
			}
		}).start();
	}
}
