package com.yimeng.okr.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yimeng.okr.entity.AssessmentDimension;
import com.yimeng.okr.exception.BusinessException;
import com.yimeng.okr.mapper.AssessmentDimensionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DimensionService {

    private final AssessmentDimensionMapper mapper;

    public List<AssessmentDimension> listAll() {
        return mapper.selectList(
                new LambdaQueryWrapper<AssessmentDimension>().orderByAsc(AssessmentDimension::getSortOrder));
    }

    public AssessmentDimension create(AssessmentDimension dim) {
        mapper.insert(dim);
        validateTotal();
        return dim;
    }

    public void update(AssessmentDimension dim) {
        mapper.updateById(dim);
        validateTotal();
    }

    public void delete(Long id) {
        mapper.deleteById(id);
        validateTotal();
    }

    private void validateTotal() {
        List<AssessmentDimension> dims = listAll();
        if (dims.isEmpty()) return;
        int sum = dims.stream().mapToInt(d -> d.getMaxScore() != null ? d.getMaxScore() : 0).sum();
        if (sum != 40) {
            throw new BusinessException("所有考核维度满分之和必须为40，当前为" + sum);
        }
    }
}
