package com.huimv.env.input.server;

import com.alibaba.fastjson.JSONArray;
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.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
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
@Log4j2
public class EnvInputServerHandler extends ChannelInboundHandlerAdapter {
    private StringBuilder askTextSb = null;

    //
    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);
        //保存实例内的客户端请求
        appendClientAsk(clientAskText);
        //临时写入耳标数据到文件
//        writeTxt(clientAskText,"all");
    }

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

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

    /**
     * @Method : handleClientAskCmd
     * @Description : 处理请求小心
     * @Params : [clientAskText, ctx]
     * @Return : void
     * @Author : ZhuoNing
     * @Date : 2022/3/28
     * @Time : 17:36
     */
    private void handleClientAskCmd(String clientAskText, ChannelHandlerContext ctx) throws ParseException, IOException {
        clientAskText = clientAskText.replaceAll("\r", "").replaceAll("\n", "");
        //{处理非正常命令}
//        int countPlus = regexUtil.countPlus(clientAskText);
//        if (countPlus < 4) {
//            System.out.println("当前数据为不完整数据，故丢弃.>>" + clientAskText);
//        } else {
        //--处理客户端请求数据
        //{拆分粘包数据}
        JSONArray askJa = parseAskCmdPackage(clientAskText);
        for (int a = 0; a < askJa.size(); a++) {
            String askText = askJa.getString(a);
            //{处理请求命令}
            askCmdActuator(askText, ctx);
        }
//        }
    }

    /**
     * @Method : askCmdActuator
     * @Description :
     * @Params : [askText, ctx]
     * @Return : void
     * @Author : ZhuoNing
     * @Date : 2022/3/23
     * @Time : 18:08
     */
    private void askCmdActuator(String askText, ChannelHandlerContext ctx) throws ParseException, IOException {
        System.out.println("======>接收设备请求:" + askText);
        String[] dataArray = askText.split("\\+");

        String cmdHeader = dataArray[0];
        if (!cmdHeader.trim().equalsIgnoreCase("hm")) {
            log.info("当前命令是非hm命令[" + askText + "]");
            return;
        }
        //芯片id/设备编码

        String cmd = dataArray[1];
//        Map map = new HashMap();
//        map.put("askText", askText);
//        rawDataService.insert(idCode,askText);
        switch (cmd) {
            case "1":
                //上传温度
                getTemp(dataArray,ctx);
                break;
            case "2":
                //上传充电状态
                getChargingStatus(dataArray,ctx);
            case "3":
                //上传漏电状态
                getLeakageStatus(dataArray,ctx);
            case "4":
                //心跳
                getHear(dataArray,ctx);
        }
    }

    private void getHear(String[] dataArray, ChannelHandlerContext ctx) {
        String ans = "hm+4+1+end";
        answerCmd(ans,ctx);
    }

    private void getLeakageStatus(String[] dataArray, ChannelHandlerContext ctx) {
        String ans = "hm+3+1+end";
        answerCmd(ans,ctx);
    }

    private void getChargingStatus(String[] dataArray, ChannelHandlerContext ctx) {
        String ans = "hm+2+1+end";
        answerCmd(ans,ctx);
    }

    private void getTemp(String[] dataArray, ChannelHandlerContext ctx) {
        String ans = "hm+1+1+end";
        answerCmd(ans,ctx);
    }


    //应答
    public void answerCmd(String answerText, ChannelHandlerContext ctx) {
        log.info(String.format("应答数据--->%s",answerText));
        ctx.writeAndFlush(Unpooled.copiedBuffer(answerText.getBytes()));
    }

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

    //拆分粘包数据
    public JSONArray parseAskCmdPackage(String text) {
        String key = "end";
        Pattern pattern = Pattern.compile(key);
        Matcher matcher = pattern.matcher(text);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        JSONArray dataJa = new JSONArray();
        if (count == 1) {
            dataJa.add(text);
        } else {
            for (int a = 0; a < count; a++) {
                int p1 = text.indexOf("end");
                dataJa.add(text.substring(0, p1 + 3));
                text = text.substring(p1 + 3, text.length());
            }
        }
        return dataJa;
    }
}
