package shop.alien.store.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.StoreStaffComment;
import shop.alien.entity.store.dto.StoreStaffCommentRequestDto;
import shop.alien.entity.store.dto.StoreStaffReplyDto;
import shop.alien.entity.store.vo.StoreStaffCommentVo;
import shop.alien.store.service.StoreStaffCommentService;

import java.util.List;

/**
 * 员工评论 前端控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"员工评论"})
@ApiSort(21)
@CrossOrigin
@RestController
@RequestMapping("/store/staffComment")
@RequiredArgsConstructor
public class StoreStaffCommentController {

    private final StoreStaffCommentService storeStaffCommentService;

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

    @ApiOperation("根据评价ID查询评论列表")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reviewId", value = "评价ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "currentUserId", value = "当前用户ID（用于判断是否已点赞）", dataTypeClass = Integer.class, paramType = "query", required = false)
    })
    @GetMapping("/list/reviewId")
    public R<List<StoreStaffCommentVo>> getCommentListByReviewId(
            @RequestParam Integer reviewId,
            @RequestParam(required = false) Integer currentUserId) {
        log.info("根据评价ID查询评论列表, reviewId={}, currentUserId={}", reviewId, currentUserId);
        if (reviewId == null) {
            return R.fail("评价ID不能为空");
        }
        return storeStaffCommentService.getCommentListByReviewId(reviewId, currentUserId);
    }

    @ApiOperation("点赞评论")
    @ApiOperationSupport(order = 3)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping("/like")
    public R<Boolean> likeComment(@RequestParam Integer commentId,
                                   @RequestParam Integer userId) {
        log.info("点赞评论, commentId={}, userId={}", commentId, userId);
        if (commentId == null) {
            return R.fail("评论ID不能为空");
        }
        if (userId == null) {
            return R.fail("用户未登录");
        }
        StoreStaffCommentRequestDto requestDto = new StoreStaffCommentRequestDto();
        requestDto.setCommentId(commentId);
        requestDto.setUserId(userId);
        return storeStaffCommentService.likeComment(requestDto);
    }

    @ApiOperation("取消点赞评论")
    @ApiOperationSupport(order = 4)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commentId", value = "评论ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping("/cancelLike")
    public R<Boolean> cancelLikeComment(@RequestParam Integer commentId,
                                         @RequestParam Integer userId) {
        log.info("取消点赞评论, commentId={}, userId={}", commentId, userId);
        if (commentId == null) {
            return R.fail("评论ID不能为空");
        }
        if (userId == null) {
            return R.fail("用户未登录");
        }
        StoreStaffCommentRequestDto requestDto = new StoreStaffCommentRequestDto();
        requestDto.setCommentId(commentId);
        requestDto.setUserId(userId);
        return storeStaffCommentService.cancelLikeComment(requestDto);
    }

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

    @ApiOperation("根据首评ID查询回复列表")
    @ApiOperationSupport(order = 6)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "headId", value = "首评ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "currentUserId", value = "当前用户ID（用于判断是否已点赞）", dataTypeClass = Integer.class, paramType = "query", required = false)
    })
    @GetMapping("/reply/list/headId")
    public R<List<StoreStaffCommentVo>> getReplyListByHeadId(
            @RequestParam Integer headId,
            @RequestParam(required = false) Integer currentUserId) {
        log.info("根据首评ID查询回复列表, headId={}, currentUserId={}", headId, currentUserId);
        if (headId == null) {
            return R.fail("首评ID不能为空");
        }
        return storeStaffCommentService.getReplyListByHeadId(headId, currentUserId);
    }

    @ApiOperation("删除回复")
    @ApiOperationSupport(order = 7)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "replyId", value = "回复ID", dataTypeClass = Integer.class, paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataTypeClass = Integer.class, paramType = "query", required = true)
    })
    @PostMapping("/reply/delete")
    public R<Boolean> deleteReply(@RequestParam Integer replyId,
                                   @RequestParam Integer userId) {
        log.info("删除回复, replyId={}, userId={}", replyId, userId);
        if (replyId == null) {
            return R.fail("回复ID不能为空");
        }
        if (userId == null) {
            return R.fail("用户未登录");
        }
        return storeStaffCommentService.deleteReply(replyId, userId);
    }

    @ApiOperation(value = "删除评论（根据ID）", notes = "根据评论ID删除评论，userId有值时只能删除自己发布的评论，userId为空时允许删除任何评论（管理员删除）")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "评论ID", dataTypeClass = Integer.class, paramType = "body", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID（可选，有值时只能删除自己的评论，为空时允许删除任何评论）", dataTypeClass = Integer.class, paramType = "body", required = false)
    })
    @PostMapping("/deleteReviewComment")
    public R<Boolean> deleteReviewComment(@RequestBody StoreStaffComment storeStaffComment) {
        log.info("删除评论, storeStaffComment={}", storeStaffComment);
        if (storeStaffComment == null || storeStaffComment.getId() == null) {
            return R.fail("评论ID不能为空");
        }
        return storeStaffCommentService.deleteReviewComment(storeStaffComment);
    }
}
