package com.lutao.cloud.consume.factory;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.JsonNode;
import com.lutao.cloud.collect.vo.DataAddVO;
import com.lutao.cloud.common.core.kafka.MessageCommandEnum;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.consume.service.PerceptionDynamicService;
import com.lutao.cloud.consume.service.PerceptionMonitorHazardousGasInfoService;
import com.lutao.cloud.consume.util.TimeUtil;
import com.lutao.entity.PerceptionDynamic;
import com.lutao.entity.PerceptionMonitorHazardousGasInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 感知监测信息
 *
 * @author yx
 * @date 2023/07/21
 */
@Component
@Slf4j
public class PerceptionMonitorHazardousGasInfoStrategy implements CommandStrategy<PerceptionMonitorHazardousGasInfo> {

//    @Resource
//    private LindormTSDBClient lindormTSDBClient;


    @Resource
    private PerceptionMonitorHazardousGasInfoService perceptionMonitorHazardousGasInfoService;

    private static PerceptionMonitorHazardousGasInfoStrategy perceptionMonitorHazardousGasInfoStrategy;

    @Resource
    private PerceptionDynamicService perceptionDynamicService;

    @Resource(name = "redisTemplateAlias")
    private RedisTemplate redisTemplate;


    @PostConstruct
    public void init() {
        perceptionMonitorHazardousGasInfoStrategy = this;
        perceptionMonitorHazardousGasInfoStrategy.perceptionMonitorHazardousGasInfoService = this.perceptionMonitorHazardousGasInfoService;
        perceptionMonitorHazardousGasInfoStrategy.perceptionDynamicService = this.perceptionDynamicService;
        perceptionMonitorHazardousGasInfoStrategy.redisTemplate = this.redisTemplate;
    }

