package com.lesingle.modules.biz.review.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.common.enums.ErrorCode;
import com.lesingle.common.exception.BusinessException;
import com.lesingle.modules.biz.review.dto.CreatePresetCommentDto;
import com.lesingle.modules.biz.review.dto.PresetCommentVo;
import com.lesingle.modules.biz.review.entity.BizPresetComment;
import com.lesingle.modules.biz.review.mapper.PresetCommentMapper;
import com.lesingle.modules.biz.review.service.IPresetCommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PresetCommentServiceImpl extends ServiceImpl<PresetCommentMapper, BizPresetComment> implements IPresetCommentService {

    @Override
    public BizPresetComment createComment(CreatePresetCommentDto dto, Long judgeId) {
        log.info("创建预设评语，评委ID：{}，活动ID：{}", judgeId, dto.getContestId());

        BizPresetComment entity = new BizPresetComment();
        entity.setContestId(dto.getContestId());
        entity.setJudgeId(judgeId);
        entity.setContent(dto.getContent());
        entity.setScore(dto.getScore());
        entity.setSortOrder(dto.getSortOrder() != null ? dto.getSortOrder() : 0);
        entity.setUseCount(0);

        save(entity);
        log.info("预设评语创建成功，ID：{}", entity.getId());
        return entity;
    }

    @Override
    public List<PresetCommentVo> findAll(Long judgeId) {
        log.info("查询预设评语列表（当前评委全部），评委ID：{}", judgeId);

        LambdaQueryWrapper<BizPresetComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizPresetComment::getValidState, 1);
        wrapper.eq(BizPresetComment::getJudgeId, judgeId);
        wrapper.orderByAsc(BizPresetComment::getSortOrder);
        wrapper.orderByDesc(BizPresetComment::getUseCount);

        List<BizPresetComment> rows = list(wrapper);
        return rows.stream().map(PresetCommentVo::fromEntity).collect(Collectors.toList());
    }

    @Override
    public PresetCommentVo findDetail(Long id, Long judgeId) {
        log.info("查询预设评语详情，ID：{}，评委ID：{}", id, judgeId);

        BizPresetComment entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "预设评语不存在");
        }
        if (!entity.getJudgeId().equals(judgeId)) {
            throw BusinessException.of(ErrorCode.FORBIDDEN, "无权查看此评语");
        }
        return PresetCommentVo.fromEntity(entity);
    }

    @Override
    public BizPresetComment updateComment(Long id, CreatePresetCommentDto dto, Long judgeId) {
        log.info("更新预设评语，ID：{}，评委ID：{}", id, judgeId);

        BizPresetComment entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "预设评语不存在");
        }
        if (!entity.getJudgeId().equals(judgeId)) {
            throw BusinessException.of(ErrorCode.FORBIDDEN, "无权修改此评语");
        }

        if (dto.getContent() != null) {
            entity.setContent(dto.getContent());
        }
        if (dto.getScore() != null) {
            entity.setScore(dto.getScore());
        }
        if (dto.getSortOrder() != null) {
            entity.setSortOrder(dto.getSortOrder());
        }
        if (dto.getContestId() != null) {
            entity.setContestId(dto.getContestId());
        }

        updateById(entity);
        log.info("预设评语更新成功，ID：{}", id);
        return entity;
    }

    @Override
    public void removeComment(Long id, Long judgeId) {
        log.info("删除预设评语，ID：{}，评委ID：{}", id, judgeId);

        BizPresetComment entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "预设评语不存在");
        }
        if (!entity.getJudgeId().equals(judgeId)) {
            throw BusinessException.of(ErrorCode.FORBIDDEN, "无权删除此评语");
        }

        removeById(id);
        log.info("预设评语删除成功，ID：{}", id);
    }

    @Override
    public void batchDelete(List<Long> ids, Long judgeId) {
        log.info("批量删除预设评语，数量：{}，评委ID：{}", ids.size(), judgeId);

        LambdaQueryWrapper<BizPresetComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(BizPresetComment::getId, ids);
        wrapper.eq(BizPresetComment::getJudgeId, judgeId);

        remove(wrapper);
        log.info("批量删除预设评语完成");
    }

    @Override
    public void incrementUseCount(Long id, Long judgeId) {
        log.info("增加预设评语使用次数，ID：{}，评委ID：{}", id, judgeId);

        BizPresetComment entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "预设评语不存在");
        }
        if (!entity.getJudgeId().equals(judgeId)) {
            throw BusinessException.of(ErrorCode.FORBIDDEN, "无权操作此评语");
        }

        LambdaUpdateWrapper<BizPresetComment> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BizPresetComment::getId, id);
        updateWrapper.setSql("use_count = use_count + 1");
        update(updateWrapper);
    }

}
