package com.zksy.visualization.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.common.core.domain.Result;
import com.zksy.visualization.config.IccConfigProperty;
import com.zksy.visualization.domain.request.*;
import com.zksy.visualization.domain.response.AnalogQuantityResponse;
import com.zksy.visualization.domain.response.EventStatisticsResponse;
import com.zksy.visualization.domain.response.FireEquipmentResponse;
import com.zksy.visualization.domain.response.FirefightingComponentsResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author Administrator
 * @version 1.0
 * @project dh-server-micro
 * @description 消防业务
 * @date 2024/12/19 15:17:52
 */
@RestController
@Api(tags = "消防业务", description = "消防业务")
@RequestMapping("/fireFighting")
@Slf4j
public class FireFightingController {
    @Autowired
    private OkHttpClient httpClient;
    @Autowired
    private IccConfigProperty iccConfigProperty;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    @ApiOperation(value = "消防物联设备分页查询")
    @PostMapping("/queryFireEquipment")
    public Result queryFireEquipment(FireEquipmentRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-fdbu/"+ iccConfigProperty.getVersion() +"/device/subsystem/page")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        FireEquipmentResponse fireEquipmentResponse = objectMapper.treeToValue(dataNode, FireEquipmentResponse.class);
                        return Result.ok(fireEquipmentResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("消防物联设备分页查询失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "消防探测器分页查询")
    @PostMapping("/analogQuantity")
    public Result analogQuantity(FirefightingComponentsRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-fdbu/"+ iccConfigProperty.getVersion() +"/detector/subsystem/page")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        FirefightingComponentsResponse firefightingComponentsResponse = objectMapper.treeToValue(dataNode, FirefightingComponentsResponse.class);
                        return Result.ok(firefightingComponentsResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("消防探测器分页查询失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "分页查询消防最新模拟量信息")
    @PostMapping("/fireSimulation")
    public Result fireSimulation(AnalogQuantityRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-fdbu/"+ iccConfigProperty.getVersion() +"/analog/subsystem/page")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        AnalogQuantityResponse analogQuantityResponse = objectMapper.treeToValue(dataNode, AnalogQuantityResponse.class);
                        return Result.ok(analogQuantityResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("分页查询消防最新模拟量信息失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "消防事件统计")
    @PostMapping("/queryEventStatistics")
    public Result queryEventStatistics(EventStatisticsRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-event/"+ iccConfigProperty.getVersion() +"/alarm-record/count-num")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        EventStatisticsResponse fireEquipmentResponse = objectMapper.treeToValue(dataNode, EventStatisticsResponse.class);
                        return Result.ok(fireEquipmentResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("消防事件统计失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "alarm事件分页查询")
    @PostMapping("/queryEventStatisticsPage")
    public Result queryEventStatisticsPage(EventStatisticsPageRequest request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-event/"+ iccConfigProperty.getVersion() +"/alarm-record/page")
                .addHeader("Authorization", authorization)
                .post(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("消防事件统计失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
    @ApiOperation(value = "alarm事件处理")
    @PostMapping("/getAlarmEventProcessing")
    public Result getAlarmEventProcessing(AlarmRecord request){
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonParams = null;
        try {
            jsonParams = objectMapper.writeValueAsString(request);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败: {}", e);
            return Result.error("请求失败");
        }
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        // 创建请求体
        RequestBody body = RequestBody.create(jsonParams, JSON);
        // 构建请求
        Request requestHttp = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-event/"+iccConfigProperty.getVersion()+"/alarm-record/stat")
                .addHeader("Authorization", authorization)
                .put(body)
                .build();
        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return Result.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return Result.ok(dataNode);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    return Result.error("事件处理失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
}
