package com.ruoyi.dj.mqtt.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dj.mqtt.cmd.CmdConstant;
import com.ruoyi.system.domain.GatewayOperationLog;
import com.ruoyi.system.service.IGatewayOperationLogService;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @auther 周志雄
 * @date 2024/7/10 17:41
 */

@Component
public class GatewayOperationLogUtil {

    @Resource
    private IGatewayOperationLogService gatewayOperationLogService;

    private static IGatewayOperationLogService staticGatewayOperationLogService;

    @PostConstruct
    public void init() {
        staticGatewayOperationLogService = this.gatewayOperationLogService;
    }

    public static void generateLog(String gateway, String method, String message, String response) {
        ObjectMapper objectMapper = new ObjectMapper();
        String resultMsg = "成功";
        try {
            JsonNode rootNode = objectMapper.readTree(response);
            int result = rootNode.path("data").path("result").asInt();
            if (result != 0) {
                resultMsg = "失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        GatewayOperationLog gatewayOperationLog = new GatewayOperationLog();
        gatewayOperationLog.setGatewayId(gateway);
        gatewayOperationLog.setOperationCommand(method);
        gatewayOperationLog.setSendParams(message);
        gatewayOperationLog.setExecutionResponse(response);
        gatewayOperationLog.setExecutionResult(resultMsg);
        gatewayOperationLog.setOperationTime(new Date());
        staticGatewayOperationLogService.insertGatewayOperationLog(gatewayOperationLog);
    }
}
