package com.ruoyi.dj.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.dj.mqtt.utils.StorageConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/dj/video/record")
public class VideoRecordController {

    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("gateway") String gateway) {
        // 保存文件到临时目录
        String tempFilePath = saveTempFile(file);
        if (tempFilePath == null) {
            return AjaxResult.error("文件保存失败");
        }

        // 立即返回成功响应，前端会收到响应
        new Thread(() -> uploadFileAsync(gateway, tempFilePath)).start();

        // 直接返回成功响应，前端会收到响应
        return AjaxResult.success();
    }

    private String saveTempFile(MultipartFile file) {
        log.info("文件大小:");
        try {
            // 获取系统临时目录
            Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempFilePath = tempDir.resolve(file.getOriginalFilename());

            // 将文件保存到临时目录
            file.transferTo(tempFilePath.toFile());

            log.info("文件已保存到临时目录: {}", tempFilePath.toString());
            return tempFilePath.toString();
        } catch (IOException e) {
            log.error("保存文件到临时目录失败: ", e);
            return null;
        }
    }

    @Async
    public void uploadFileAsync(String gateway, String tempFilePath) {
        try {
            // 从临时目录读取文件
            File tempFile = new File(tempFilePath);
            if (!tempFile.exists()) {
                log.error("临时文件不存在: {}", tempFilePath);
                return;
            }

            // 读取文件并调用 StorageConfigUtil 上传
            StorageConfigUtil.uploadFile(gateway, "视频录制", tempFile);

            // 上传完成后，删除临时文件
            if (tempFile.delete()) {
                log.info("临时文件已删除: {}", tempFilePath);
            } else {
                log.warn("删除临时文件失败: {}", tempFilePath);
            }
        } catch (Exception e) {
            log.error("文件上传失败: ", e);
        }
    }
}
