package com.zksy.visualization.controller.smartElectricController;

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.DevicesOperatorRequest;
import com.zksy.visualization.domain.request.ElectricEnergyMonitorRequest;
import com.zksy.visualization.domain.response.DevicesOperatorResponse;
import com.zksy.visualization.domain.response.ElectricEnergyMonitorResponse;
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/18 15:33:33
 */
@RestController
@Api(tags = "智慧用电-电能监测", description = "智慧用电-电能监测")
@RequestMapping("/electricEnergyMonitor")
@Slf4j
public class ElectricEnergyMonitorController {
    @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("/getElectricEnergyMonitor")
    public Result getElectricEnergyMonitor(ElectricEnergyMonitorRequest 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-electricity/"+ iccConfigProperty.getVersion() +"/electric-energy-detection/showInfos")
                .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(success.isBoolean() && success.asBoolean()) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        ElectricEnergyMonitorResponse parkingOverviewResponse = objectMapper.treeToValue(dataNode, ElectricEnergyMonitorResponse.class);
                        return Result.ok(parkingOverviewResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode errMsgNode = rootNode.path("errMsg");
                    String errMsg = errMsgNode.isTextual() ? errMsgNode.asText() : "未知错误";
                    return Result.error(errMsg);
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }

    @ApiOperation(value = "批量开启/关闭、单个设备开启/关闭")
    @PostMapping("/devicesOperator")
    public Result DevicesOperator(DevicesOperatorRequest 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-electricity/"+ iccConfigProperty.getVersion() +"/electric-energy-detection/devicesOperator")
                .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(success.isBoolean() && success.asBoolean()) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        DevicesOperatorResponse parkingOverviewResponse = objectMapper.treeToValue(dataNode, DevicesOperatorResponse.class);
                        return Result.ok(parkingOverviewResponse);
                    } else {
                        return Result.ok(null);
                    }
                }else {
                    JsonNode errMsgNode = rootNode.path("errMsg");
                    String errMsg = errMsgNode.isTextual() ? errMsgNode.asText() : "未知错误";
                    return Result.error(errMsg);
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return Result.error("请求失败");
    }
}
