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.AccessControlRequest;
import com.zksy.visualization.domain.request.AccessQueryNumberRequest;
import com.zksy.visualization.domain.request.AccessRecordQueryRequest;
import com.zksy.visualization.domain.request.DevicePageRequest;
import com.zksy.visualization.domain.response.DevicePageResponse;
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 2025/1/16 09:48:44
 */
@RestController
@Api(tags = "门禁管理", description = "门禁管理")
@RequestMapping("/accessControl")
@Slf4j
public class AccessControlController {
    @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("/getAccessControl")
    public Result getAccessControl(DevicePageRequest 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-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(success.isBoolean() && success.asBoolean()) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode.isObject()) {
                        DevicePageResponse intelligentPanelResponse = objectMapper.treeToValue(dataNode, DevicePageResponse.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("/getAccessControlPage")
    public Result getAccessControlPage(AccessRecordQueryRequest 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-accesscontrol/"+ iccConfigProperty.getVersion()+"/card/accessControl/swingCardRecord/bycondition/combined")
                .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("/getAccessControlNumber")
    public Result getAccessControlNumber(AccessQueryNumberRequest 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-accesscontrol/"+ iccConfigProperty.getVersion()+"/card/accessControl/swingCardRecord/bycondition/combinedCount")
                .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("请求失败");
    }
}
