package com.jeesharp.business.file.controller;

import com.jeesharp.framework.memberauth.utils.MemberAuthUtils;
import com.jeesharp.framework.memberauth.web.BaseMobileController;
import com.jeesharp.framework.pojo.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 移动端-媒体附件上传 Controller
 *
 * @author jeesharp
 * @version 2026-02-06
 */
@Slf4j
@RestController
@RequestMapping("${jeesharp.web.mobilePath}/atomicCard/media")
@Tag(name = "移动端-媒体附件上传", description = "卡片媒体附件上传相关接口")
@AllArgsConstructor
public class MediaUploadMobileController extends BaseMobileController {

    @Operation(summary = "上传单个媒体文件", description = "上传图片/音频/视频文件，返回文件URL")
    @PostMapping("/upload")
    public AjaxResult<Map<String, Object>> upload(
            @Parameter(description = "文件类型：image-图片 audio-音频 video-视频", required = true)
            @RequestParam("type") String type,
            @Parameter(description = "文件", required = true)
            @RequestParam("file") MultipartFile file) {
        String memberId = MemberAuthUtils.getLoginUserId();
        
        // 验证文件类型
        if (!isValidFileType(type, file)) {
            return AjaxResult.fail(203, "不支持的文件类型");
        }
        
        // 验证文件大小
        if (!isValidFileSize(type, file)) {
            return AjaxResult.fail(203, "文件大小超出限制");
        }
        
        try {
            // TODO: 调用文件上传服务，上传文件并返回URL
            // String fileUrl = fileUploadService.upload(file);
            // 这里先返回模拟URL
            String fileUrl = "https://cdn.example.com/files/" + file.getOriginalFilename();
            
            Map<String, Object> data = new HashMap<>();
            data.put("url", fileUrl);
            data.put("type", type);
            data.put("fileName", file.getOriginalFilename());
            data.put("fileSize", file.getSize());
            
            return AjaxResult.ok("上传成功", data);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return AjaxResult.fail(202, "文件上传失败：" + e.getMessage());
        }
    }

    @Operation(summary = "批量上传媒体文件", description = "批量上传多个媒体文件，返回文件URL列表")
    @PostMapping("/uploadBatch")
    public AjaxResult<Map<String, Object>> uploadBatch(
            @Parameter(description = "文件类型：image-图片 audio-音频 video-视频", required = true)
            @RequestParam("type") String type,
            @Parameter(description = "文件列表", required = true)
            @RequestParam("files") MultipartFile[] files) {
        String memberId = MemberAuthUtils.getLoginUserId();
        
        List<Map<String, Object>> successList = new ArrayList<>();
        List<String> failureList = new ArrayList<>();
        
        for (MultipartFile file : files) {
            // 验证文件类型
            if (!isValidFileType(type, file)) {
                failureList.add(file.getOriginalFilename() + "：不支持的文件类型");
                continue;
            }
            
            // 验证文件大小
            if (!isValidFileSize(type, file)) {
                failureList.add(file.getOriginalFilename() + "：文件大小超出限制");
                continue;
            }
            
            try {
                // TODO: 调用文件上传服务，上传文件并返回URL
                // String fileUrl = fileUploadService.upload(file);
                // 这里先返回模拟URL
                String fileUrl = "https://cdn.example.com/files/" + file.getOriginalFilename();
                
                Map<String, Object> data = new HashMap<>();
                data.put("url", fileUrl);
                data.put("type", type);
                data.put("fileName", file.getOriginalFilename());
                data.put("fileSize", file.getSize());
                successList.add(data);
            } catch (Exception e) {
                log.error("文件上传失败: {}", file.getOriginalFilename(), e);
                failureList.add(file.getOriginalFilename() + "：上传失败");
            }
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("successList", successList);
        result.put("failureList", failureList);
        
        return AjaxResult.ok("上传完成", result);
    }

    /**
     * 验证文件类型
     */
    private boolean isValidFileType(String type, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            return false;
        }
        
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        
        switch (type) {
            case "image":
                return extension.matches("jpg|jpeg|png|gif|webp");
            case "audio":
                return extension.matches("mp3|wav|m4a|aac");
            case "video":
                return extension.matches("mp4|mov|avi");
            default:
                return false;
        }
    }

    /**
     * 验证文件大小
     */
    private boolean isValidFileSize(String type, MultipartFile file) {
        long maxSize;
        switch (type) {
            case "image":
                maxSize = 5 * 1024 * 1024; // 5MB
                break;
            case "audio":
                maxSize = 10 * 1024 * 1024; // 10MB
                break;
            case "video":
                maxSize = 50 * 1024 * 1024; // 50MB
                break;
            default:
                return false;
        }
        return file.getSize() <= maxSize;
    }
}
