package shop.alien.store.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiSort;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import shop.alien.entity.result.R;
import shop.alien.store.util.FileUploadUtil;
import shop.alien.store.util.ImageToPdfUploadUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 二期-文件上传
 *
 * @author ssk
 * @version 1.0
 * @date 2024/12/6 15:30
 */
@Slf4j
@Api(tags = {"二期-文件上传"})
@ApiSort(6)
@CrossOrigin
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class StoreFileUploadController {

    private final FileUploadUtil fileUpload;
    
    private final ImageToPdfUploadUtil imageToPdfUploadUtil;

    @ApiOperation("单个文件上传(图片、视频或PDF,返回路径)")
    @ApiOperationSupport(order = 1)
    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("StoreFileUploadController.upload fileName：{}", file.getOriginalFilename());
        return R.data(fileUpload.uploadOneFile(file));
    }

    @ApiOperation("多个文件上传(图片、视频或PDF,视频会截取第一秒图片,返回路径)")
    @ApiOperationSupport(order = 2)
    @PostMapping("/uploadMore")
    public R<List<String>> uploadMore(MultipartRequest multipartRequest) {
        log.info("StoreFileUploadController.upload uploadMore：{}", multipartRequest);
        return R.data(fileUpload.uploadMoreFile(multipartRequest));
    }

    @ApiOperation(value = "图片上传(其实也可以传视频,不会截图), 返回图片id", notes = "文件格式: file_0,file_1, list格式: [{\"storeId\":1,\"imgType\":3,\"imgDescription\":\"菜品1\",\"imgSort\":1},{\"storeId\":1,\"imgType\":3,\"imgDescription\":\"菜品2\",\"imgSort\":2}]")
    @ApiOperationSupport(order = 3)
    @PostMapping("/uploadImg")
    public R<List<Integer>> uploadImg(MultipartRequest multipartRequest, @RequestParam("list") String list) {
        return R.data(fileUpload.uploadImg(multipartRequest, list));
    }

    @ApiOperation("上传app(格式包含apk,ipa,wgt,返回路径)")
    @ApiOperationSupport(order = 4)
    @PostMapping("/uploadApp")
    public R<String> uploadApp(@RequestParam("file") MultipartFile file) {
        log.info("StoreFileUploadController.uploadApp fileName：{}", file.getOriginalFilename());
        return R.data(fileUpload.uploadApp(file));
    }

    @ApiOperation("上传PDF文件(返回路径)")
    @ApiOperationSupport(order = 5)
    @PostMapping("/uploadPdf")
    public R<String> uploadPdf(@RequestParam("file") MultipartFile file) {
        log.info("StoreFileUploadController.uploadPdf fileName：{}", file.getOriginalFilename());
        try {
            String filePath = fileUpload.uploadPdf(file);
            if (filePath == null) {
                return R.fail("上传失败，文件不是PDF格式");
            }
            return R.data(filePath);
        } catch (Exception e) {
            log.error("上传PDF文件失败: {}", e.getMessage(), e);
            return R.fail("上传失败: " + e.getMessage());
        }
    }

    @ApiOperation("图片转PDF并上传(单张图片,返回PDF的线上URL)")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "file",
                    value = "图片文件（支持jpg、jpeg、png、bmp、webp、gif格式）",
                    dataType = "file",
                    paramType = "form",
                    required = true
            )
    })
    @PostMapping("/imageToPdf")
    public R<String> imageToPdf(@RequestParam("file") MultipartFile file) {
        log.info("StoreFileUploadController.imageToPdf fileName：{}", file.getOriginalFilename());
        try {
            // 参数验证
            if (file == null || file.isEmpty()) {
                return R.fail("请选择要转换的图片文件");
            }
            
            String pdfUrl = imageToPdfUploadUtil.imageToPdfAndUpload(file);
            if (pdfUrl == null) {
                return R.fail("图片转PDF并上传失败，请检查图片格式是否正确");
            }
            return R.data(pdfUrl);
        } catch (IllegalArgumentException e) {
            log.warn("图片转PDF参数错误: {}", e.getMessage());
            return R.fail("参数错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("图片转PDF并上传失败: {}", e.getMessage(), e);
            return R.fail("图片转PDF并上传失败: " + e.getMessage());
        }
    }

    @ApiOperation("图片转PDF并上传(多张图片合并为一个PDF,返回PDF的线上URL)")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "files",
                    value = "图片文件列表（支持jpg、jpeg、png、bmp、webp、gif格式，可上传多张）",
                    dataType = "file",
                    paramType = "form",
                    required = true,
                    allowMultiple = true
            )
    })
    @PostMapping("/imagesToPdf")
    public R<String> imagesToPdf(MultipartRequest multipartRequest) {
        log.info("StoreFileUploadController.imagesToPdf");
        try {
            if (multipartRequest == null) {
                return R.fail("请求参数不能为空");
            }
            
            List<MultipartFile> imageFiles = new ArrayList<>();
            for (String key : multipartRequest.getFileMap().keySet()) {
                MultipartFile file = multipartRequest.getFile(key);
                if (file != null && !file.isEmpty()) {
                    imageFiles.add(file);
                }
            }
            
            if (imageFiles.isEmpty()) {
                return R.fail("请至少上传一张图片");
            }
            
            log.info("StoreFileUploadController.imagesToPdf 收到{}张图片", imageFiles.size());
            
            String pdfUrl = imageToPdfUploadUtil.imagesToPdfAndUpload(imageFiles);
            if (pdfUrl == null) {
                return R.fail("图片转PDF并上传失败，请检查图片格式是否正确");
            }
            return R.data(pdfUrl);
        } catch (IllegalArgumentException e) {
            log.warn("图片转PDF参数错误: {}", e.getMessage());
            return R.fail("参数错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("图片转PDF并上传失败: {}", e.getMessage(), e);
            return R.fail("图片转PDF并上传失败: " + e.getMessage());
        }
    }

    @ApiOperation("图片转PDF并上传(A4页面大小,单张图片,返回PDF的线上URL)")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "file",
                    value = "图片文件（支持jpg、jpeg、png、bmp、webp、gif格式，图片会自动缩放适应A4页面）",
                    dataType = "file",
                    paramType = "form",
                    required = true
            )
    })
    @PostMapping("/imageToPdfA4")
    public R<String> imageToPdfA4(@RequestParam("file") MultipartFile file) {
        log.info("StoreFileUploadController.imageToPdfA4 fileName：{}", file.getOriginalFilename());
        try {
            // 参数验证
            if (file == null || file.isEmpty()) {
                return R.fail("请选择要转换的图片文件");
            }
            
            String pdfUrl = imageToPdfUploadUtil.imageToPdfA4AndUpload(file);
            if (pdfUrl == null) {
                return R.fail("图片转PDF并上传失败，请检查图片格式是否正确");
            }
            return R.data(pdfUrl);
        } catch (IllegalArgumentException e) {
            log.warn("图片转PDF参数错误: {}", e.getMessage());
            return R.fail("参数错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("图片转PDF并上传失败: {}", e.getMessage(), e);
            return R.fail("图片转PDF并上传失败: " + e.getMessage());
        }
    }

    @ApiOperation("Base64图片转PDF并上传(返回PDF的线上URL)")
    @ApiOperationSupport(order = 9)
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "base64Image",
                    value = "Base64编码的图片字符串（支持带或不带data:image前缀，如：data:image/png;base64,iVBORw0KGgo...）",
                    dataType = "String",
                    paramType = "form",
                    required = true
            )
    })
    @PostMapping("/base64ToPdf")
    public R<String> base64ToPdf(@RequestParam("base64Image") String base64Image) {
        log.info("StoreFileUploadController.base64ToPdf 收到Base64图片");
        try {
            // 参数验证
            if (!StringUtils.hasText(base64Image)) {
                return R.fail("Base64图片字符串不能为空");
            }

            String pdfUrl = imageToPdfUploadUtil.base64ToPdfAndUpload(base64Image);
            if (pdfUrl == null) {
                return R.fail("Base64图片转PDF并上传失败，请检查Base64格式是否正确");
            }
            return R.data(pdfUrl);
        } catch (IllegalArgumentException e) {
            log.warn("Base64图片转PDF参数错误: {}", e.getMessage());
            return R.fail("参数错误: " + e.getMessage());
        } catch (Exception e) {
            log.error("Base64图片转PDF并上传失败: {}", e.getMessage(), e);
            return R.fail("Base64图片转PDF并上传失败: " + e.getMessage());
        }
    }

}
