package com.css.simulation.resource.video.controller;

import api.common.pojo.common.ResponseBodyVO;
import api.common.util.StringUtil;
import com.css.simulation.resource.video.service.VideoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class VideoController {

    @Resource
    private VideoService videoService;

    /**
     * 接受 xosc 文件
     */
    @GetMapping(value = "/generate")
    ResponseBodyVO<String> generateVideo(
            @RequestParam("generateVideoKey") String generateVideoKey,
            @RequestParam("nodeName") String nodeName,
            @RequestParam("projectId") String projectId,
            @RequestParam("projectType") String projectType,
            @RequestParam("maxSimulationTime") String maxSimulationTime,
            @RequestParam("taskId") String taskId
    ) {
        log.info("节点 nodeName 收到项目 " + projectId + " 的任务 " + taskId + " 生成 cpu 视频的请求。");
        new Thread(
                () -> videoService.generateVideo(generateVideoKey, nodeName, projectId, projectType, maxSimulationTime, taskId),
                "generateVideo-" + StringUtil.getRandomEightBitUUID()
        ).start();
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);
    }




    @RequestMapping(value = "/uploadToLocal")
    public ResponseBodyVO<Map<String, String>> uploadToLocal(
            @RequestParam("name") String name,
            @RequestParam("type") String type,
            @RequestParam("objectPath") String objectPath,
            @RequestPart("file") MultipartFile file
    ) {
        // 获取文件原本的名字
        String originName = file.getOriginalFilename();
        String fileName = originName.substring(0, originName.lastIndexOf("."));
        // 创建保存路径
        // 日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String format = sdf.format(new Date());
        // 保存文件的文件夹
        String savePath = "/root/disk1/simulation-cloud/esmini/resources/models/" + fileName + "/" + format;
        log.info("车辆模型对应osgb地址:" + savePath);
        File folder = new File(savePath);
        // 判断路径是否存在,不存在则自动创建
        if (!folder.exists()) {
            folder.mkdirs();
        }
        try {
            file.transferTo(new File(folder, originName));
            Map<String, String> map = new HashMap<>();
            String filePath = savePath + "/" + originName;
            map.put("filePath", filePath);
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS, map);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, e.getMessage());
        }
    }

}
