package com.usky.ai.controller.web;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.ai.domain.AiAlarmLog;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import org.springframework.http.*;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/upload")
public class UniversalUploadController {

    @Value("${file.domain}")
    private String fileDomain;

    @Value("${file.path}")
    private String filePath;

    @Value("${file.prefix}")
    private String filePrefix;

    @Value("${aiAlarmLog.api}")
    private String alarmLogApi;

    // 定义一个线程安全的计数器
    private static final AtomicInteger counter = new AtomicInteger(0);

    @PostMapping(value = "/anything", consumes = "*/*")
    public String receiveAnything(HttpServletRequest request) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String body = sb.toString();
            System.out.println("Received raw data:");
            System.out.println(body);

            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(body);

            // 创建告警日志对象
            AiAlarmLog alarmLog = new AiAlarmLog();

            // 设置字段
            alarmLog.setDeviceId(getTextValue(jsonNode, "BoardId"));
            alarmLog.setAlarmTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            alarmLog.setAlarmType("666");
            alarmLog.setAlarmObject(getTextValue(jsonNode, "TaskSession"));
            alarmLog.setAlarmData("0");
            alarmLog.setAlarmAttribute(getTextValue(jsonNode, "Summary"));
            alarmLog.setAlarmContent(getTextValue(jsonNode.get("Result"), "Description"));
            alarmLog.setAlarmGrade(1);
            alarmLog.setAlarmAddress("二楼研发中心");
            alarmLog.setProductCode("513_202");


            // 处理图片存储
            String imageDataLabeled = getTextValue(jsonNode, "ImageDataLabeled");
            if (!imageDataLabeled.isEmpty()) {
                try {
                    String imageUrl = saveImage(imageDataLabeled, "sitePhoto");
                    alarmLog.setSitePhoto(imageUrl);
                } catch (Exception e) {
                    System.err.println("Failed to save image: " + e.getMessage());
                    e.printStackTrace();
                }
            }

            // 调用新增告警日志接口
            if (!sendAlarmLog(alarmLog)) {
                return "Failed to send alarm log";
            }

            return "Received data:\n" + body;
        } catch (Exception e) {
            e.printStackTrace();
            return "Error reading request body: " + e.getMessage();
        }
    }

    // 添加辅助方法处理可能的空值
    private String getTextValue(JsonNode node, String fieldName) {
        JsonNode fieldNode = node.get(fieldName);
        if (fieldNode != null && !fieldNode.isNull()) {
            return fieldNode.asText();
        }
        return "";
    }

    // 保存图片并返回 URL
    private String saveImage(String base64Image, String fileName) throws IOException {
        // 检查 Base64 数据是否符合预期格式
        byte[] imageBytes;

        // 处理带有前缀的Base64数据 (如: data:image/jpeg;base64,/9j/...)
        if (base64Image.contains(",")) {
            String[] parts = base64Image.split(",", 2);
            if (parts.length < 2) {
                throw new IllegalArgumentException("Invalid Base64 image data format");
            }
            imageBytes = Base64.getDecoder().decode(parts[1]);
        } else {
            // 处理不带前缀的Base64数据 (如: /9j/...)
            imageBytes = Base64.getDecoder().decode(base64Image);
        }


        // 生成文件路径 (使用yyyyMMddHHmmss格式)
        LocalDateTime now = LocalDateTime.now();
        String monthPath = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String formattedTime = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        int counterSuffix = counter.getAndIncrement(); // 获取并递增计数器
        String filePathWithPrefix = filePath + "/" + monthPath + "/" + fileName + "_" + formattedTime + "_" + counterSuffix + ".jpg";
        Path path = Paths.get(filePathWithPrefix);

        // 保存图片到文件系统
        Files.createDirectories(path.getParent());
        Files.write(path, imageBytes);

        // 返回可访问的 URL
        return fileDomain + filePrefix + "/" + monthPath + "/" + fileName + "_" + formattedTime + "_" + counterSuffix + ".jpg";
    }

    // 调用新增告警日志接口
    private boolean sendAlarmLog(AiAlarmLog alarmLog) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<AiAlarmLog> request = new HttpEntity<>(alarmLog, headers);

        try {
            restTemplate.postForObject(alarmLogApi, request, String.class);
            return true;
        } catch (Exception e) {
            System.err.println("Failed to send alarm log: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}