package com.lesingle.modules.biz.homework.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.lesingle.common.enums.ErrorCode;
import com.lesingle.common.exception.BusinessException;
import com.lesingle.common.result.PageResult;
import com.lesingle.modules.biz.homework.dto.CreateHomeworkReviewRuleDto;
import com.lesingle.modules.biz.homework.entity.BizHomeworkReviewRule;
import com.lesingle.modules.biz.homework.mapper.HomeworkReviewRuleMapper;
import com.lesingle.modules.biz.homework.service.IHomeworkReviewRuleService;
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 HomeworkReviewRuleServiceImpl extends ServiceImpl<HomeworkReviewRuleMapper, BizHomeworkReviewRule> implements IHomeworkReviewRuleService {

    private final HomeworkReviewRuleMapper homeworkReviewRuleMapper;

    @Override
    public BizHomeworkReviewRule create(CreateHomeworkReviewRuleDto dto, Long tenantId) {
        log.info("创建作业评审规则，名称：{}，租户：{}", dto.getName(), tenantId);

        BizHomeworkReviewRule entity = new BizHomeworkReviewRule();
        entity.setTenantId(tenantId);
        entity.setName(dto.getName());
        entity.setDescription(dto.getDescription());
        entity.setCriteria(dto.getCriteria());

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

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

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

        if (tenantId != null) {
            wrapper.eq(BizHomeworkReviewRule::getTenantId, tenantId);
        }
        if (StringUtils.hasText(name)) {
            wrapper.like(BizHomeworkReviewRule::getName, name);
        }

        wrapper.orderByDesc(BizHomeworkReviewRule::getCreateTime);

        Page<BizHomeworkReviewRule> pageObj = new Page<>(page, pageSize);
        Page<BizHomeworkReviewRule> result = homeworkReviewRuleMapper.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<BizHomeworkReviewRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BizHomeworkReviewRule::getValidState, 1);
        if (tenantId != null) {
            wrapper.eq(BizHomeworkReviewRule::getTenantId, tenantId);
        }
        wrapper.orderByDesc(BizHomeworkReviewRule::getCreateTime);

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

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

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

    @Override
    public BizHomeworkReviewRule update(Long id, CreateHomeworkReviewRuleDto dto) {
        log.info("更新作业评审规则，ID：{}", id);

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

        if (StringUtils.hasText(dto.getName())) {
            entity.setName(dto.getName());
        }
        if (dto.getDescription() != null) {
            entity.setDescription(dto.getDescription());
        }
        if (dto.getCriteria() != null) {
            entity.setCriteria(dto.getCriteria());
        }

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

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

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

    private Map<String, Object> entityToMap(BizHomeworkReviewRule entity) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", entity.getId());
        map.put("tenantId", entity.getTenantId());
        map.put("name", entity.getName());
        map.put("description", entity.getDescription());
        map.put("criteria", entity.getCriteria());
        map.put("createTime", entity.getCreateTime());
        map.put("modifyTime", entity.getModifyTime());
        return map;
    }
}
