package com.Modules.Device;


import com.common.entity.DeviceDevice;
import com.haobang.config.AppConfig;
import com.kafka.kafkaProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.common.service.DeviceDeviceService;
import com.common.service.DeviceUnknownService;
import com.common.service.DeviceCollectTaskService;
import com.haobang.util.SpringContextUtil;

import java.time.format.DateTimeFormatter;
import java.util.List;
import com.common.entity.DeviceUnknown;
import com.common.entity.DeviceCollectTask;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import com.common.service.DeviceReceiveLogService;
import com.common.entity.DeviceReceiveLog;

import org.springframework.cache.CacheManager;

public class DeviceProcess {

    private static final Logger logger = LoggerFactory.getLogger(DeviceProcess.class);

    @Autowired
    public static DeviceDeviceService  deviceDeviceService =SpringContextUtil.getBean(DeviceDeviceService.class);
    @Autowired
    public static DeviceUnknownService  deviceUnknownService =SpringContextUtil.getBean(DeviceUnknownService.class);
    @Autowired
    public static DeviceCollectTaskService  deviceCollectTaskService =SpringContextUtil.getBean(DeviceCollectTaskService.class);

    @Autowired
    public static DeviceReceiveLogService  deviceReceiveLogService =SpringContextUtil.getBean(DeviceReceiveLogService.class);


    @Autowired
    private DeviceDevice deviceDevice  ;
    @Autowired
    private  DeviceReceiveLog devicelog;
    private String sourceIP;

    public  DeviceProcess(String source_ip) {
        sourceIP=source_ip;
        List<DeviceDevice> deviceList = deviceDeviceService.getByIpSafely(source_ip);
        if (deviceList.size() >0)
        {
            deviceDevice= deviceList.get(0);
        }
    }
    public DeviceDevice  getDeviceDevice()
    {
        if(deviceDevice!=null)  return this.deviceDevice;
        return null;
    }

    public DeviceReceiveLog  getDeviceReceiveLog()
    {
        if(devicelog!=null)  return this.devicelog;
        return null;
    }
    public  int getDeviceID(String source_ip)
    {
        //默认deviceId =-1
        int  deviceId=-1 ;
        List<DeviceDevice>  deviceList=  deviceDeviceService.getByIpSafely(source_ip);
        if(deviceList.isEmpty()) {
            logger.error("设备请求的Host IP非系统注册，请联系管理员添加设备信息！");
            return deviceId;
        }
        if(deviceList.size()>1)
        {
            logger.error("设备请求的Host IP注册超过一条记录，请联系管理员处理！");
            return deviceId;
        }
        return   deviceList.get(0).getId();
    }

    public   boolean IsBelongDeviceCollectTask( )
    {
        //当前判断是否归属
        if(deviceDevice!=null )
        {
            int deviceCollectId =AppConfig.getDeviceCollectId();
            if(deviceDevice.getDeviceCollectId()!=deviceCollectId)
            {
                logger.error("设备请求的Host IP不属于当前采集探针任务,请联系管理员核实！");
                return false;
            }
        }
        return true;
    }
    public boolean saveDeviceUnknow(String networkProtocol)
    {
        DeviceUnknown deviceUnknown =new DeviceUnknown() ;
        List<DeviceUnknown> deviceList =deviceUnknownService.getDevicesByIp(this.sourceIP);
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        try
        {
            //已有deviceUnknow记录则更新最后发现时间
            if(deviceList.size()>0)
            {
                deviceUnknownService.updateLastTime( deviceList.get(0).getId(),currentTime );
                System.out.println("更新未知设备的最后发现时间,IP:"+this.sourceIP);
            }
            else {
                //创建未知设备记录
                DeviceCollectTask   deviceCollectTask= deviceCollectTaskService.getById(AppConfig.getDeviceCollectId());
                deviceUnknown.setDeviceCollectId( AppConfig.getDeviceCollectId());
                deviceUnknown.setDeviceIp( this.sourceIP);
                deviceUnknown.setFirstTime(currentTime);
                if(deviceCollectTask!=null)   deviceUnknown.setDeviceCollectName(deviceCollectTask.getTaskName());
                deviceUnknown.setNetworkProtocol( networkProtocol );
                deviceUnknown.setOrganizationId(0);
                deviceUnknownService.createDevice(deviceUnknown);
                logger.info("请求的Host IP :{}为未知，已创建记录 ",this.sourceIP);
            }
        }
        catch(Exception e) {
            logger.error("saveDeviceUnknow exception", e);
        }


        return true;
    }


    public boolean saveDeviceReceiveLog(String syslog ,boolean isSuccess ) {

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义格式化器，包含毫秒
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        // 转换为字符串
        String timeString = now.format(formatter);

        try {
            // 创建设备接收日志对象
            devicelog= DeviceReceiveLog.builder()
                    .deviceId(deviceDevice.getId())
                    .deviceCollectId(AppConfig.getDeviceCollectId())
                    .deviceIp(deviceDevice.getIp())
                    .receiveTime(now)
                    .receiveTimeStr(timeString)
                    .syslogMessage(syslog)
                    .pushSuccess(isSuccess)
                    .build();
            deviceReceiveLogService.insertLog(devicelog);
        } catch (Exception e) {
            logger.error("saveDeviceReceiveLog exception", e);
            return false;
        }
        return true;
    }


}
