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.AcquisitionDeviceRequest;
import com.zksy.visualization.domain.request.EmptyDomainRequest;
import com.zksy.visualization.domain.response.*;
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/16 15:13:50
 */
@RestController
@Api(tags = "智慧用电-设备管理", description = "智慧用电-设备管理")
@RequestMapping("/acquisitionDevice")
@Slf4j
public class AcquisitionDeviceController {
    @Autowired
    private IccConfigProperty iccConfigProperty;
    @Autowired
    private OkHttpClient httpClient;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

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

    @ApiOperation(value = "获取设备能力")
    @PostMapping("/getAcquisitionDevice")
    public Result getAcquisitionDevice(AcquisitionDeviceRequest 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() +"/electricity/device/info")
                .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()) {
                        AcquisitionDeviceResponse intelligentPanelResponse = objectMapper.treeToValue(dataNode, AcquisitionDeviceResponse.class);
                        return Result.ok(intelligentPanelResponse);
                    } 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("/getEmptyDomain")
    public Result getEmptyDomain(EmptyDomainRequest 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() +"/electricity/device/airSwitch/set")
                .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.isTextual()) {
                        return Result.ok(dataNode.asText());
                    }else if (dataNode.isObject() && dataNode.isEmpty()) {
                        return Result.ok(null);
                    } else {
                        return Result.error("Unexpected data format: " + dataNode);
                    }
                }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("请求失败");
    }
/*    public AcquisitionDeviceResponse airConditioner(AcquisitionDeviceRequest acquisitionDeviceRequest){
        OauthConfigUserPwdInfo config = oauthConfigUtil.getOauthConfig();
        AcquisitionDeviceResponse response=null;
        try {
            log.info("acquisitionDevice,getAcquisitionDevice,request:{}", JSONUtil.toJsonStr(acquisitionDeviceRequest));
            response = HttpUtils.executeJson("/evo-apigw/evo-electricity/"+ iccConfigProperty.getVersion() +"/electricity/device/info", acquisitionDeviceRequest,null, Method.POST , config, AcquisitionDeviceResponse.class);
            log.info("acquisitionDevice,getAcquisitionDevice,response:{}", JSONUtil.toJsonStr(response));
        } catch (ClientException e) {
            log.error(e.getErrMsg(), e);
        }
        if(!response.isSuccess()) {
            log.info("获取设备能力失败:{}",response.getErrMsg());
        }
        return response;
    }*/

    /*public EmptyDomainResponse emptyDomain(EmptyDomainRequest emptyDomainRequest){
        OauthConfigUserPwdInfo config = oauthConfigUtil.getOauthConfig();
        EmptyDomainResponse response=null;
        try {
            log.info("emptyDomain,getEmptyDomain,request:{}", JSONUtil.toJsonStr(emptyDomainRequest));
            response = HttpUtils.executeJson("/evo-apigw/evo-electricity/"+ iccConfigProperty.getVersion() +"/electricity/device/airSwitch/set", emptyDomainRequest,null, Method.POST , config, EmptyDomainResponse.class);
            log.info("emptyDomain,getEmptyDomain,response:{}", JSONUtil.toJsonStr(response));
        } catch (ClientException e) {
            log.error(e.getErrMsg(), e);
        }
        if(!response.isSuccess()) {
            log.info("下发单个空开阀值失败:{}",response.getErrMsg());
        }
        return response;
    }*/
}
