package com.huimv.admin.server;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.admin.entity.ProtData;
import com.huimv.admin.entity.ProtThreshold;
import com.huimv.admin.entity.ProtWarningInfo;
import com.huimv.admin.mapper.ProtDataMapper;
import com.huimv.admin.service.IProtThresholdService;
import com.huimv.admin.service.IProtWarningInfoService;
import io.netty.buffer.ByteBuf;
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.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
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 EnvInputServerHandler extends ChannelInboundHandlerAdapter {
    private StringBuilder askTextSb = null;
    @Autowired
    private ProtDataMapper protDataMapper;

    //
    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 {
        try {
            System.out.println("接收到消息: " + clientAskText + "  时间: " + System.currentTimeMillis());
            EnvironmentalData parse = HJ212Parser.parse(clientAskText.replace("##", ""));
            ProtData protData = new ProtData();
            if (ObjectUtil.isEmpty(parse.getCpData().getParameters().get("w01001").getAvg() )){
                askTextSb.delete(0, askTextSb.length());
                return;
            }
            protData.setPh(parse.getCpData().getParameters().get("w01001").getAvg());
//        protData.setOther1(parse.getCpData().getParameters().get("w01010").getAvg());
            protData.setCod(parse.getCpData().getParameters().get("w01018").getAvg());
            protData.setNh3n(parse.getCpData().getParameters().get("w21003").getAvg());
            protData.setOther2(parse.getCpData().getParameters().get("w00000").getAvg());
            protData.setLoctionType(1);

            String mn = parse.getHeader().getMn();
            if ("01523162079470".equals(mn)){
                protData.setFarmId(30);
                saveWarning(protData,30,3);
            }else {
                protData.setFarmId(28);
                saveWarning(protData,28,3);
            }
            protData.setOther3(clientAskText);
            protData.setCreateDate(new Date());
            protDataMapper.insert(protData);


        }catch (Exception e){
            System.out.println(e);
            askTextSb.delete(0, askTextSb.length());

        }


    }
    @Autowired
    private IProtThresholdService protThresholdService;
    @Autowired
    private IProtWarningInfoService warningInfoService;

    private void saveWarning(ProtData protData,Integer farmId,Integer protType) {
        ProtThreshold one = protThresholdService.getOne(new QueryWrapper<ProtThreshold>().eq("farm_id", farmId).eq("prot_type", protType));
        ProtWarningInfo protWarningInfo = new ProtWarningInfo();
        protWarningInfo.setDate(new Date());
        protWarningInfo.setFarmId(farmId);
        boolean ble = false;
        if (comperStringAndString(protData.getCod(),one.getCod2())){
            protWarningInfo.setWarningType(0);
            protWarningInfo.setWarningContent("cod浓度为 "+protData.getCod()+",超过阈值"+one.getCod2()+"红色预警");
        } else if (comperStringAndString(protData.getCod(),one.getCod1())  ) {
            protWarningInfo.setWarningType(0);
            protWarningInfo.setWarningContent("cod浓度为 "+protData.getCod()+",超过阈值"+one.getCod2()+"黄色预警");
            ble = true;
        }

        if (comperStringAndString(protData.getFlow(),one.getFlow2())){
            protWarningInfo.setWarningType(5);
            protWarningInfo.setWarningContent("流量为 "+protData.getFlow()+",超过阈值"+one.getFlow2()+"红色预警");
            ble = true;
        } else if (comperStringAndString(protData.getFlow(),one.getFlow1())  ) {

            protWarningInfo.setWarningType(5);
            protWarningInfo.setWarningContent("流量为 "+protData.getFlow()+",超过阈值"+one.getFlow1()+"黄色预警");
            ble = true;
        }

        if (comperStringAndString(protData.getNh3n(),one.getNh3n2())){
            protWarningInfo.setWarningType(2);
            protWarningInfo.setWarningContent("氨氮为 "+protData.getNh3n()+",超过阈值"+one.getNh3n2()+"红色预警");
            ble = true;
        } else if (comperStringAndString(protData.getNh3n(),one.getNh3n1())  ) {
            protWarningInfo.setWarningType(2);
            protWarningInfo.setWarningContent("氨氮为 "+protData.getNh3n()+",超过阈值"+one.getNh3n1()+"黄色预警");
            ble = true;
        }
        if (comperStringAndString(protData.getPh(),"8.8")){
            protWarningInfo.setWarningType(1);
            protWarningInfo.setWarningContent("ph为 "+protData.getPh()+",超过阈值8.8红色预警");
            ble = true;
        }else if (comperStringAndString("6.2",protData.getPh())  ) {
            protWarningInfo.setWarningType(1);
            protWarningInfo.setWarningContent("ph为 "+protData.getPh()+",低于阈值6.2红色色预警");
            ble = true;
        } else if (!(comperStringAndString(protData.getPh(),one.getOther2()) &&  comperStringAndString(one.getPh1() ,protData.getPh()) )) {
            protWarningInfo.setWarningType(1);
            protWarningInfo.setWarningContent("ph为 "+protData.getPh()+"黄色预警");
            ble = true;
        }
        if (ble){
            warningInfoService.save(protWarningInfo);
        }

    }
    private boolean comperStringAndString(String value ,String th){
        if (StringUtils.isBlank(value) || StringUtils.isBlank(th)){
            return false;
        }
        return Double.parseDouble(value) > Double.parseDouble(th);

    }
    //QN	20250412142007184	请求编号（21位时间戳：2025-04-12 14:20:07.184）
    //ST	32	系统类型（32表示污水处理设施）
    //CN	2051	命令编号（2051表示实时数据上报）
    //PW	123456	密码（默认密码）
    //MN	01523162079470	设备唯一标识（015为厂商代码，后续为设备编号）
    //Flag	4	数据包标志位（4表示数据需要应答）
    //w01001	pH值	-	水质酸碱度指标
    //w01010	水温	℃	水体温度
    //w01018	溶解氧	mg/L	水体中氧气含量
    //w21003	总磷	mg/L	水体富营养化指标
    //w00000	自定义/扩展参数	-	需结合具体设备文档确认含义
    //Min：周期内最小值
    //Max：周期内最大值
    //Avg：周期内平均值
    //Cou：累计值（如流量累计）

//    public static void main(String[] args) {
//        String rawData = "##QN=20250412142007184;ST=32;CN=2051;PW=123456;MN=01523162079470;Flag=4;" +
//                "CP=&&DataTime=20250412141900;w01018-Min=78.9,w01018-Max=78.9,w01018-Avg=78.9," +
//                "w01018-Cou=0.026,w01018-Flag=N;w00000-Min=5.497,w00000-Max=5.728,w00000-Avg=5.597," +
//                "w00000-Cou=0.336,w00000-Flag=N;w01001-Min=7.33,w01001-Max=7.34,w01001-Avg=7.336," +
//                "w01001-Flag=N;w01010-Min=23,w01010-Max=23,w01010-Avg=23,w01010-Flag=N;" +
//                "w21003-Min=0.455,w21003-Max=0.455,w21003-Avg=0.455,w21003-Cou=0,w21003-Flag=N&&7200";
//
//        EnvironmentalData data = HJ212Parser.parse(rawData.replace("##",""));
//        System.out.println("DataTime: " + data.getCpData().getDataTime());
//        System.out.println("pH值: " + data.getCpData().getParameters().get("w01001").getAvg());
//    }

    /**
     * @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 idCode = dataArray[1];
        String cmd = dataArray[2];
        Map map = new HashMap();
        map.put("askText", askText);
//        rawDataService.insert(idCode,askText);
        switch (cmd) {
//            case "1":
//                //获取远程设备编码
//                getDeviceCode(askText, idCode, ctx);
//                break;
//            case "2":
//                //同步时间
//                getServerTime(askText, idCode, ctx);
//                break;
//            case "3":
//                //日龄上传
//                uploadDayAge(askText, idCode, ctx);
//                break;
//            case "4":
//                //通风等级
//                uploadFeng(askText, idCode, ctx);
//                break;
//            case "5":
//                //室外温度
//                uploadOutTemp(askText, idCode, ctx);
//                break;
//            case "6":
//                //室内温度 平均温度
//                uploadInTemp(askText, idCode, ctx);
//                break;
//            case "7":
//                //目标温度
//                uploadTargetnTemp(askText, idCode, ctx);
//                break;
//            case "8":
//                //水暖温度
//                uploadShuiNuanTemp(askText, idCode, ctx);
//                break;
//            case "9":
//                //水暖温度
//                uploadWeiZhiTemp(askText, idCode, ctx);
//                break;
//            case "21":
//                //温度
//                uploadTemp(askText, idCode, ctx);
//                break;
//            case "22":
//                //湿度
//                uploadHumi(askText, idCode, ctx);
//                break;
//            case "23":
//                //co2
//                uploadCo2(dataArray,askText, idCode, ctx);
//                break;
//            case "24":
//                //压力
//                uploadYaLi(dataArray,askText, idCode, ctx);
//                break;
//            case "31":
//                //水表
//                uploadShuiBiao(dataArray,askText, idCode, ctx);
//                break;
//            case "32":
//                //电表
//                uploadDianBiao(dataArray,askText, idCode, ctx);
//                break;
//            case "41":
//                //报警
//                uploadWarning(askText, idCode, ctx);
//                break;
//            case "42":
//                //报警
//                uploadStatusWaraning(askText, idCode, ctx);
//                break;
//            case "61":
//                //风机状态
//                uploadFengStatus(askText, idCode, ctx);
//                break;
//            case "62":
//                //湿帘状态
//                uploadShiLianStatus(askText, idCode, ctx);
//                break;
//            case "63":
//                //喷雾状态
//                uploadPengWuStatus(askText, idCode, ctx);
//                break;
//            case "64":
//                //加热器状态
//                uploadJiaReQiStatus(askText, idCode, ctx);
//                break;
//            case "65":
//                //小窗状态
//                uploadXiaoChuangStatus(askText, idCode, ctx);
//                break;
//            case "66":
//                //导流板状态
//                uploadDaoLiuBanStatus(askText, idCode, ctx);
//                break;
//            case "67":
//                //照明状态
//                uploadZhaoMingStatus(askText, idCode, ctx);
//                break;
//            case "81":
//                //日龄配置
//                uploadDayAgePeizhiuStatus(askText, idCode, ctx);
//                break;
//            case "82":
//                //通风级别配置
//                uploadTongFengPeizhiuStatus(askText, idCode, ctx);
//                break;
//            case "91":
//                //通获取日龄配置
//                uploadGainDayAgePeizhiuStatus(dataArray,askText, idCode, ctx);
//                break;
//            case "92":
//                //通风级别配置
//                uploadGainTongFengPeizhiuStatus(dataArray,askText, idCode, ctx);
//                break;
//            default:
//                System.out.println("==>未知命令");
//                log.error(">>当前数据为非法数据-未知命令>>" + askText);
        }
    }
//
//    private void uploadZhaoMingStatus(String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("#照明状态上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+67+0+4+end";
//        log.info(">>照明状态上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        producer.sendZhaoMingStatus(askText);
//    }
//
//    private void uploadDaoLiuBanStatus(String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("#导流板状态上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+66+0+4+end";
//        log.info(">>导流板状态上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        producer.sendDaoLiuStatus(askText);
//    }
//
//    private void uploadXiaoChuangStatus(String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("#小窗状态上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+65+0+4+end";
//        log.info(">>小窗状态上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendXiaoChuangStatus(askText);
//    }
//
//    private void uploadJiaReQiStatus(String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("#加热状态上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+64+0+4+end";
//        log.info(">>加热温度上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendJiaReStatus(askText);
//    }
//
//    private void uploadDianBiao(String[] dataArray, String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("#电表上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+32+0+4+end";
//        log.info(">>电表上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendDianBiaoData(askText);
//    }
//
//    private void uploadShuiBiao(String[] dataArray, String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("#水表上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+31+0+4+end";
//        log.info(">>水表温度上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendShuiBiaoData(askText);
//    }
//    private void uploadWeiZhiTemp(String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("##位置温度上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+9+0+4+end";
//        log.info(">>位置温度上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendWeiZhi(askText);
//    }
//
//    private void uploadShuiNuanTemp(String askText, String idCode, ChannelHandlerContext ctx) {
//
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("##水暖上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+8+0+4+end";
//        log.info(">>水暖上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendShuiNuan(askText);
//    }
//
//    private void uploadStatusWaraning(String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("##状态报警上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+42+0+2+end";
//        log.info(">>状态报警上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendWarning(askText);
//    }
//
//    private void uploadYaLi(String[] dataArray, String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("##压力 上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        String answerText = "hm+24+0+8+end";
//        log.info(">>压力  等级上传请求-应答数据>>" + answerText);
//        answerCmd(answerText, ctx);
//        //发送湿度请求到消息队列
//        producer.sendYaLi(askText);
//    }
//
//    private void uploadCo2(String[] dataArray, String askText, String idCode, ChannelHandlerContext ctx) {
//        if (!cmdProService.isEffectiveDevice(idCode)) {
//            System.out.println("##CO2 上传请求-未注册设备 idCode=" + idCode);
//            return;
//        }
//        //TODO
//        String answerText = "hm+23+0+8+end";

//    //拆分粘包数据
    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;
    }
}
