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 com.baomidou.mybatisplus.core.metadata.IPage;
import shop.alien.entity.store.CommonRating;
import shop.alien.entity.store.vo.MyMergedReviewItemVo;
import shop.alien.store.annotation.TrackEvent;
import shop.alien.store.service.CommonCommentService;
import shop.alien.store.service.CommonRatingService;

/**
 * 评价表 前端控制器
 *
 * @author lyx
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"评价管理"})
@ApiSort(12)
@CrossOrigin
@RestController
@RequestMapping("/commonRating")
@RequiredArgsConstructor
public class CommonRatingController {

    private final CommonRatingService commonRatingService;
    private final CommonCommentService commonCommentService;

    @ApiOperation("分页查询评价列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "businessType", value = "业务类型：1-店铺", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "businessId", value = "业务关联ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "auditStatus", value = "审核状态：0-待审核 1-通过 2-驳回", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "searchScore", value = "搜索评分：0-全部,1-好评 2-中评 3-差评,4-有图", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "days", value = "查询时间, 多少天前", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "replyStatus", value = "回复状态(0:全部, 1:已回复, 2:未回复)", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "tagId", value = "标签id", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getList")
    public R getList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer businessType,
            @RequestParam(required = false) Long businessId,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(defaultValue = "0") Integer searchScore,
            @RequestParam(required = false) Integer days,
            @RequestParam(required = false) Integer replyStatus,
            @RequestParam(required = false) Integer tagId) {
        log.info("CommonRatingController.getList?pageNum={}&pageSize={}&businessType={}&businessId={}&userId={}&auditStatus={}&searchScore={}&days={}&replyStatus={}&tagId={}",
                pageNum, pageSize, businessType, businessId, userId, auditStatus, searchScore, days, replyStatus, tagId);
        return commonRatingService.getRatingList(pageNum, pageSize, businessType, businessId, userId, auditStatus, searchScore, days, replyStatus, tagId);
    }

    @ApiOperation("获取全部评价数量（好评，中评，差评）")
    @ApiImplicitParams({
           @ApiImplicitParam(name = "storeId", value = "店铺ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getRatingCount")
    public R getRatingCount(@RequestParam Integer businessId, @RequestParam Integer businessType) {
        log.info("CommonRatingController.getRatingCount?businessId={}&businessType={}", businessId, businessType);
        return R.data(commonRatingService.getRatingCount(businessId, businessType));
    }

//
//    @ApiOperation("根据ID获取评价详情")
//    @ApiImplicitParam(name = "id", value = "评价ID", dataType = "Long", paramType = "path", required = true)
//    @GetMapping("/getById/{id}")
//    public R<CommonRating> getById(@PathVariable Long id) {
//        log.info("CommonRatingController.getById?id={}", id);
//        return R.data(commonRatingService.getById(id));
//    }
//
    @TrackEvent(
            eventType = "RATING_ADD",
            eventCategory = "SERVICE",
            storeId = "#{#commonRating.businessId}",
            targetType = "STORE"
    )
    @ApiOperation(value = "新增评价", notes = "0:成功（包括审核通过和审核不通过但允许创建的情况）, 1:失败, 2:内容审核不通过（直接拒绝）。注意：小票审核不通过时，允许创建评论但审核状态设为不通过并记录原因；打卡仅要求在该店铺有未删除的打卡记录（不校验打卡内容是否审核通过）。若未在该店铺打卡且小票未通过（含未上传有效消费凭证），将推送「评价审核失败通知」并含店铺名、失败原因与参与指引")
    @PostMapping("/addRating")
    public R<Integer> add(@RequestBody CommonRating commonRating) {
        log.info("CommonRatingController.add?commonRating={}", commonRating);
        try {
            // 参数校验
            if (commonRating.getBusinessId() == null) {
                return R.fail("参数错误：businessId不能为空");
            }
            if (commonRating.getBusinessType() == null) {
                return R.fail("参数错误：businessType不能为空");
            }
            if (commonRating.getUserId() == null) {
                return R.fail("参数错误：userId不能为空");
            }
            
            Integer result = commonRatingService.saveCommonRating(commonRating);
            if (result == 0) {
                return R.data(result);
            } else if (result == 2) {
                return R.fail("评价内容包含敏感字符，审核不通过");
            } else {
                return R.fail("保存评价失败");
            }
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("新增评价异常", e);
            return R.fail("保存评价失败：" + e.getMessage());
        }
    }

    @ApiOperation("获取评价详情，和所有回复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "评价主键", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "当前用户ID", dataType = "Long", paramType = "query", required = true)
    })
    @GetMapping("/getRatingDetail")
    public R getCommentDetail(@RequestParam Integer ratingId, @RequestParam Long userId) {
        log.info("CommonRatingController.getRatingDetail?id={}&userId={}", ratingId, userId);
        if (ratingId == null) {
            return R.fail("参数[ratingId]不能为空");
        }
        if (userId == null) {
            return R.fail("参数[userId]不能为空");
        }
        try {
            return R.data(commonRatingService.getRatingDetail(ratingId, userId));
        } catch (IllegalArgumentException e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 删除评价（并重新统计店铺评分）
     *
     * @param ratingId 评价id
     * @return 0:成功, 1:失败
     */
    @ApiOperation(value = "删除评价", notes = "0:成功, 1:失败")
    @GetMapping("/deleteRating")
    public R deleteRating(@RequestParam Long ratingId) {
        log.info("删除评价，ratingId={}", ratingId);

        // 先获取评价信息（用于后续更新评分）
        CommonRating rating = commonRatingService.getById(ratingId);
        if (rating == null) {
            return R.fail("评价不存在");
        }

        // 删除评价
        boolean b = commonRatingService.removeById(ratingId);

        if (b) {
            // 删除成功后，重新统计店铺评分（仅店铺评价类型）
            if (rating.getBusinessType() != null && rating.getBusinessType() == 1) {
                try {
                    commonRatingService.updateStoreScoreAfterDelete(rating.getBusinessId());
                    log.info("更新店铺评分成功，businessId={}", rating.getBusinessId());
                } catch (Exception e) {
                    log.error("更新店铺评分失败，businessId={}，error={}", rating.getBusinessId(), e.getMessage());
                    // 评分更新失败不影响删除结果
                }
            }
            return R.success("删除评价成功");
        }
        return R.fail("删除评价失败");
    }

    // 查询我自己的评价
    @ApiOperation("查询我的评价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "businessType", value = "业务类型", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "auditStatus", value = "审核状态", dataType = "Integer", paramType = "query", required = true)})
    @GetMapping("/getMyRatingList")
    public R getMyRatingList(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam Integer businessType,
                             @RequestParam Long userId,
                             @RequestParam(required = false) Integer auditStatus) {
        log.info("CommonRatingController.getMyRatingList?pageNum={}&pageSize={}&businessType={}&userId={}&auditStatus={}", pageNum, pageSize, businessType, userId, auditStatus);
        return commonRatingService.getMyRatingList(pageNum, pageSize, businessType, userId, auditStatus);
    }

    @ApiOperation(value = "融合查询我的评价列表",
            notes = "【请求】GET /commonRating/getMyMergedRatingList\n\n"
                    + "【功能】合并「门店评价 common_rating」与「律师订单评价」，按发布时间倒序（新在前）；服务端合并后再分页。\n\n"
                    + "【查询参数】\n"
                    + "- pageNum：页码，默认 1\n"
                    + "- pageSize：每页条数，默认 10\n"
                    + "- businessType：门店侧 business_type，不传默认 1（门店评价），语义同 getMyRatingList\n"
                    + "- userId：必填，被查询的用户 ID（Long）\n"
                    + "- auditStatus：可选，仅过滤门店评价侧；律师订单评价不受此参数影响\n"
                    + "- currentUserId：可选，传入时用于律师评价侧「是否已点赞」等当前用户态\n\n"
                    + "【响应】外层统一 R；success=true 时 data 为分页对象（IPage），元素类型 MyMergedReviewItemVo。\n"
                    + "- data.records：列表项，itemType=STORE 为门店评价，LAWYER 为律师订单评价，字段见模型说明\n"
                    + "- data.total：门店评价总数 + 律师评价总数（合并前各自 total 之和）\n"
                    + "- data.current、data.size、data.pages：标准分页字段\n\n"
                    + "【错误】userId 为空时返回失败（msg 提示）。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码，默认 1", dataType = "Integer", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认 10", dataType = "Integer", paramType = "query", defaultValue = "10"),
            @ApiImplicitParam(name = "businessType", value = "门店侧业务类型，不传默认 1-门店评价", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户 ID（必填）", dataType = "Long", paramType = "query", required = true, example = "10001"),
            @ApiImplicitParam(name = "auditStatus", value = "门店评价审核状态筛选，可选；律师侧不过滤", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "currentUserId", value = "当前登录用户 ID，可选；律师评价用于点赞态等", dataType = "Integer", paramType = "query")
    })
    @GetMapping("/getMyMergedRatingList")
    public R<IPage<MyMergedReviewItemVo>> getMyMergedRatingList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer businessType,
            @RequestParam Long userId,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false) Integer currentUserId) {
        log.info("CommonRatingController.getMyMergedRatingList?pageNum={}&pageSize={}&businessType={}&userId={}&auditStatus={}&currentUserId={}",
                pageNum, pageSize, businessType, userId, auditStatus, currentUserId);
        return commonRatingService.getMyMergedRatingList(pageNum, pageSize, businessType, userId, auditStatus, currentUserId);
    }

}
