package com.huimv.lamp.server;

import com.huimv.lamp.service.DataService;
import com.huimv.lamp.service.LampService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@ChannelHandler.Sharable
@Component
@Slf4j
public class EartagServerHandler2 extends ChannelInboundHandlerAdapter {
    @Value("${data.input.flow}")
    private Integer dataInputFlow;
    @Value("${data.test.input}")
    private Integer dataTestInput;
    private StringBuilder askTextSb = null;
    private int num = 0;
    @Autowired
    private DataService dataService;
    @Autowired
    private LampService lampService;

    //
    public void appendClientAsk(String text){
        if(this.askTextSb == null){
            askTextSb = new StringBuilder();
        }
        askTextSb.append(text);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf data = (ByteBuf) msg;
        String clientAskText = data.toString(CharsetUtil.UTF_8);
//        System.out.println("客户端消息clientAskText>>"+clientAskText);
        //保存实例内的客户端请求
//        appendClientAsk(clientAskText);
        handleClientMessage(clientAskText,ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        if(askTextSb.toString().indexOf("end") != -1){
//            // 处理客户端消息
//            handleClientMessage(askTextSb.toString(),ctx);
//            //清空重置;
//            askTextSb.delete(0,askTextSb.length());
//            num = 0;
//        }
    }

    private void handleClientMessage(String askText, ChannelHandlerContext ctx) throws ParseException {
        String[] dataArray = askText.split("\\+");
        String cmdHeader = dataArray[0];
        //芯片id/设备编码
        String idCode = dataArray[1];
        String cmd = dataArray[2];
        Map map = new HashMap();
        map.put("askText", askText);
        if (cmdHeader.trim().equalsIgnoreCase("hm")) {
            //采集器应答数据
            if (cmd.trim().equalsIgnoreCase("0")) {
                //不需要处理
                System.out.println("==>命令0");
            } else if (cmd.trim().equalsIgnoreCase("1")) {
                System.out.println("==>命令1请求 askText>>" + askText.trim());
                //处理获取设备编码命令
                //{读取设备编码}
                String deviceCode = dataService.getDeviceCodeByChipId(idCode);
                log.info("获取设备编码结果,芯片id>>" + idCode + " ,deviceCode>>" + deviceCode);
                if (deviceCode != null) {
                    String answer = "hm+1+0+" + deviceCode + "+123+8+end";
                    log.info(">>命令1设备编码-应答数据>>" + answer);
                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
                } else {
                    log.error("检测到未注册的采集器设备,已舍弃请求.");
                }
            } else if (cmd.trim().equalsIgnoreCase("2")) {
                    //处理服务器时间命令
                    String answer = "hm+2+" + dataService.getNowText() + "+4+end";
                    log.info(">>命令2服务器时间-应答数据>>" + answer);
                    ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));

            } else if (cmd.trim().equalsIgnoreCase("3")) {
                System.out.println("==>命令3请求 askText>>" + askText);
                //处理心跳包命令
                //{设备心跳应答}
                String answer = "hm+3+6+end";
                log.info(">>命令3心跳包-应答数据>>" + answer);
                ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
            } else if (cmd.trim().equalsIgnoreCase("4")) {
                System.out.println("==>命令4请求 askText>>" + askText);
                //处理设备环境温度命令
                //{设备环境温度应答}
                String answer = "hm+4+7+end";
                log.info(">>命令4环境温度-应答数据>>" + answer);
                ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
            } else if (cmd.trim().equalsIgnoreCase("7")) {
                System.out.println("==>命令7请求 askText>>" + askText);
                //处理设备环境温度命令
//                Integer lighteness = dataService.getLighteness(askText);
//                int lighteness = lampService.getLighteness(askText);
                //灯光亮度应答
//                Integer lighteness = 50;
                Integer lighteness = lampService.getLight();
                System.out.println("lighteness>>"+lighteness);
                String answer = "hm+7+"+lighteness+"+0+end";
                log.info(">>命令7亮度-应答数据>>" + answer);
                ctx.writeAndFlush(Unpooled.copiedBuffer(answer.getBytes()));
            } else {
                System.out.println("==>未知命令");
                log.error(">>当前数据为非法数据>>" + askText);
            }
        } else {
            System.out.println("==>未知命令");
            log.error("##当前请求数据为非法数据>>" + askText);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if(cause.getMessage().indexOf("Connection reset") != -1){
            log.info("相关采集器设备正在重启:"+cause.toString());
        }
        ctx.close();
    }

    //检查无效耳标
    public boolean checkValidEarmark(String earmark) {
        if (earmark.trim().equalsIgnoreCase("ffffffffffffffff") || earmark.trim().equalsIgnoreCase("0000000000000000")) {
            return true;
        } else {
            return false;
        }
    }



}
