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.ChannelPageRequest;
import com.zksy.visualization.domain.request.DevicePageRequest;
import com.zksy.visualization.domain.request.DeviceTreeRequest;
import com.zksy.visualization.domain.response.ChannelPageResponse;
import com.zksy.visualization.domain.response.DeviceDetailsResponse;
import com.zksy.visualization.domain.response.DevicePageResponse;
import com.zksy.visualization.domain.response.DeviceTreeResponse;
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.GetMapping;
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/12 16:56:41
 */
@RestController
@Api(tags = "设备管理", description = "设备管理")
@RequestMapping("/deviceInfo")
@Slf4j
public class DeviceInfoController {
    @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 = "设备详情查询")
    @GetMapping("/deviceDetails")
    public Result deviceDetails(String deviceCode){
        String authorization = redisTemplate
                .opsForValue()
                .get("Authorization:" + iccConfigProperty.getUsername());
        Request request = new Request.Builder()
                .url("https://" + iccConfigProperty.getHost() + "/evo-apigw/evo-brm/"+iccConfigProperty.getVersion()+"/device/"+deviceCode)
                .addHeader("Authorization", authorization)
                .build();
        try {
            Response response = httpClient.newCall(request).execute();
            if(!response.isSuccessful()){
                return Result.error("设备详情查询失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if(success.isBoolean() && success.asBoolean()) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        DeviceDetailsResponse parkingOverviewResponse = objectMapper.treeToValue(dataNode, DeviceDetailsResponse.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 (Exception e) {
            log.error("设备详情查询失败:{}", e);
        }
        return Result.error("设备详情查询失败");
    }
    @ApiOperation(value = "设备分页查询")
    @PostMapping("/devicePage")
    public Result devicePage(DevicePageRequest 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-brm/"+ 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 != 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 = "设备树查询")
    @PostMapping("/deviceTree")
    public Result deviceTree(DeviceTreeRequest 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-brm/"+ iccConfigProperty.getVersion() +"/tree")
                .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()) {
                        DeviceTreeResponse deviceTreeResponse = objectMapper.treeToValue(dataNode, DeviceTreeResponse.class);
                        return Result.ok(deviceTreeResponse);
                    } 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("请求失败");
    }

    /**
     * TODO 分页获取通道信息
     * @param
     * @return ChannelPageResponse
     * @author Administrator
     * @date 2024/12/12 16:02:14
     */
    @ApiOperation(value = "分页获取通道信息")
    @PostMapping("/getChannelPage")
    public Result getChannelPage(ChannelPageRequest 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-brm/"+ iccConfigProperty.getVersion() +"/device/channel/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(success.isBoolean() && success.asBoolean()) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        ChannelPageResponse intelligentPanelResponse = objectMapper.treeToValue(dataNode, ChannelPageResponse.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("请求失败");
    }
}
