package com.example.demo.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.UserWork;
import com.example.demo.model.enums.CommonTaskType;
import com.example.demo.service.UserWorkService;
import com.example.demo.util.JwtUtils;

import io.jsonwebtoken.ExpiredJwtException;

/**
 * 用户作品API控制器
 */
@RestController
@RequestMapping("/api/works")
public class UserWorkApiController {

    private static final Logger logger = LoggerFactory.getLogger(UserWorkApiController.class);

    @Autowired
    private UserWorkService userWorkService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取正在进行中的作品
     */
    @GetMapping("/processing")
    public ResponseEntity<Map<String, Object>> getProcessingWorks(
            @RequestHeader("Authorization") String token) {

        Map<String, Object> response = new HashMap<>();

        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            List<UserWork> processingWorks = userWorkService.getProcessingWorks(username);

            response.put("success", true);
            response.put("data", processingWorks);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("获取正在进行中的作品失败", e);
            response.put("success", false);
            response.put("message", "获取作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取我的作品列表
     * @param includeProcessing 是否包含正在排队和生成中的作品，默认为true
     * @param workType 作品类型筛选（可选）：TEXT_TO_VIDEO, IMAGE_TO_VIDEO, STORYBOARD_VIDEO, STORYBOARD_IMAGE
     */
    @GetMapping("/my-works")
    public ResponseEntity<Map<String, Object>> getMyWorks(
            @RequestHeader(value = "Authorization", required = false) String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(defaultValue = "true") boolean includeProcessing,
            @RequestParam(required = false) String workType) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 输入验证 - 设置合理的size上限
            if (page < 0) page = 0;
            if (size <= 0) size = 20;
            if (size > 100) size = 100; // 设置上限，最多100条

            // 解析作品类型
            CommonTaskType filterType = null;
            if (workType != null && !workType.isEmpty()) {
                try {
                    filterType = CommonTaskType.valueOf(workType.toUpperCase());
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的作品类型: {}", workType);
                }
            }

            // 根据参数决定是否包含正在进行中的作品
            Page<UserWork> works;
            if (filterType != null) {
                // 按类型筛选
                works = userWorkService.getUserWorksByType(username, filterType, includeProcessing, page, size);
                logger.info("获取作品列表(按类型): username={}, type={}, total={}", 
                    username, filterType, works.getTotalElements());
            } else if (includeProcessing) {
                works = userWorkService.getAllUserWorks(username, page, size);
                // 调试日志：检查是否有 PROCESSING 状态的作品
                long processingCount = works.getContent().stream()
                    .filter(w -> w.getStatus() == UserWork.WorkStatus.PROCESSING || w.getStatus() == UserWork.WorkStatus.PENDING)
                    .count();
                logger.info("获取作品列表: username={}, total={}, processing/pending={}", 
                    username, works.getTotalElements(), processingCount);
            } else {
                works = userWorkService.getUserWorks(username, page, size);
            }
            Map<String, Object> workStats = userWorkService.getUserWorkStats(username);

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("stats", workStats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取我的作品列表失败", e);
            response.put("success", false);
            response.put("message", "获取作品列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取作品详情
     */
    @GetMapping("/{workId:\\d+}")
    public ResponseEntity<Map<String, Object>> getWorkDetail(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            UserWork work = userWorkService.getUserWorkDetail(workId, username);
            
            // 增加浏览次数
            userWorkService.incrementViewCount(workId);

            response.put("success", true);
            response.put("data", work);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取作品详情失败", e);
            response.put("success", false);
            response.put("message", "获取作品详情失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新作品信息
     */
    @PutMapping("/{workId:\\d+}")
    public ResponseEntity<Map<String, Object>> updateWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> updateData) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            String title = (String) updateData.get("title");
            String description = (String) updateData.get("description");
            String tags = (String) updateData.get("tags");
            Boolean isPublic = null;
            Object isPublicObj = updateData.get("isPublic");
            if (isPublicObj instanceof Boolean) {
                isPublic = (Boolean) isPublicObj;
            } else if (isPublicObj instanceof String) {
                isPublic = Boolean.parseBoolean((String) isPublicObj);
            }

            UserWork work = userWorkService.updateWork(workId, username, title, description, tags, isPublic);

            response.put("success", true);
            response.put("data", work);
            response.put("message", "作品更新成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新作品失败", e);
            response.put("success", false);
            response.put("message", "更新作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除作品（按数据库 ID）
     */
    @DeleteMapping("/{workId:\\d+}")
    public ResponseEntity<Map<String, Object>> deleteWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            boolean deleted = userWorkService.deleteWork(workId, username);
            if (deleted) {
                response.put("success", true);
                response.put("message", "作品删除成功");
            } else {
                response.put("success", false);
                response.put("message", "作品不存在");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("删除作品失败", e);
            response.put("success", false);
            response.put("message", "删除作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除作品（按 taskId，支持 sb_xxx、sb_xxx_image 等非数字 ID）
     */
    @DeleteMapping("/{taskId}")
    public ResponseEntity<Map<String, Object>> deleteWorkByTaskId(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 通过 taskId 查找作品
            var workOpt = userWorkService.getWorkByTaskId(taskId);
            if (workOpt.isPresent()) {
                boolean deleted = userWorkService.deleteWork(workOpt.get().getId(), username);
                if (deleted) {
                    response.put("success", true);
                    response.put("message", "作品删除成功");
                } else {
                    response.put("success", false);
                    response.put("message", "作品不存在或无权限删除");
                }
            } else {
                response.put("success", false);
                response.put("message", "作品不存在: " + taskId);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("按taskId删除作品失败: {}", taskId, e);
            response.put("success", false);
            response.put("message", "删除作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 批量删除作品
     */
    @PostMapping("/batch-delete")
    public ResponseEntity<Map<String, Object>> batchDeleteWorks(
            @RequestBody Map<String, List<Long>> body,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            List<Long> workIds = body.get("workIds");
            if (workIds == null || workIds.isEmpty()) {
                response.put("success", false);
                response.put("message", "请选择要删除的作品");
                return ResponseEntity.badRequest().body(response);
            }

            // 限制单次批量删除数量，防止滥用
            if (workIds.size() > 100) {
                response.put("success", false);
                response.put("message", "单次最多删除100个作品");
                return ResponseEntity.badRequest().body(response);
            }

            Map<String, Object> result = userWorkService.batchDeleteWorks(workIds, username);
            int deletedCount = (int) result.get("deletedCount");

            response.put("success", true);
            response.put("message", "成功删除 " + deletedCount + " 个作品");
            response.put("deletedCount", deletedCount);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("批量删除作品失败", e);
            response.put("success", false);
            response.put("message", "批量删除作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 点赞作品
     */
    @PostMapping("/{workId:\\d+}/like")
    public ResponseEntity<Map<String, Object>> likeWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 检查作品是否存在
            try {
                userWorkService.getUserWorkDetail(workId, username);
                userWorkService.incrementLikeCount(workId);
                response.put("success", true);
                response.put("message", "点赞成功");
            } catch (RuntimeException e) {
                response.put("success", false);
                response.put("message", "作品不存在或无权限");
                return ResponseEntity.status(404).body(response);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("点赞作品失败", e);
            response.put("success", false);
            response.put("message", "点赞失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 下载作品（记录下载次数）
     */
    @PostMapping("/{workId:\\d+}/download")
    public ResponseEntity<Map<String, Object>> downloadWork(
            @PathVariable Long workId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 检查作品是否存在
            try {
                userWorkService.getUserWorkDetail(workId, username);
                userWorkService.incrementDownloadCount(workId);
                response.put("success", true);
                response.put("message", "下载记录成功");
            } catch (RuntimeException e) {
                response.put("success", false);
                response.put("message", "作品不存在或无权限");
                return ResponseEntity.status(404).body(response);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("记录下载失败", e);
            response.put("success", false);
            response.put("message", "记录下载失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取作品文件（实际下载）
     * 支持两种模式：
     * 1. 直接下载（download=true）：返回文件流供用户下载
     * 2. 重定向（download=false）：重定向到COS URL（默认）
     */
    @GetMapping("/{workId:\\d+}/file")
    public ResponseEntity<?> downloadWorkFile(
            @PathVariable Long workId,
            @RequestParam(defaultValue = "false") boolean download,
            @RequestHeader("Authorization") String token) {
        
        try {
            // 提取用户名（必须登录）
            String username = extractUsernameFromToken(token);
            if (username == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "用户未登录");
                return ResponseEntity.status(401).body(errorResponse);
            }

            // 获取作品并验证权限（只允许作品所有者下载）
            UserWork work = userWorkService.getWorkForDownload(workId, username);
            String resultUrl = work.getResultUrl();

            // 记录下载次数
            userWorkService.incrementDownloadCount(workId);

            // 判断resultUrl类型
            if (resultUrl.startsWith("data:")) {
                // Base64编码的数据
                return handleBase64Download(work, resultUrl);
            } else if (resultUrl.startsWith("http://") || resultUrl.startsWith("https://")) {
                // 外部URL（如COS）
                if (download) {
                    // 直接下载模式：代理下载
                    return handleUrlDownload(work, resultUrl);
                } else {
                    // 重定向模式（默认）：重定向到COS URL
                    return ResponseEntity.status(HttpStatus.FOUND)
                            .header(HttpHeaders.LOCATION, resultUrl)
                            .build();
                }
            } else {
                logger.error("不支持的resultUrl格式: {}", resultUrl);
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "不支持的资源格式");
                return ResponseEntity.status(500).body(errorResponse);
            }

        } catch (RuntimeException e) {
            logger.error("下载作品文件失败: workId={}", workId, e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(400).body(errorResponse);
        } catch (Exception e) {
            logger.error("下载作品文件失败: workId={}", workId, e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "下载失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 处理Base64数据下载
     */
    private ResponseEntity<InputStreamResource> handleBase64Download(UserWork work, String dataUrl) {
        try {
            // 解析data URL格式：data:image/png;base64,xxxxx
            String[] parts = dataUrl.split(",", 2);
            if (parts.length != 2) {
                throw new RuntimeException("无效的Base64数据格式");
            }

            // 提取MIME类型
            String mimeType = "application/octet-stream";
            if (parts[0].contains(":") && parts[0].contains(";")) {
                mimeType = parts[0].substring(parts[0].indexOf(":") + 1, parts[0].indexOf(";"));
            }

            // 解码Base64数据
            byte[] fileBytes = Base64.getDecoder().decode(parts[1]);
            InputStream inputStream = new ByteArrayInputStream(fileBytes);

            // 生成文件名
            String filename = generateFilename(work, mimeType);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(mimeType));
            headers.setContentLength(fileBytes.length);
            headers.setContentDispositionFormData("attachment", 
                URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20"));

            logger.info("下载Base64作品: workId={}, filename={}, size={}KB", 
                work.getId(), filename, fileBytes.length / 1024);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(inputStream));

        } catch (Exception e) {
            logger.error("处理Base64下载失败: workId={}", work.getId(), e);
            throw new RuntimeException("处理下载数据失败：" + e.getMessage());
        }
    }

    /**
     * 处理URL下载（代理下载）
     */
    private ResponseEntity<InputStreamResource> handleUrlDownload(UserWork work, String fileUrl) {
        try {
            logger.info("开始代理下载: workId={}, url={}", work.getId(), fileUrl);

            // 打开连接
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(30000); // 30秒连接超时
            connection.setReadTimeout(300000);   // 5分钟读取超时

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException("下载失败，HTTP状态码：" + responseCode);
            }

            // 获取内容信息
            String contentType = connection.getContentType();
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            long contentLength = connection.getContentLengthLong();

            // 生成文件名
            String filename = generateFilename(work, contentType);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            if (contentLength > 0) {
                headers.setContentLength(contentLength);
            }
            headers.setContentDispositionFormData("attachment", 
                URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20"));

            logger.info("下载URL作品: workId={}, filename={}, contentType={}, size={}MB", 
                work.getId(), filename, contentType, contentLength / (1024 * 1024));

            // 返回文件流
            InputStream inputStream = connection.getInputStream();
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(new InputStreamResource(inputStream));

        } catch (IOException e) {
            logger.error("处理URL下载失败: workId={}, url={}", work.getId(), fileUrl, e);
            throw new RuntimeException("下载文件失败：" + e.getMessage());
        }
    }

    /**
     * 生成下载文件名
     */
    private String generateFilename(UserWork work, String mimeType) {
        // 使用作品标题作为文件名基础
        String basename = work.getTitle();
        if (basename == null || basename.isEmpty()) {
            basename = "work_" + work.getId();
        }

        // 清理文件名中的非法字符
        basename = basename.replaceAll("[\\\\/:*?\"<>|]", "_");

        // 根据MIME类型确定扩展名
        String extension = getExtensionFromMimeType(mimeType);

        // 添加工作类型信息
        String typePrefix = "";
        if (work.getWorkType() != null) {
            switch (work.getWorkType()) {
                case TEXT_TO_VIDEO:
                    typePrefix = "文生视频_";
                    break;
                case IMAGE_TO_VIDEO:
                    typePrefix = "图生视频_";
                    break;
                case STORYBOARD_VIDEO:
                    typePrefix = "分镜视频_";
                    break;
                case STORYBOARD_IMAGE:
                    typePrefix = "分镜图_";
                    break;
            }
        }

        return typePrefix + basename + extension;
    }

    /**
     * 根据MIME类型获取文件扩展名
     */
    private String getExtensionFromMimeType(String mimeType) {
        if (mimeType == null) {
            return ".bin";
        }

        // 视频类型
        if (mimeType.contains("video/mp4")) return ".mp4";
        if (mimeType.contains("video/webm")) return ".webm";
        if (mimeType.contains("video/avi")) return ".avi";
        if (mimeType.contains("video/quicktime")) return ".mov";

        // 图片类型
        if (mimeType.contains("image/png")) return ".png";
        if (mimeType.contains("image/jpeg") || mimeType.contains("image/jpg")) return ".jpg";
        if (mimeType.contains("image/gif")) return ".gif";
        if (mimeType.contains("image/webp")) return ".webp";

        // 默认
        if (mimeType.contains("video")) return ".mp4";
        if (mimeType.contains("image")) return ".png";

        return ".bin";
    }

    /**
     * 获取公开作品列表
     */
    @GetMapping("/public")
    public ResponseEntity<Map<String, Object>> getPublicWorks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String sort) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;
            
            Page<UserWork> works;
            
            if ("popular".equals(sort)) {
                works = userWorkService.getPopularWorks(page, size);
            } else if ("latest".equals(sort)) {
                works = userWorkService.getLatestWorks(page, size);
            } else if (type != null) {
                try {
                    CommonTaskType workType = CommonTaskType.valueOf(type.toUpperCase());
                    works = userWorkService.getPublicWorksByType(workType, page, size);
                } catch (IllegalArgumentException e) {
                    logger.warn("无效的作品类型: {}", type);
                    works = userWorkService.getPublicWorks(page, size);
                }
            } else {
                works = userWorkService.getPublicWorks(page, size);
            }

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取公开作品列表失败", e);
            response.put("success", false);
            response.put("message", "获取作品列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 搜索公开作品
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchPublicWorks(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (keyword == null || keyword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "搜索关键词不能为空");
                return ResponseEntity.status(400).body(response);
            }
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;

            Page<UserWork> works = userWorkService.searchPublicWorks(keyword.trim(), page, size);

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("keyword", keyword);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("搜索作品失败", e);
            response.put("success", false);
            response.put("message", "搜索作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 根据标签搜索作品
     */
    @GetMapping("/tag/{tag}")
    public ResponseEntity<Map<String, Object>> searchWorksByTag(
            @PathVariable String tag,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (tag == null || tag.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "标签不能为空");
                return ResponseEntity.status(400).body(response);
            }
            if (page < 0) page = 0;
            if (size <= 0 || size > 100) size = 10;

            Page<UserWork> works = userWorkService.searchPublicWorksByTag(tag.trim(), page, size);

            response.put("success", true);
            response.put("data", works.getContent());
            response.put("totalElements", works.getTotalElements());
            response.put("totalPages", works.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            response.put("tag", tag);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("根据标签搜索作品失败", e);
            response.put("success", false);
            response.put("message", "搜索作品失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            // 提取实际的token
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            // 验证token并获取用户名
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (ExpiredJwtException e) {
            // Token过期是常见情况，不打印堆栈
            logger.debug("Token已过期");
            return null;
        } catch (Exception e) {
            logger.warn("解析token失败: {}", e.getMessage());
            return null;
        }
    }
}
