package shop.alien.lawyer.controller;

import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.result.R;
import shop.alien.entity.store.ReviewComment;
import shop.alien.entity.store.dto.LawyerReplyDto;
import shop.alien.entity.store.dto.ReviewCommentRequestDto;
import shop.alien.entity.store.dto.ReviewReplyDto;
import shop.alien.entity.store.vo.ReviewCommentVo;
import shop.alien.lawyer.service.ReviewCommentService;

import java.util.List;

/**
 * 评价评论 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"律师平台-评价评论"})
@ApiSort(16)
@CrossOrigin
@RestController
@RequestMapping("/lawyer/reviewComment")
@RequiredArgsConstructor
public class ReviewCommentController {

    private final ReviewCommentService reviewCommentService;

    @ApiOperation("创建评论（用户对评价的评论，支持普通用户和律师）")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reviewId", value = "评价ID", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "sendUserId", value = "发送用户ID（评论用户ID，如果传入userId则自动映射到sendUserId）", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID（登录用户ID，会自动映射到sendUserId，如果sendUserId已存在则优先使用sendUserId）", dataType = "int", paramType = "body", required = false),
            @ApiImplicitParam(name = "receiveUserId", value = "接收用户ID（可选，不填时默认为评价的创建者）", dataType = "int", paramType = "body", required = false),
            @ApiImplicitParam(name = "sendUserType", value = "发送用户类型：1-普通用户，2-律师（必填）", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "receiveUserType", value = "接收用户类型：1-普通用户，2-律师（必填）", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "commentContent", value = "评论内容", dataType = "String", paramType = "body", required = true)
    })
    @PostMapping("/create")
    public R<ReviewComment> createComment(@RequestBody ReviewComment comment) {
        log.info("ReviewCommentController.createComment?comment={}", comment);
        
        // 参数校验：优先使用sendUserId，如果不存在则使用userId
        if (comment.getSendUserId() == null) {
            if (comment.getUserId() == null) {
                return R.fail("用户ID不能为空");
            }
            // 将userId映射到sendUserId
            comment.setSendUserId(comment.getUserId());
        }
        
        // 校验用户类型字段：必须传入
        if (comment.getSendUserType() == null) {
            return R.fail("发送用户类型不能为空");
        }
        if (comment.getReceiveUserType() == null) {
            return R.fail("接收用户类型不能为空");
        }
        
        return reviewCommentService.createComment(comment);
    }

    @ApiOperation("根据评价ID查询评论列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reviewId", value = "评价ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "currentUserId", value = "当前用户ID（用于判断是否已点赞）", dataType = "int", paramType = "query")
    })
    @GetMapping("/list/reviewId")
    public R<List<ReviewCommentVo>> getCommentListByReviewId(
            @RequestParam Integer reviewId,
            @RequestParam(required = false) Integer currentUserId) {
        log.info("ReviewCommentController.getCommentListByReviewId?reviewId={}, currentUserId={}", reviewId, currentUserId);
        return reviewCommentService.getCommentListByReviewId(reviewId, currentUserId);
    }

    @ApiOperation("点赞评论")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/like")
    public R<Boolean> likeComment(@RequestBody ReviewComment reviewComment) {
        Integer commentId = reviewComment.getId();
        Integer userId = reviewComment.getUserId();
        log.info("ReviewCommentController.likeComment?commentId={}, userId={}", commentId, userId);
        if (userId == null) {
            return R.fail("用户未登录");
        }
        if (commentId == null) {
            return R.fail("评论ID不能为空");
        }
        ReviewCommentRequestDto requestDto = new ReviewCommentRequestDto();
        requestDto.setCommentId(commentId);
        requestDto.setUserId(userId);
        return reviewCommentService.likeComment(requestDto);
    }

    @ApiOperation("取消点赞评论")
    @ApiOperationSupport(order = 5)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/cancelLike")
    public R<Boolean> cancelLikeComment(@RequestBody ReviewComment reviewComment) {
        Integer commentId = reviewComment.getId();
        Integer userId = reviewComment.getUserId();
        log.info("ReviewCommentController.cancelLikeComment?commentId={}, userId={}", commentId, userId);
        if (userId == null) {
            return R.fail("用户未登录");
        }
        if (commentId == null) {
            return R.fail("评论ID不能为空");
        }
        ReviewCommentRequestDto requestDto = new ReviewCommentRequestDto();
        requestDto.setCommentId(commentId);
        requestDto.setUserId(userId);
        return reviewCommentService.cancelLikeComment(requestDto);
    }

    @ApiOperation("创建回复（用户对评论的回复）")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "首评ID", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID（发送用户ID）", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "replyToUserId", value = "被回复用户ID（可选，不填时默认为首评的发送用户）", dataType = "int", paramType = "body", required = false),
            @ApiImplicitParam(name = "sendUserType", value = "发送用户类型：1-普通用户，2-律师（必填）", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "receiveUserType", value = "接收用户类型：1-普通用户，2-律师（必填）", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "replyContent", value = "回复内容", dataType = "String", paramType = "body", required = true)
    })
    @PostMapping("/reply/create")
    public R<ReviewComment> createReply(@RequestBody ReviewReplyDto replyDto) {
        log.info("ReviewCommentController.createReply?replyDto={}", replyDto);
        
        if (replyDto.getUserId() == null) {
            return R.fail("用户ID不能为空");
        }
        
        // 校验用户类型字段：必须传入
        if (replyDto.getSendUserType() == null) {
            return R.fail("发送用户类型不能为空");
        }
        if (replyDto.getReceiveUserType() == null) {
            return R.fail("接收用户类型不能为空");
        }
        
        return reviewCommentService.createReply(replyDto);
    }

    @ApiOperation("根据首评ID查询回复列表")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "headId", value = "首评ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "currentUserId", value = "当前用户ID（用于判断是否已点赞）", dataType = "int", paramType = "query")
    })
    @GetMapping("/reply/list/headId")
    public R<List<ReviewCommentVo>> getReplyListByHeadId(
            @RequestParam Integer headId,
            @RequestParam(required = false) Integer currentUserId) {
        log.info("ReviewCommentController.getReplyListByHeadId?headId={}, currentUserId={}", headId, currentUserId);
        return reviewCommentService.getReplyListByHeadId(headId, currentUserId);
    }

    @ApiOperation("删除回复")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "replyId", value = "回复ID", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "int", paramType = "query", required = true)
    })
    @PostMapping("/reply/delete")
    public R<Boolean> deleteReply(
            @RequestParam Integer replyId,
            @RequestParam Integer userId) {
        log.info("ReviewCommentController.deleteReply?replyId={}, userId={}", replyId, userId);
        if (userId == null) {
            return R.fail("用户未登录");
        }
        return reviewCommentService.deleteReply(replyId, userId);
    }

    @ApiOperation(value = "删除评论（根据ID）", notes = "根据评论ID删除评论，userId有值时只能删除自己发布的评论，userId为空时允许删除任何评论（管理员删除）")
    @ApiOperationSupport(order = 11)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "评论ID", dataType = "int", paramType = "body", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID（可选，有值时只能删除自己的评论，为空时允许删除任何评论）", dataType = "int", paramType = "body", required = false)
    })
    @PostMapping("/deleteReviewComment")
    public R<Boolean> deleteReviewComment(@RequestBody ReviewComment reviewComment) {
        log.info("ReviewCommentController.deleteReviewComment?reviewComment={}", reviewComment);
        return reviewCommentService.deleteReviewComment(reviewComment);
    }

    @Deprecated
    @ApiOperation(value = "律师回复（律师对用户的评价或评论的回复）", notes = "【已废弃】请使用 createComment（回复评价）或 createReply（回复评论）接口，通过 sendUserType=2 标识律师身份，系统会自动进行权限校验")
    @ApiOperationSupport(order = 12)
    @PostMapping("/lawyer/reply")
    public R<ReviewComment> lawyerReply(@RequestBody LawyerReplyDto replyDto) {
        log.warn("【废弃接口】ReviewCommentController.lawyerReply 已废弃，请使用 createComment 或 createReply 接口");
        log.info("ReviewCommentController.lawyerReply?replyDto={}", replyDto);
        if (replyDto.getLawyerUserId() == null) {
            return R.fail("律师用户ID不能为空");
        }
        return reviewCommentService.lawyerReply(replyDto);
    }

}

