package com.fr.tx.common.netty.eqt;

import javax.swing.JTextArea;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fr.tx.common.consts.FrameConsts;
import com.fr.tx.common.dao.MysqlDao;
import com.fr.tx.common.dao.MysqlDaoImpl;
import com.fr.tx.common.data.CacheData;
import com.fr.tx.common.netty.cpu3.DataSave;
import com.fr.tx.common.util.CommUtil;
import com.fr.tx.common.util.ConvertUtil;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class TcpServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    /**
     * 日志
     */
    public static final Logger logger = Logger.getLogger(TcpServerHandler.class.getSimpleName());
    /**
     * 打印信息
     */
    private JTextArea flashuser;
    
    // 创建MYSQL用DAO
    MysqlDao dao = new MysqlDaoImpl();

    /**
     * 构造函数
     * @param StationDataEntity
     */
    public TcpServerHandler(JTextArea flashuser) {
        this.flashuser = flashuser;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        ByteBuf buf = msg.readBytes(msg.readableBytes());
        String data = ByteBufUtil.hexDump(buf);
        logger.info(ctx.channel().remoteAddress().toString()+"收到客户端发送的消息："+data);
        //16进制转string
        data = ConvertUtil.hexString2String(data);
        CommUtil.doPrint(flashuser, "", ctx.channel().remoteAddress().toString()+"收到客户端发送的消息："+data);
    	DataSave ds = new DataSave();
    	try {
//    		JSONArray jsonArr = JSONArray.parseArray(data);
//    		for(int i=0;i<jsonArr.size();i++){
    			JSONObject json = JSONObject.parseObject(data);
    			System.out.println(json);
    			//判断data是否以68开始,68开始为采集器数据
        		if("68".equals(json.getString("St"))){
        			//entity为GunEntity时    油枪配置信息
        			if("GunEntity".equals(json.getString("Entity"))){
        				//成功返回1
        				int p = ds.doSaveGun(json);
        				ctx.channel().writeAndFlush(p);     
        			}
        			//entity为GunLogEntity时    加油信息
        			if("GunLogEntity".equals(json.getString("Entity"))){
        				int p = ds.doSaveGunLog(json);
        				ctx.channel().writeAndFlush(p);
        			}
        			//entity为GunSts时    加油状态
        			if("GunSts".equals(json.getString("Entity"))){
        				ds.AnslytRealData(json);
        			}
        		}
        		//否则为设备数据
        		else if("69".equals(json.getString("St"))){
        			//entity为NdEntity时    浓度数据
        			if("NdEntity".equals(json.getString("Entity"))){
        				ds.saveNd(json);
        			}
        			//entity为WdEntity时    温度数据
        			if("WdEntity".equals(json.getString("Entity"))){
        				ds.saveWd(json);
        			}
        			//entity为YgEntity时    油罐数据
        			if("YgEntity".equals(json.getString("Entity"))){
        				ds.saveYg(json);
        			}
        			//entity为NdEntity时    油机数据
        			if("YjEntity".equals(json.getString("Entity"))){
        				ds.saveYj(json);
        			}
        		}
//    		}
			//CacheData.sessionWebMap.get(sessionBeats).writeAndFlush(new TextWebSocketFrame(data));
		} catch(Exception e) {
			
		}
    }
    //ctx.channel().writeAndFlush("1234567890");        
        
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 删除通道
        Global.channelGroup.remove(ctx.channel());
        CacheData.sessionBeats.remove(ctx.channel().remoteAddress().toString());
        // 关闭链接
        ctx.channel().close();
        // 通道需要注册
        CommUtil.doPrint(flashuser, "",ctx.channel().remoteAddress().toString()+ "客户端下线啦");
        CommUtil.doPrint(flashuser, "","当前客户端数量"+ Global.channelGroup.size());
        
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 添加通道
        Global.channelGroup.add(ctx.channel());
        // IP端口注册一个空的
        CacheData.sessionBeats.put(ctx.channel().remoteAddress().toString(), "");
        // 通道需要注册
        CommUtil.doPrint(flashuser, "",ctx.channel().remoteAddress().toString()+ "客户端上线啦");
        CommUtil.doPrint(flashuser, "","当前客户端数量"+ Global.channelGroup.size());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 删除通道
        Global.channelGroup.remove(ctx.channel());
        CacheData.sessionBeats.remove(ctx.channel().remoteAddress().toString());
        // 通道需要注册
        CommUtil.doPrint(flashuser, "",ctx.channel().remoteAddress().toString()+ "客户端下线啦");
        CommUtil.doPrint(flashuser, "","当前客户端数量"+ Global.channelGroup.size());
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("已经"+FrameConsts.READ_TIME_OUT_LONG+"秒未收到客户端的消息了！");
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
                CommUtil.doPrint(flashuser, "",ctx.channel().remoteAddress().toString()+ "关闭这个不活跃的客户端");
                CacheData.sessionBeats.remove(ctx.channel().remoteAddress().toString());
                ctx.channel().close();
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }
}