    @Override
    public MessageInfo execute(String command, JsonNode data, DataAddVO dataAddVO) {
        if (MessageCommandEnum.MESSAGE_ADD.getCommand().equals(command)) {
            PerceptionMonitorHazardousGasInfo perceptionMonitorHazardousGasInfo = JSONUtil.toBean(data.toString(), PerceptionMonitorHazardousGasInfo.class);
            perceptionMonitorHazardousGasInfo.setAppId(dataAddVO.getAppId());
            log.info("PerceptionMonitorHazardousGasInfoStrategy 进行add操作 ......");

            String tagCode = perceptionMonitorHazardousGasInfo.getTagCode();

            PerceptionDynamic perceptionDynamic = new PerceptionDynamic();
            perceptionDynamic.setTagCode(tagCode);
            perceptionDynamic.setAppId(perceptionMonitorHazardousGasInfo.getAppId());
            perceptionDynamic.setRtValue(perceptionMonitorHazardousGasInfo.getRtValue());
            perceptionDynamic.setCollectTime(perceptionMonitorHazardousGasInfo.getCollectTime());
            perceptionDynamic.setCreateTime(perceptionMonitorHazardousGasInfo.getCreateTime());
            perceptionDynamic.setUpdateTime(perceptionMonitorHazardousGasInfo.getUpdateTime());
            perceptionMonitorHazardousGasInfoStrategy.perceptionDynamicService.saveOrUpdate(perceptionDynamic, Wrappers.lambdaQuery(PerceptionDynamic.class)
                    .eq(PerceptionDynamic::getAppId, perceptionDynamic.getAppId())
                    .eq(PerceptionDynamic::getTagCode, perceptionDynamic.getTagCode()));

            perceptionMonitorHazardousGasInfoStrategy.perceptionMonitorHazardousGasInfoService.save(perceptionMonitorHazardousGasInfo);

            //表名-appid-平台-code
            BoundHashOperations perceptionMonitorHazardousGasInfoCache = perceptionMonitorHazardousGasInfoStrategy.redisTemplate.boundHashOps(LocalDate.now() + ":" + dataAddVO.getResource() + ":"
                    + perceptionMonitorHazardousGasInfo.getAppId() + ":" + perceptionMonitorHazardousGasInfo.getPlatformCode() + ":" + perceptionMonitorHazardousGasInfo.getTagCode());
            Integer enable = (Integer) perceptionMonitorHazardousGasInfoCache.get("enable");
            log.info("----------------是否启用------------:" + enable);
            if (enable != null && enable == 0) {
                try {
                    log.info(perceptionMonitorHazardousGasInfo.getTagCode() + "启用-------------------");
                    // 获取当前时间字符串
                    String currentTimeStr = perceptionMonitorHazardousGasInfo.getCollectTime().toString();
                    // 检查是否需要更新
                    String lastReceivedTime = (String) perceptionMonitorHazardousGasInfoCache.get("received_time");
                    Double currentValue = (Double) perceptionMonitorHazardousGasInfoCache.get("value");
                    Double newRtValue = perceptionMonitorHazardousGasInfo.getRtValue();
                    boolean b = !currentTimeStr.equals(lastReceivedTime)  || !(newRtValue.equals(currentValue));
                    log.info("-----------检查是否需要更新-------------" + b);
                    if (b) {
                        log.info("-----------更新缓存条目-------------");
                        perceptionMonitorHazardousGasInfoCache.increment("received_count", 1);
                        // 计算每分钟应该接受的数据量
                        LocalDateTime beginTime = LocalDateTime.parse(perceptionMonitorHazardousGasInfoCache.get("begin_time").toString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                        Long shouldAcceptCount = TimeUtil.getTimeDifference(beginTime, LocalDateTime.now());
                        perceptionMonitorHazardousGasInfoCache.put("should_accept_count", shouldAcceptCount);
                        // 获取已接收计数
                        Integer receivedCount = (Integer) perceptionMonitorHazardousGasInfoCache.get("received_count");
                        log.info("receivedCount:" + receivedCount);
                        if (shouldAcceptCount > 0) {
                            perceptionMonitorHazardousGasInfoCache.put("online_rate", (float) receivedCount / shouldAcceptCount);
                        }
                        perceptionMonitorHazardousGasInfoCache.put("entity", JSONUtil.toJsonStr(perceptionMonitorHazardousGasInfo));
                        perceptionMonitorHazardousGasInfoCache.put("received_time", currentTimeStr);
                        perceptionMonitorHazardousGasInfoCache.put("value", newRtValue);
                        perceptionMonitorHazardousGasInfoCache.put("resource", dataAddVO.getResource());
                    }
                } catch (Exception e) {
                    log.error("更新感知监控有毒气体信息缓存异常", e);
                    e.printStackTrace();
                }
            }


        }

        return MessageInfo.ok();

    }

    @Override
    public MessageInfo executeBatch(List<DataAddVO> dataAddVOS) {
        List<PerceptionMonitorHazardousGasInfo> perceptionMonitorHazardousGasInfos = new ArrayList<>();
        for (DataAddVO dataAddVO : dataAddVOS) {
            PerceptionMonitorHazardousGasInfo perceptionMonitorHazardousGasInfo = JSONUtil.toBean(dataAddVO.getJsonDate().toString(), PerceptionMonitorHazardousGasInfo.class);
            perceptionMonitorHazardousGasInfo.setAppId(dataAddVO.getAppId());
            perceptionMonitorHazardousGasInfos.add(perceptionMonitorHazardousGasInfo);
        }

        String command = dataAddVOS.get(0).getCommand();

        if (MessageCommandEnum.MESSAGE_ADD.getCommand().equals(command)) {
            log.info("PerceptionMonitorHazardousGasInfoStrategy 进行add-Batch操作 ......");
            perceptionMonitorHazardousGasInfoStrategy.perceptionMonitorHazardousGasInfoService.saveBatch(perceptionMonitorHazardousGasInfos);
        }

        return MessageInfo.ok();
    }
}
