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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.competition.common.enums.ErrorCode;
import com.competition.common.exception.BusinessException;
import com.competition.common.result.PageResult;
import com.competition.modules.biz.review.dto.CreateReviewRuleDto;
import com.competition.modules.biz.review.entity.BizContestReviewRule;
import com.competition.modules.biz.review.mapper.ContestReviewRuleMapper;
import com.competition.modules.biz.review.service.IContestReviewRuleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ContestReviewRuleServiceImpl extends ServiceImpl<ContestReviewRuleMapper, BizContestReviewRule> implements IContestReviewRuleService {

    private final ContestReviewRuleMapper contestReviewRuleMapper;

    @Override
    public BizContestReviewRule createRule(CreateReviewRuleDto dto, Long tenantId) {
        log.info("创建评审规则，名称：{}，租户：{}", dto.getRuleName(), tenantId);

        BizContestReviewRule entity = new BizContestReviewRule();
        entity.setTenantId(tenantId);
        entity.setRuleName(dto.getRuleName());
        entity.setRuleDescription(dto.getRuleDescription());
        entity.setJudgeCount(dto.getJudgeCount());
        entity.setDimensions(dto.getDimensions());
        entity.setCalculationRule(dto.getCalculationRule());

        save(entity);
        log.info("评审规则创建成功，ID：{}", entity.getId());
        return entity;
    }

    @Override
    public PageResult<Map<String, Object>> findAll(Long page, Long pageSize, String ruleName, Long tenantId) {
        log.info("查询评审规则列表，页码：{}，每页：{}", page, pageSize);

        LambdaQueryWrapper<BizContestReviewRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizContestReviewRule::getValidState, 1);

        if (tenantId != null) {
            wrapper.eq(BizContestReviewRule::getTenantId, tenantId);
        }
        if (StringUtils.hasText(ruleName)) {
            wrapper.like(BizContestReviewRule::getRuleName, ruleName);
        }

        wrapper.orderByDesc(BizContestReviewRule::getCreateTime);

        Page<BizContestReviewRule> pageObj = new Page<>(page, pageSize);
        Page<BizContestReviewRule> result = contestReviewRuleMapper.selectPage(pageObj, wrapper);

        List<Map<String, Object>> voList = result.getRecords().stream()
                .map(this::entityToMap)
                .collect(Collectors.toList());

        return PageResult.from(result, voList);
    }

    @Override
    public List<Map<String, Object>> findAllForSelect(Long tenantId) {
        log.info("查询评审规则下拉列表，租户：{}", tenantId);

        LambdaQueryWrapper<BizContestReviewRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizContestReviewRule::getValidState, 1);
        if (tenantId != null) {
            wrapper.eq(BizContestReviewRule::getTenantId, tenantId);
        }
        wrapper.orderByDesc(BizContestReviewRule::getCreateTime);

        List<BizContestReviewRule> list = contestReviewRuleMapper.selectList(wrapper);
        return list.stream().map(this::entityToMap).collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> findDetail(Long id) {
        log.info("查询评审规则详情，ID：{}", id);

        BizContestReviewRule entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "评审规则不存在");
        }
        return entityToMap(entity);
    }

    @Override
    public BizContestReviewRule updateRule(Long id, CreateReviewRuleDto dto) {
        log.info("更新评审规则，ID：{}", id);

        BizContestReviewRule entity = getById(id);
        if (entity == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "评审规则不存在");
        }

        if (StringUtils.hasText(dto.getRuleName())) {
            entity.setRuleName(dto.getRuleName());
        }
        if (dto.getRuleDescription() != null) {
            entity.setRuleDescription(dto.getRuleDescription());
        }
        if (dto.getJudgeCount() != null) {
            entity.setJudgeCount(dto.getJudgeCount());
        }
        if (dto.getDimensions() != null) {
            entity.setDimensions(dto.getDimensions());
        }
        if (StringUtils.hasText(dto.getCalculationRule())) {
            entity.setCalculationRule(dto.getCalculationRule());
        }

        updateById(entity);
        log.info("评审规则更新成功，ID：{}", id);
        return entity;
    }

    @Override
    public void removeRule(Long id) {
        log.info("删除评审规则，ID：{}", id);
        removeById(id);
        log.info("评审规则删除成功，ID：{}", id);
    }

    // ====== 私有辅助方法 ======

    private Map<String, Object> entityToMap(BizContestReviewRule entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", entity.getId());
        map.put("tenantId", entity.getTenantId());
        map.put("ruleName", entity.getRuleName());
        map.put("ruleDescription", entity.getRuleDescription());
        map.put("judgeCount", entity.getJudgeCount());
        map.put("dimensions", entity.getDimensions());
        map.put("calculationRule", entity.getCalculationRule());
        map.put("createTime", entity.getCreateTime());
        map.put("modifyTime", entity.getModifyTime());
        return map;
    }
}
