package com.zhentao.controller;

import com.zhentao.common.PageResult;
import com.zhentao.common.Result;
import com.zhentao.dto.DynamicQueryDTO;
import com.zhentao.dto.PublishDynamicDTO;
import com.zhentao.service.*;
import com.zhentao.entity.DynamicComments;
import org.springframework.web.bind.annotation.RequestBody;
import com.zhentao.dto.CommentCreateDTO;
import com.zhentao.dto.ReportCreateDTO;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import com.zhentao.vo.DynamicVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户动态控制器
 */
@RestController
@RequestMapping("/api/dynamic")
@Validated
public class DynamicController {

    @Autowired
    private UserDynamicsService userDynamicsService;
    @Autowired
    private InteractionService interactionService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private PublishService publishService;
    @Autowired
    private com.zhentao.service.MediaUploadService mediaUploadService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private BrowseHistoryService browseHistoryService;

    /**
     * 分页查询动态列表
     * @param queryDTO 查询条件
     * @return 动态列表
     */
    @GetMapping("/list")
    public Result<PageResult<DynamicVO>> getDynamicList(@Valid DynamicQueryDTO queryDTO) {
        try {
            PageResult<DynamicVO> result = userDynamicsService.getDynamicList(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询动态列表失败：" + e.getMessage());
        }
    }

    /**
     * 管理端：取消封禁（恢复正常）
     */
    @PostMapping("/admin/unban")
    public Result<String> adminUnban(@RequestParam Integer dynamicId,
                                     @RequestParam String reason) {
        try {
            if (reason == null || reason.trim().isEmpty()) {
                return Result.error("处理原因不能为空");
            }
            boolean ok = userDynamicsService.adminModerate(dynamicId, 1, reason);
            return ok ? Result.success("已恢复正常") : Result.error("操作失败");
        } catch (Exception e) {
            return Result.error("操作失败：" + e.getMessage());
        }
    }

    /**
     * 管理端：封禁/删除动态
     * action: 2=封禁 3=删除，reason为必填
     */
    @PostMapping("/admin/moderate")
    public Result<String> adminModerate(@RequestParam Integer dynamicId,
                                        @RequestParam Integer action,
                                        @RequestParam String reason) {
        try {
            if (reason == null || reason.trim().isEmpty()) {
                return Result.error("处理原因不能为空");
            }
            boolean ok = userDynamicsService.adminModerate(dynamicId, action, reason);
            return ok ? Result.success("处理成功") : Result.error("处理失败");
        } catch (Exception e) {
            return Result.error("处理失败：" + e.getMessage());
        }
    }

    /**
     * 查询动态详情
     * @param dynamicId 动态ID
     * @param userId 当前用户ID（可选）
     * @return 动态详情
     */
    @GetMapping("/detail/{dynamicId}")
    public Result<DynamicVO> getDynamicDetail(
            @PathVariable Integer dynamicId,
            @RequestParam(required = false) Integer userId,
            javax.servlet.http.HttpServletRequest request) {
        try {
            DynamicVO dynamic = userDynamicsService.getDynamicDetail(dynamicId, userId);
            if (dynamic == null) {
                return Result.error(404, "动态不存在");
            }
            
            // 添加浏览记录（如果有用户ID）
            if (userId != null) {
                // 获取IP地址
                String ip = request.getHeader("X-Forwarded-For");
                if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                } else {
                    // 取第一个IP地址
                    ip = ip.split(",")[0].trim();
                }
                
                // 获取设备信息
                String deviceInfo = request.getHeader("User-Agent");
                
                // 异步添加浏览记录，不影响主流程
                String finalIp = ip;
                new Thread(() -> {
                    try {
                        browseHistoryService.addBrowseHistory(userId, dynamicId, finalIp, deviceInfo);
                    } catch (Exception e) {
                        // 忽略异常，不影响主流程
                        e.printStackTrace();
                    }
                }).start();
            }
            
            return Result.success(dynamic);
        } catch (Exception e) {
            return Result.error("查询动态详情失败：" + e.getMessage());
        }
    }

