package com.ruoyi.dj.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dj.mqtt.domain.RespModel;
import com.ruoyi.dj.mqtt.utils.AESUtil;
import com.ruoyi.dj.mqtt.utils.StorageConfigUtil;
import com.ruoyi.dj.websocket.service.MessagingService;
import io.minio.*;
import io.minio.errors.ErrorResponseException;
import io.minio.http.Method;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

@Slf4j
@Api(tags = "AI相关")
@RestController
@RequestMapping("/business/ai")
public class AiController {

    // 创建一个线程安全的 MinioClient 实例、避免重复创建
    private static final MinioClient minioClient = StorageConfigUtil.getMinioClient();
    @Resource
    private MessagingService messagingService;

    @PostMapping("/callback")
    public AjaxResult ai(@RequestBody AiDataObject aiDataObject) {
        System.out.println("收到AI数据：" + aiDataObject.getCategory_counts());
        String gateway = aiDataObject.getGateway();

        System.out.println(aiDataObject.getCategory_counts());

        try {
            // 解码 imgData
            byte[] decodedImg = Base64.decodeBase64(aiDataObject.getFrame_base64());
            // 获取当前日期，构建目录结构
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            String datePath = dateFormat.format(new Date());
            // 定义桶名称
            String bucketName = "ai" + gateway.toLowerCase().replace("_", "");
            // 检查桶是否存在、不存在则创建
            synchronized (this) {
                // 使用 synchronized 避免并发创建
                if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                    try {
                        minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                        log.info("已创建桶: {}", bucketName);
                    } catch (Exception e) {
                        if (e instanceof ErrorResponseException &&
                                ((ErrorResponseException) e).errorResponse().code().equals("BucketAlreadyOwnedByYou")) {
                            log.warn("桶已存在: {}", bucketName);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            // 生成文件名
            String fileName = UUID.randomUUID().toString() + ".jpg";
            String objectName = "AI检测数据/" + datePath + "/" + fileName;
            // 上传文件，设置并发上传，提高效率
            ByteArrayInputStream inputStream = new ByteArrayInputStream(decodedImg);
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(inputStream, decodedImg.length, -1)
                            .contentType("image/jpeg")
                            .build()
            );
            log.info("文件上传成功: {}", objectName);
        } catch (Exception e) {
            log.error("保存图片时出现错误", e);
        }
        return AjaxResult.success();
    }
}
