package com.zksy.controller.common;

import com.zksy.common.domain.FileManager;
import com.zksy.common.domain.dto.FileManagerDTO;
import com.zksy.common.service.FileManagerService;
import com.zksy.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author sy
 * @date 2025-06-25
 */
@RestController
@RequestMapping("/fileManager")
@Api(tags = "文件管理")
public class FileManagerController {

    @Autowired
    private FileManagerService service;

    @PostMapping("/upload")
    @ApiOperation(value = "文件管理新增")
    public AjaxResult save(@RequestBody FileManagerDTO fileManagerDTO) {
        FileManager xcrFile = buildXrcFile(fileManagerDTO);
        xcrFile.setCreateBy("管理员");
        xcrFile.setCreateTime(LocalDateTime.now());
        return service.saveMinio(xcrFile, fileManagerDTO.getFile())
                ? AjaxResult.success(xcrFile)
                : AjaxResult.error("新增失败");
    }

    @PostMapping("/updateById")
    @ApiOperation(value = "文件管理修改")
    public AjaxResult updateById(FileManagerDTO fileManagerDTO) {
        FileManager xcrFile = buildXrcFile(fileManagerDTO);
        xcrFile.setUpdateBy("管理员");
        xcrFile.setUpdateTime(LocalDateTime.now());
        return service.updateMinio(xcrFile, fileManagerDTO.getFile())
                ? AjaxResult.success(xcrFile)
                : AjaxResult.error("更新失败");
    }

    @PostMapping("/deleteFile")
    @ApiOperation(value = "文件管理删除")
    public AjaxResult deleteFile(FileManagerDTO fileManagerDTO) {
        return service.deleteFile(fileManagerDTO.getId().toString())
                ? AjaxResult.success("删除成功")
                : AjaxResult.error("删除失败");
    }
    @GetMapping("/getFileByFid")
    @ApiOperation(value = "根据fid查询文件")
    public AjaxResult getFileByFid(String fid) {
        return AjaxResult.success(service.getFileByFid(fid));
    }

    private FileManager buildXrcFile(FileManagerDTO fileManagerDTO) {
        FileManager xcrFile = new FileManager();
        xcrFile.setId(fileManagerDTO.getId());
        xcrFile.setFid(fileManagerDTO.getFid());
        xcrFile.setModuleName(fileManagerDTO.getModuleName());
        xcrFile.setFileOriginalName(fileManagerDTO.getFile().getOriginalFilename());
        xcrFile.setFileSize(fileManagerDTO.getFile().getSize());
        return xcrFile;
    }

}