    /**
     * 查询某个用户的动态列表
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param currentUserId 当前登录用户ID（可选）
     * @return 动态列表
     */
    @GetMapping("/user/{userId}")
    public Result<PageResult<DynamicVO>> getUserDynamics(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer currentUserId) {
        try {
            DynamicQueryDTO queryDTO = new DynamicQueryDTO();
            queryDTO.setTargetUserId(userId);
            queryDTO.setPageNum(pageNum);
            queryDTO.setPageSize(pageSize);
            queryDTO.setCurrentUserId(currentUserId);
            
            PageResult<DynamicVO> result = userDynamicsService.getUserDynamics(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询用户动态失败：" + e.getMessage());
        }
    }

    /**
     * 获取推荐动态列表（审核通过且公开）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param userId 当前用户ID（可选）
     * @return 动态列表
     */
    @GetMapping("/recommend")
    public Result<PageResult<DynamicVO>> getRecommendDynamics(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer userId) {
        try {
            DynamicQueryDTO queryDTO = new DynamicQueryDTO();
            queryDTO.setPageNum(pageNum);
            queryDTO.setPageSize(pageSize);
            queryDTO.setCurrentUserId(userId);
            queryDTO.setAuditStatus(1); // 审核通过
            queryDTO.setVisibility(1);  // 公开
            
            PageResult<DynamicVO> result = userDynamicsService.getDynamicList(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询推荐动态失败：" + e.getMessage());
        }
    }

    // ====== 互动接口 ======
    /**
     * 点赞
     */
    @PostMapping("/like")
    public Result<String> like(@RequestParam Integer dynamicId,
                               @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.like(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    // ====== 发布动态 ======
    @PostMapping("/publish")
    public Result<Integer> publish(@RequestBody PublishDynamicDTO dto) {
        try {
            if (dto.getUserId() == null) dto.setUserId(1);
            if (dto.getMediaType() == null) dto.setMediaType(1);
            if (dto.getVisibility() == null) dto.setVisibility(1);
            Integer dynamicId = publishService.publish(dto);
            return Result.success(dynamicId);
        } catch (Exception e) {
            return Result.error("发布动态失败：" + e.getMessage());
        }
    }

    /**
     * 发布动态媒体上传（图片/视频）
     */
    @PostMapping(value = "/publish/upload", consumes = {"multipart/form-data"})
    public Result<String> uploadDynamicMedia(@RequestParam("file") MultipartFile file) {
        try {
            String url = mediaUploadService.uploadDynamicMedia(file);
            return Result.success(url);
        } catch (Exception e) {
            return Result.error("媒体上传失败：" + e.getMessage());
        }
    }

    /**
     * 发布动态批量媒体上传（多张图片）
     */
    @PostMapping(value = "/publish/upload/batch", consumes = {"multipart/form-data"})
    public Result<java.util.List<String>> uploadDynamicMediaBatch(@RequestParam("files") MultipartFile[] files) {
        try {
            java.util.List<String> urls = mediaUploadService.uploadDynamicMediaBatch(files);
            return Result.success(urls);
        } catch (Exception e) {
            return Result.error("批量媒体上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件上传大小限制异常处理
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result<String> handleMaxUploadSizeExceeded(MaxUploadSizeExceededException e) {
        return Result.error("文件大小超过限制，单个文件最大10MB，请压缩后重试");
    }

    // ====== 评论接口 ======
    @PostMapping("/comment")
    public Result<String> addComment(@RequestBody CommentCreateDTO dto) {
        try {
            String[] imageUrls = null;
            if (dto.getImageList() != null && !dto.getImageList().isEmpty()) {
                imageUrls = dto.getImageList().toArray(new String[0]);
            } else if (dto.getImages() != null && !dto.getImages().trim().isEmpty()) {
                imageUrls = dto.getImages().split(",");
            }
            Integer uid = dto.getUserId() != null ? dto.getUserId() : 1;
            Integer parentId = dto.getParentCommentId() != null ? dto.getParentCommentId() : 0;
            commentService.addComment(uid, dto.getDynamicId(), dto.getContent(), imageUrls, parentId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("发表评论失败：" + e.getMessage());
        }
    }

    @GetMapping("/comment/list/{dynamicId}")
    public Result<PageResult<DynamicComments>> listComments(@PathVariable Integer dynamicId,
                                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            return Result.success(commentService.listComments(dynamicId, pageNum, pageSize));
        } catch (Exception e) {
            return Result.error("查询评论失败：" + e.getMessage());
        }
    }

    @PostMapping("/comment/like")
    public Result<String> likeComment(@RequestParam Integer commentId,
                                      @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            commentService.likeComment(userId, commentId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("评论点赞失败：" + e.getMessage());
        }
    }

    

    @DeleteMapping("/comment/like/{commentId}")
    public Result<String> unlikeComment(@PathVariable Integer commentId,
                                        @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            commentService.unlikeComment(userId, commentId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("取消评论点赞失败：" + e.getMessage());
        }
    }

    /**
     * 取消点赞
     */
    @DeleteMapping("/like/{dynamicId}")
    public Result<String> unlike(@PathVariable Integer dynamicId,
                                 @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.unlike(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("取消点赞失败：" + e.getMessage());
        }
    }

    /**
     * 收藏
     */
    @PostMapping("/favorite")
    public Result<String> favorite(@RequestParam Integer dynamicId,
                                   @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.favorite(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("收藏失败：" + e.getMessage());
        }
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/favorite/{dynamicId}")
    public Result<String> unfavorite(@PathVariable Integer dynamicId,
                                     @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.unfavorite(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("取消收藏失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户收藏列表
     */
    @GetMapping("/favorites")
    public Result<PageResult<DynamicVO>> getFavoritesList(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<DynamicVO> result = interactionService.listFavorites(userId, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取收藏列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户点赞列表
     */
    @GetMapping("/likes")
    public Result<PageResult<DynamicVO>> getLikedDynamicsList(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<DynamicVO> result = interactionService.listLikedDynamics(userId, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取点赞列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户浏览记录列表
     */
    @GetMapping("/browse-history")
    public Result<PageResult<DynamicVO>> getBrowseHistoryList(
            @RequestParam Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            PageResult<DynamicVO> result = browseHistoryService.getBrowseHistoryList(userId, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取浏览记录失败：" + e.getMessage());
        }
    }
    
    /**
     * 清空用户浏览记录
     */
    @DeleteMapping("/browse-history")
    public Result<String> clearBrowseHistory(@RequestParam Integer userId) {
        try {
            browseHistoryService.clearBrowseHistory(userId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("清空浏览记录失败：" + e.getMessage());
        }
    }

    // ====== 举报接口 ======
    /**
     * 提交举报
     * @param dto 举报信息
     * @return 提交结果
     */
    @PostMapping("/report")
    public Result<String> submitReport(@RequestBody @Valid ReportCreateDTO dto) {
        try {
            boolean success = reportService.submitReport(dto);
            if (success) {
                return Result.success("举报已提交，我们将尽快处理", "success");
            } else {
                return Result.error("举报提交失败，请重试");
            }
        } catch (Exception e) {
            return Result.error("举报提交失败：" + e.getMessage());
        }
    }
    
}


