package com.kexue.skills.controller;

import com.kexue.skills.common.CommonResult;
import com.kexue.skills.config.UploadConfig;
import com.kexue.skills.entity.request.UploadResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author 维哥
 * @Description
 * @create 2025-02-27 10:55
 */
@RestController
@RequestMapping("api/common")
@Tag(name = "Common Api")
@CrossOrigin(origins = "*")
@Slf4j
public class CommonController {

    @Resource
    private UploadConfig uploadConfig;


    /**
     * 文件上传接口
     * URL: http://localhost:8080/common/uploadFile
     * Method: POST
     * Body: form-data
     * Key: file
     * Value: 选择一个文件进行上传
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    @Operation(summary = "文件上传", description = "文件上传接口")
    public CommonResult<UploadResponse> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("文件为空，请选择文件后再上传");
        }

        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(uploadConfig.getFileUploadDir());
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 构建文件保存路径
            Path filePath = uploadPath.resolve(file.getOriginalFilename());

            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            UploadResponse uploadResponse = new UploadResponse();
            uploadResponse.setFileName(file.getOriginalFilename());
            uploadResponse.setFileUrl(uploadConfig.getFileUrlPrefix() + file.getOriginalFilename());
            return CommonResult.success(uploadResponse);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 图片上传接口
     * URL: http://localhost:8080/common/uploadImage
     * Method: POST
     * Body: form-data
     * Key: file
     * Value: 选择一个图片文件进行上传
     * @param image
     * @return
     */
    @PostMapping("/uploadImage")
    @Operation(summary = "图片上传", description = "图片上传接口")
    public CommonResult<UploadResponse> uploadImage(@RequestParam("image") MultipartFile image) {
        if (image.isEmpty()) {
            return CommonResult.failed("图片为空，请选择图片后再上传");
        }

        // 检查文件是否为图片
        if (!image.getContentType().startsWith("image")) {
            return CommonResult.failed("上传的文件不是图片");
        }

        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(uploadConfig.getImgUploadDir());
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 构建文件保存路径
            Path filePath = uploadPath.resolve(image.getOriginalFilename());

            // 保存文件
            Files.copy(image.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            UploadResponse uploadResponse = new UploadResponse();
            uploadResponse.setFileName(image.getOriginalFilename());
            uploadResponse.setFileUrl(uploadConfig.getImgUrlPrefix() + image.getOriginalFilename());
            return CommonResult.success(uploadResponse);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("图片上传失败: " + e.getMessage());
        }
    }

    // 在 CommonController.java 中新增接口




}
