package com.hz.pm.api.performance.helper.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.hz.pm.api.performance.enumration.AppraisalTypeEnum;
import com.hz.pm.api.performance.enumration.PerformanceTemplateTypeEnum;
import com.hz.pm.api.performance.helper.TemplateDetailBuildHelper;
import com.hz.pm.api.performance.model.entity.PerformanceAppraisalScoreInfo;
import com.hz.pm.api.performance.model.entity.PerformanceIndicatorProjectTemplateDetail;
import com.hz.pm.api.performance.model.vo.ProjectAppraisalIndexDetailVO;
import com.hz.pm.api.performance.model.vo.ProjectTemplateDetailVO;
import com.hz.pm.api.performance.service.IPerformanceAppraisalScoreInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author CMM
 * @since 2023/08/09 22:31
 */
@Component
@RequiredArgsConstructor
public class TemplateDetailBuildHelperImpl implements TemplateDetailBuildHelper {

    private final IPerformanceAppraisalScoreInfoService performanceAppraisalScoreInfoService;

    @Override
    public List<ProjectTemplateDetailVO> buildTemplateDetail(List<PerformanceIndicatorProjectTemplateDetail> templateDetails, String projectCode, ProjectAppraisalIndexDetailVO vo) {
        List<ProjectTemplateDetailVO> res = Lists.newArrayList();
        //第一层是 一级的
        for (PerformanceIndicatorProjectTemplateDetail templateDetailFirst : templateDetails) {
            if (PerformanceTemplateTypeEnum.FIRST_INDEX.getCode().equals(templateDetailFirst.getType())) {
                ProjectTemplateDetailVO detailFirstVo = BeanUtil.copyProperties(templateDetailFirst, ProjectTemplateDetailVO.class);
                List<ProjectTemplateDetailVO> firstList = Lists.newArrayList();
                // 该层循环筛选出第二 指标
                for (PerformanceIndicatorProjectTemplateDetail templateDetailSecond : templateDetails) {
                    if (Objects.nonNull(templateDetailSecond.getParentId()) &&
                            templateDetailSecond.getParentId().equals(templateDetailFirst.getId())) {
                        ProjectTemplateDetailVO detailSecondVo = BeanUtil.copyProperties(templateDetailSecond, ProjectTemplateDetailVO.class);
                        List<ProjectTemplateDetailVO> secondList = Lists.newArrayList();
                        // 该层循环筛选出第三 指标
                        for (PerformanceIndicatorProjectTemplateDetail templateDetailThird : templateDetails) {
                            if (Objects.nonNull(templateDetailThird.getParentId()) &&
                                    templateDetailThird.getParentId().equals(templateDetailSecond.getId())) {
                                ProjectTemplateDetailVO detailThirdVo = BeanUtil.copyProperties(templateDetailThird, ProjectTemplateDetailVO.class);
                                // 如果有单位自评、复评、核查、整改审核分数信息，各自装配信息
                                // 获取自评分数信息
                                List<PerformanceAppraisalScoreInfo> selfAppraisalScoreInfo = performanceAppraisalScoreInfoService.list(Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                                        .eq(PerformanceAppraisalScoreInfo::getTemplateDetailId, templateDetailThird.getId())
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode,projectCode)
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.SELF_APPRAISAL.getCode()));
                                if (CollUtil.isNotEmpty(selfAppraisalScoreInfo)) {
                                    detailThirdVo.setSelfAppraisalScoreInfo(selfAppraisalScoreInfo);
                                    BigDecimal score = selfAppraisalScoreInfo.stream().map(PerformanceAppraisalScoreInfo::getAppraisalScore)
                                            .filter(Objects::nonNull)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                                    if (Objects.nonNull(vo)) {
                                        vo.setSelfAppraisalTotalScore(score);
                                    }
                                }
                                // 按照复评人员分组 获取复评分数信息
                                List<PerformanceAppraisalScoreInfo> reAppraisalScoreInfo = performanceAppraisalScoreInfoService.list(Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                                        .eq(PerformanceAppraisalScoreInfo::getTemplateDetailId, templateDetailThird.getId())
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode,projectCode)
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.RE_APPRAISAL.getCode()));
                                if (CollUtil.isNotEmpty(reAppraisalScoreInfo)) {
                                    Map<String, List<PerformanceAppraisalScoreInfo>> reAppScoreInfoMap = reAppraisalScoreInfo.stream()
                                            .collect(Collectors.groupingBy(PerformanceAppraisalScoreInfo::getAppraisalUserName));
                                    HashMap<String, BigDecimal> scoreMap = MapUtil.newHashMap();
                                    for (String name : reAppScoreInfoMap.keySet()) {
                                        List<PerformanceAppraisalScoreInfo> scoreInfos = reAppScoreInfoMap.get(name);
                                        BigDecimal totalScore = scoreInfos.stream().map(PerformanceAppraisalScoreInfo::getAppraisalScore)
                                                .filter(Objects::nonNull)
                                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                                        scoreMap.put(name, totalScore);
                                    }
                                    detailThirdVo.setReAppraisalTotalScoreInfo(scoreMap);
                                    detailThirdVo.setReAppraisalScoreInfo(reAppScoreInfoMap);
                                    if (Objects.nonNull(vo)){
                                        BigDecimal sum = scoreMap.values().stream()
                                                .filter(Objects::nonNull)
                                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                                        vo.setReAppraisalTotalScore(sum);
                                    }
                                }
                                // 按照核查人员分组 获取核查分数信息
                                List<PerformanceAppraisalScoreInfo> verifyScoreInfo = performanceAppraisalScoreInfoService.list(Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                                        .eq(PerformanceAppraisalScoreInfo::getTemplateDetailId, templateDetailThird.getId())
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode,projectCode)
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.EXPERT_VERIFY.getCode()));
                                if (CollUtil.isNotEmpty(verifyScoreInfo)) {
                                    Map<String, List<PerformanceAppraisalScoreInfo>> verifyScoreInfoMap = verifyScoreInfo.stream()
                                            .collect(Collectors.groupingBy(PerformanceAppraisalScoreInfo::getAppraisalUserName));
                                    HashMap<String, BigDecimal> scoreMap = MapUtil.newHashMap();
                                    for (String name : verifyScoreInfoMap.keySet()) {
                                        List<PerformanceAppraisalScoreInfo> scoreInfos = verifyScoreInfoMap.get(name);
                                        BigDecimal totalScore = scoreInfos.stream().map(PerformanceAppraisalScoreInfo::getAppraisalScore)
                                                .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                                        scoreMap.put(name, totalScore);
                                    }
                                    detailThirdVo.setVerifyTotalScoreInfo(scoreMap);
                                    detailThirdVo.setVerifyScoreInfo(verifyScoreInfoMap);
                                    if (Objects.nonNull(vo)){
                                        BigDecimal sum = scoreMap.values().stream()
                                                .filter(Objects::nonNull)
                                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                                        vo.setVerifyTotalScore(sum);
                                    }
                                }
                                // 获取整改审核分数信息
                                List<PerformanceAppraisalScoreInfo> rectifyAuditScoreInfo = performanceAppraisalScoreInfoService.list(Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                                        .eq(PerformanceAppraisalScoreInfo::getTemplateDetailId, templateDetailThird.getId())
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode,projectCode)
                                        .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.EXPERT_RECTIFY_AUDIT.getCode()));
                                if (CollUtil.isNotEmpty(rectifyAuditScoreInfo)) {
                                    detailThirdVo.setRectifyAuditScoreInfo(rectifyAuditScoreInfo);
                                    BigDecimal score = rectifyAuditScoreInfo.stream().map(PerformanceAppraisalScoreInfo::getAppraisalScore)
                                            .filter(Objects::nonNull)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                                    if (Objects.nonNull(vo)) {
                                        vo.setRectifyAuditTotalScore(score);
                                    }
                                }
                                secondList.add(detailThirdVo);
                            }
                        }
                        detailSecondVo.setChildren(secondList);
                        firstList.add(detailSecondVo);
                    }
                }
                detailFirstVo.setChildren(firstList);
                res.add(detailFirstVo);

            }
        }
        return res;
    }
}
