package com.hz.pm.api.performance.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.hz.pm.api.common.enumeration.CommonEnum;
import com.hz.pm.api.common.model.constant.BizConst;
import com.hz.pm.api.common.util.ExcelDownUtil;
import com.hz.pm.api.common.util.StrUtils;
import com.hz.pm.api.performance.constant.ProjectBizConst;
import com.hz.pm.api.performance.enumration.AppraisalTypeEnum;
import com.hz.pm.api.performance.enumration.RectifyStatusEnum;
import com.hz.pm.api.performance.model.dto.ProjectAppraisalDTO;
import com.hz.pm.api.performance.model.dto.ProjectAppraisalInfoDTO;
import com.hz.pm.api.performance.model.entity.*;
import com.hz.pm.api.performance.model.req.PerformanceAppraisalExportReq;
import com.hz.pm.api.performance.model.req.PerformanceAppraisalListReq;
import com.hz.pm.api.performance.model.vo.PerformanceAppraisalProjectVO;
import com.hz.pm.api.performance.model.vo.PerformanceAppraisalVO;
import com.hz.pm.api.performance.service.*;
import com.hz.pm.api.performance.util.*;
import com.hz.pm.api.portrait.model.entity.ProjectTag;
import com.hz.pm.api.portrait.service.IProjectTagService;
import com.hz.pm.api.projectlib.model.entity.Project;
import com.hz.pm.api.projectlib.model.enumeration.ProjectTypeNewEnum;
import com.hz.pm.api.projectlib.service.IProjectService;
import com.hz.pm.api.sys.model.entity.Role;
import com.hz.pm.api.sys.service.IRoleService;
import com.hz.pm.api.user.model.enumeration.RoleEnum;
import com.hz.pm.api.user.security.model.UserInfoDetails;
import com.hz.pm.api.user.util.LoginUserUtil;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.function.VUtils;
import com.ningdatech.basic.model.PageVo;
import com.ningdatech.basic.util.StrPool;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * VerifyManage
 *
 * @author CMM
 * @since 2023/08/10 8:55
 */
@Slf4j
@Component
@AllArgsConstructor
public class VerifyManage {

    private final IPerformanceAppraisalService performanceAppraisalService;
    private final IPerformanceAppraisalProjectService performanceAppraisalProjectService;
    private final IProjectService projectService;
    private final IRoleService roleService;
    private final IPerformanceIndicatorProjectTemplateDetailService indicatorProjectTemplateDetailService;
    private final IPerformanceAppraisalScoreInfoService performanceAppraisalScoreInfoService;
    private final IPerformanceAppraisalProjectGroupService groupService;
    private final IProjectTagService projectTagService;
    private final IPerformanceIndicatorProjectTemplateService indicatorProjectTemplateService;

    /**
     * 核查-评价计划列表
     *
     * @param req \
     * @return \
     */
    public PageVo<PerformanceAppraisalVO> list(PerformanceAppraisalListReq req) {
        UserInfoDetails user = LoginUserUtil.loginUserDetail();
        String employeeCode = user.getEmployeeCode();
        // 获取当前登录用户的角色列表，只有专家核查人员才能查看该列表
        List<Role> userRoleList = user.getUserRoleList();
        List<Long> roleIdList = userRoleList.stream().map(Role::getId).collect(Collectors.toList());
        Role role = roleService.getOne(Wrappers.lambdaQuery(Role.class)
                .eq(Role::getName, RoleEnum.EXPERT.getDesc()));
        if (Objects.isNull(role)) {
            throw new BizException("登录用户没有复评员角色!");
        }

        // 登录用户不是专家，不能查看核查计划列表
        if (!roleIdList.contains(role.getId())) {
            return PageVo.empty();
        }

        // 从绩效评价 分组表中获取当前登录专家所在的分组信息
        List<PerformanceAppraisalProjectGroup> groups = Lists.newArrayList();
        List<PerformanceAppraisalProjectGroup> projectGroups = groupService.list();
        for (PerformanceAppraisalProjectGroup projectGroup : projectGroups) {
            String verificationUsers = projectGroup.getVerificationUsers();
            if (StrUtils.isNotBlank(verificationUsers)) {
                if (verificationUsers.contains(StrPool.COMMA)) {
                    if (verificationUsers.contains(employeeCode)) {
                        groups.add(projectGroup);
                    }
                } else if (verificationUsers.equals(employeeCode)) {
                    groups.add(projectGroup);
                }
            }
        }
        // 当前登录专家没有绩效分组信息
        if (CollUtil.isEmpty(groups)) {
            return PageVo.empty();
        }

        // 获取分组所在的评价计划ID
        List<Long> appraisalIds = groups.stream().map(PerformanceAppraisalProjectGroup::getAppraisalId).collect(Collectors.toList());
        // 因为同一个核查人员只能出现在一个计划的一个分组中，所以分组信息可按照评价计划ID进行分组
        Map<Long, PerformanceAppraisalProjectGroup> groupMap = groups.stream().collect(Collectors.toMap(PerformanceAppraisalProjectGroup::getAppraisalId, g -> g));
        // 获取核查计划列表
        Page<PerformanceAppraisal> page = req.page();
        LambdaQueryWrapper<PerformanceAppraisal> wrapper = Wrappers.lambdaQuery(PerformanceAppraisal.class)
                .in(PerformanceAppraisal::getId, appraisalIds)
                .orderByDesc(PerformanceAppraisal::getUpdateOn);
        performanceAppraisalService.page(page, wrapper);

        List<PerformanceAppraisalVO> res = page.getRecords().stream().map(p -> {
            PerformanceAppraisalVO vo = BeanUtil.copyProperties(p, PerformanceAppraisalVO.class);
            PerformanceAppraisalProjectGroup group = groupMap.get(p.getId());
            if (Objects.nonNull(group)) {
                vo.setVerifyGroupId(group.getId());
                vo.setVerifyGroupName(group.getName());
            }
            return vo;
        }).collect(Collectors.toList());
        return PageVo.of(res, page.getTotal());
    }

    /**
     * 是否可以核查
     *
     * @param userId      \
     * @param projectCode \
     * @param appraisalId \
     * @return \
     */
    private Boolean checkCanVerify(String userId, String projectCode, Long appraisalId) {
        // 首次核查(核查打分信息为空)
        // 从绩效评价打分信息表中查询打分类型为专家核查、打分人员为当前登录专家用户的打分信息
        // 如果没有相关的打分信息，说明是当前登录复评用户是首次核查
        Wrapper<PerformanceAppraisalScoreInfo> query = Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.EXPERT_VERIFY.getCode())
                .eq(PerformanceAppraisalScoreInfo::getAppraisalId, appraisalId)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode, projectCode)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalUserId, userId)
                .last(BizConst.LIMIT_1);
        return performanceAppraisalScoreInfoService.count(query) == 0;
    }

    public PageVo<PerformanceAppraisalProjectVO> groupProjectList(Long groupId, PerformanceAppraisalListReq req) {

        UserInfoDetails userDetail = LoginUserUtil.loginUserDetail();
        String userIdStr = userDetail.getUserIdStr();

        // 获取分组内的项目信息
        PerformanceAppraisalProjectGroup projectGroup = groupService.getById(groupId);
        if (Objects.isNull(projectGroup)) {
            throw new BizException("当前核查用户所在分组不存在!");
        }
        String projectCodes = projectGroup.getProjectCodes();
        Long appraisalId = projectGroup.getAppraisalId();
        VUtils.isTrue(StringUtils.isBlank(projectCodes)).throwMessage("分组内项目信息不存在!");
        List<String> projectCodeList = Arrays.stream(projectCodes.split(StrPool.COMMA)).collect(Collectors.toList());

        // 筛选出分组内已完成复评的评价项目信息
        List<PerformanceAppraisalProject> appraisalProjects = performanceAppraisalProjectService.list(Wrappers.lambdaQuery(PerformanceAppraisalProject.class)
                .in(PerformanceAppraisalProject::getProjectCode, projectCodeList)
                .eq(PerformanceAppraisalProject::getIsCompleteReAppraisal, Boolean.TRUE));
        // 分组内已完成复评的项目信息不存在
        if (CollUtil.isEmpty(appraisalProjects)) {
            return PageVo.empty();
        }
        List<String> proCodeList = appraisalProjects.stream().map(PerformanceAppraisalProject::getProjectCode).collect(Collectors.toList());
        Map<String, PerformanceAppraisalProject> appraisalProjectMap = appraisalProjects.stream().collect(Collectors.toMap(PerformanceAppraisalProject::getProjectCode, p -> p));

        Page<Project> page = req.page();
        LambdaQueryWrapper<Project> wrapper = Wrappers.lambdaQuery(Project.class)
                .in(Project::getProjectCode, proCodeList)
                .eq(Project::getNewest, Boolean.TRUE)
                .like(StringUtils.isNotBlank(req.getProjectName()), Project::getProjectName, req.getProjectName());
        projectService.page(page, wrapper);

        // 分组内项目信息不存在
        if (CollUtil.isEmpty(page.getRecords())) {
            return PageVo.empty();
        }

        List<PerformanceAppraisalProjectVO> res = page.getRecords().stream().map(p -> {
                    PerformanceAppraisalProjectVO vo = BeanUtil.copyProperties(p, PerformanceAppraisalProjectVO.class);
                    PerformanceAppraisalProject appraisalProject = appraisalProjectMap.get(p.getProjectCode());
                    BeanUtil.copyProperties(appraisalProject, vo);
                    vo.setProjectId(appraisalProject.getProjectId());
                    vo.setProjectTypeName(ProjectTypeNewEnum.getDesc(p.getProjectType()));
                    vo.setCanVerify(checkCanVerify(userIdStr, appraisalProject.getProjectCode(), appraisalId));
                    // 如果登录用户是核查组长，该项目可填写整改意见
                    String verifyLeader = projectGroup.getVerifyLeader();
                    if (userIdStr.equals(verifyLeader)) {
                        vo.setCanRectify(Boolean.TRUE);
                    }
                    vo.setGroupId(groupId);
                    return vo;
                })
                .collect(Collectors.toList());
        return PageVo.of(res, page.getTotal());
    }

    @Transactional(rollbackFor = Exception.class)
    public String submitVerify(ProjectAppraisalDTO param) {
        UserInfoDetails userDetail = LoginUserUtil.loginUserDetail();
        String userIdStr = String.valueOf(userDetail.getUserId());
        String username = userDetail.getUsername();
        Long appraisalId = param.getAppraisalId();
        Long appraisalProjectId = param.getAppraisalProjectId();
        String appraisalProjectCode = param.getAppraisalProjectCode();
        List<ProjectAppraisalInfoDTO> appraisalInfoList = param.getAppraisalInfoList();
        Long groupId = param.getGroupId();
        PerformanceAppraisalProjectGroup group = groupService.getById(groupId);

        // 获取评价项目
        PerformanceAppraisalProject appraisalProject = performanceAppraisalProjectService.getOne(Wrappers.lambdaQuery(PerformanceAppraisalProject.class)
                .eq(PerformanceAppraisalProject::getAppraisalId, appraisalId)
                .eq(PerformanceAppraisalProject::getProjectCode, appraisalProjectCode)
                .eq(PerformanceAppraisalProject::getProjectId, appraisalProjectId));

        List<Long> ids = appraisalInfoList.stream()
                .map(ProjectAppraisalInfoDTO::getProjectTemplateDetailId)
                .collect(Collectors.toList());
        // 查出项目模版详情信息
        List<PerformanceIndicatorProjectTemplateDetail> detailList = indicatorProjectTemplateDetailService.list(Wrappers.lambdaQuery(PerformanceIndicatorProjectTemplateDetail.class)
                .in(PerformanceIndicatorProjectTemplateDetail::getId, ids));
        if (CollUtil.isEmpty(detailList)) {
            throw new BizException("评价指标不存在!");
        }
        Map<Long, PerformanceIndicatorProjectTemplateDetail> detailMap = detailList.stream().collect(Collectors.toMap(PerformanceIndicatorProjectTemplateDetail::getId, d -> d));
        List<PerformanceAppraisalScoreInfo> scoreInfos = appraisalInfoList.stream().map(a -> {
            PerformanceIndicatorProjectTemplateDetail templateDetail = detailMap.get(a.getProjectTemplateDetailId());
            BigDecimal score = a.getScore();
            BigDecimal indexScore = templateDetail.getIndexScore();
            if (score.compareTo(indexScore) > 0 || score.compareTo(BigDecimal.ZERO) < 0) {
                throw new BizException("核查得分必须大于等于0且小于等于指标分值!");
            }
            // 保存核查分数信息
            PerformanceAppraisalScoreInfo scoreInfo = new PerformanceAppraisalScoreInfo();
            scoreInfo.setAppraisalBasis(a.getAppraisalBasis());
            scoreInfo.setAppraisalScore(a.getScore());
            scoreInfo.setAppraisalBasisAppendix(a.getAppraisalBasisAppendix());
            scoreInfo.setAppraisalType(AppraisalTypeEnum.EXPERT_VERIFY.getCode());
            scoreInfo.setTemplateDetailId(templateDetail.getId());
            scoreInfo.setTemplateId(templateDetail.getTemplateId());
            scoreInfo.setAppraisalUserName(username);
            scoreInfo.setAppraisalUserId(userIdStr);
            scoreInfo.setAppraisalId(appraisalId);
            scoreInfo.setAppraisalProjectId(appraisalProjectId);
            scoreInfo.setAppraisalProjectCode(appraisalProjectCode);
            scoreInfo.setCreateOn(LocalDateTime.now());
            scoreInfo.setCreateBy(username);
            return scoreInfo;
        }).collect(Collectors.toList());

        if (performanceAppraisalScoreInfoService.saveBatch(scoreInfos)) {
            // 计算核查总分并保存
            BigDecimal verifyTotalScore = appraisalInfoList.stream()
                    .map(ProjectAppraisalInfoDTO::getScore)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal lastVerifyTotalScore;
            // 判断项目所在分组内其他复评人员是否已经打分
            if (Objects.nonNull(appraisalProject.getVerifyTotalScore())) {
                // 已经进行了核查，计算两个分值的平均分
                BigDecimal add = verifyTotalScore.add(appraisalProject.getReAppraisalTotalScore());
                lastVerifyTotalScore = add.divide(BigDecimal.valueOf(2), RoundingMode.HALF_UP);
            } else {
                // 还没有进行过复评
                lastVerifyTotalScore = verifyTotalScore;
            }
            appraisalProject.setVerifyTotalScore(lastVerifyTotalScore);
            // 取最新地核查打分时间
            appraisalProject.setVerifyScoreTime(LocalDateTime.now());
            // 判断当前核查人是否为该评价项目所在分组的核查人员中的最后一个核查人
            judgeCompleteVerify(group, appraisalProject);
            appraisalProject.setUpdateOn(LocalDateTime.now());
            appraisalProject.setUpdateBy(username);
            // 保存整改相关信息
            if (Objects.nonNull(param.getIsRectify()) ||
                    StringUtils.isNotBlank(param.getRectifyOpinion())) {
                appraisalProject.setIsRectify(param.getIsRectify());
                appraisalProject.setRectifyOpinion(param.getRectifyOpinion());
                appraisalProject.setRectifySubmitUserId(userIdStr);
                appraisalProject.setRectifySubmitTime(LocalDateTime.now());
                appraisalProject.setRectifyStatus(RectifyStatusEnum.TO_BE_SUBMITTED.getCode());
            }
            performanceAppraisalProjectService.updateById(appraisalProject);
            return "提交成功";
        }
        return "提交失败";
    }

    private void judgeCompleteVerify(PerformanceAppraisalProjectGroup group, PerformanceAppraisalProject appraisalProject) {
        // 获取该评价计划当前分组对该项目的核查打分信息
        List<PerformanceAppraisalScoreInfo> scoreInfoList = performanceAppraisalScoreInfoService.list(Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalId, group.getAppraisalId())
                .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode, appraisalProject.getProjectCode())
                .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.EXPERT_VERIFY.getCode()));

        // 判断打分人员是否为分组内的核查人员
        if (CollUtil.isNotEmpty(scoreInfoList)) {
            Set<String> users = scoreInfoList.stream()
                    .map(PerformanceAppraisalScoreInfo::getAppraisalUserId)
                    .collect(Collectors.toSet());
            if (CollUtil.isNotEmpty(users)) {
                String verificationUsers = group.getVerificationUsers();
                String join = String.join(StrPool.COMMA, users);
                if (join.equals(verificationUsers)) {
                    // 标记项目完成核查
                    appraisalProject.setIsCompleteVerify(Boolean.TRUE);
                }
            }
        }
    }

    public void exportScore(HttpServletResponse response, PerformanceAppraisalExportReq param) {
        String projectCode = param.getProjectCode();
        Long appraisalId = param.getAppraisalId();

        // 根据项目编码获取最新版本的项目信息
        Project project = projectService.getProjectByCode(projectCode);
        Assert.notNull(project, "项目不存在!");
        // 根据项目类型、预算年度、批复金额、项目标签匹配本区域指标模版
        String projectType = project.getProjectType();
        Integer projectYear = project.getProjectYear();
        BigDecimal approvalAmount = project.getApprovalAmount();
        Assert.notNull(approvalAmount, "未获取到该项目的立项批复金额");
        // 根据项目code获取项目标签ID列表
        String tagIdStr = projectTagService.list(Wrappers.lambdaQuery(ProjectTag.class)
                        .eq(ProjectTag::getProjectCode, projectCode)).stream()
                .map(w -> w.getTagId().toString()).collect(Collectors.joining(","));
        Assert.notEmpty(tagIdStr, "当前项目未设置标签，请至项目库或评价计划编辑页面设置标签!");

        Integer amountRange;
        if (approvalAmount.compareTo(BigDecimal.valueOf(ProjectBizConst.FIVE_MILLION)) < 0) {
            amountRange = ProjectBizConst.AMOUNT_RANGE_ONE;
        } else if (approvalAmount.compareTo(BigDecimal.valueOf(ProjectBizConst.FIVE_MILLION)) >= 0 &&
                approvalAmount.compareTo(BigDecimal.valueOf(ProjectBizConst.TWENTY_MILLION)) < 0) {
            amountRange = ProjectBizConst.AMOUNT_RANGE_TWO;
        } else if (approvalAmount.compareTo(BigDecimal.valueOf(ProjectBizConst.TWENTY_MILLION)) >= 0) {
            amountRange = ProjectBizConst.AMOUNT_RANGE_THREE;
        } else {
            amountRange = null;
        }
        LambdaQueryWrapper<PerformanceIndicatorProjectTemplate> wrapper = Wrappers
                .lambdaQuery(PerformanceIndicatorProjectTemplate.class)
                .eq(PerformanceIndicatorProjectTemplate::getProjectType, projectType)
                .eq(PerformanceIndicatorProjectTemplate::getProjectYear, projectYear)
                .eq(PerformanceIndicatorProjectTemplate::getAmountRange, amountRange)
                .eq(PerformanceIndicatorProjectTemplate::getProjectTagIds, tagIdStr)
                .eq(PerformanceIndicatorProjectTemplate::getStatus, CommonEnum.YES.getCode())
                .orderByDesc(PerformanceIndicatorProjectTemplate::getUpdateOn);
        List<PerformanceIndicatorProjectTemplate> templates = indicatorProjectTemplateService.list(wrapper);
        if (templates.size() != 1) {
            throw BizException.wrap("当前项目模版配置错误!");
        }
        PerformanceIndicatorProjectTemplate projectTemplate = templates.get(0);
        // 装配项目指标详情及分数信息
        // 获取模版绩效指标详情
        List<PerformanceIndicatorProjectTemplateDetail> templateDetails = indicatorProjectTemplateDetailService.list(Wrappers.lambdaQuery(PerformanceIndicatorProjectTemplateDetail.class)
                .eq(PerformanceIndicatorProjectTemplateDetail::getTemplateId, projectTemplate.getId()));
        Map<Long, PerformanceIndicatorProjectTemplateDetail> templateDetailMap = templateDetails.stream().collect(Collectors.toMap(PerformanceIndicatorProjectTemplateDetail::getId, t -> t));

        List<Map<String, Object>> exportDataList = Lists.newArrayList();
        List<Map<String, Object>> exportAdditionalDataList = Lists.newArrayList();
        // 构建指标和打分详情
        List<PerformanceAppraisalScoreInfo> scoreInfoList = performanceAppraisalScoreInfoService.list(Wrappers
                .lambdaQuery(PerformanceAppraisalScoreInfo.class)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalId, appraisalId)
                .and(wp -> wp.eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.SELF_APPRAISAL.getCode())
                        .or().eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.RE_APPRAISAL.getCode())
                        .or().eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.EXPERT_VERIFY.getCode()))
                .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode, projectCode)
                .orderBy(Boolean.TRUE, Boolean.TRUE, PerformanceAppraisalScoreInfo::getTemplateDetailId));
        Map<Long, PerformanceAppraisalScoreInfo> scoreInfoMap = scoreInfoList.stream()
                .collect(Collectors.toMap(PerformanceAppraisalScoreInfo::getTemplateDetailId, p -> p));

        // 获取复评打分人员信息
        List<PerformanceAppraisalScoreInfo> reScoreInfoList = scoreInfoList.stream()
                .filter(s -> AppraisalTypeEnum.RE_APPRAISAL.getCode().equals(s.getAppraisalType()))
                .collect(Collectors.toList());
        List<String> reUserList = reScoreInfoList.stream()
                .map(PerformanceAppraisalScoreInfo::getAppraisalUserName)
                .collect(Collectors.toList());

        // 获取核查打分人员信息
        List<PerformanceAppraisalScoreInfo> verifyScoreInfoList = scoreInfoList.stream()
                .filter(s -> AppraisalTypeEnum.EXPERT_VERIFY.getCode().equals(s.getAppraisalType()))
                .collect(Collectors.toList());
        List<String> verifyUserList = verifyScoreInfoList.stream()
                .map(PerformanceAppraisalScoreInfo::getAppraisalUserName)
                .collect(Collectors.toList());

        // 筛选出所有打分的三级指标模板详情ID
        for (PerformanceAppraisalScoreInfo scoreInfo : scoreInfoList) {
            Map<String, Object> scoreMap = MapUtil.newHashMap();
            Long detailId = scoreInfo.getTemplateDetailId();
            PerformanceIndicatorProjectTemplateDetail thirdTemplateDetail = templateDetailMap.get(detailId);

            // 二级指标名称
            Long secondId = thirdTemplateDetail.getParentId();
            if (Objects.nonNull(secondId)) {
                PerformanceIndicatorProjectTemplateDetail secondTemplateDetail = templateDetailMap.get(secondId);
                if (Objects.nonNull(secondTemplateDetail)) {
                    // 一级指标名称
                    Long firstId = secondTemplateDetail.getParentId();
                    if (Objects.nonNull(firstId)) {
                        PerformanceIndicatorProjectTemplateDetail firstTemplateDetail = templateDetailMap.get(firstId);
                        if (Objects.nonNull(firstTemplateDetail)) {
                            scoreMap.put(ProjectBizConst.FIRST_INDEX_NAME, firstTemplateDetail.getName());
                            scoreMap.put(ProjectBizConst.SECOND_INDEX_NAME, secondTemplateDetail.getName());
                        }
                    }
                }
            }
            scoreMap.put(ProjectBizConst.THIRD_INDEX_NAME, thirdTemplateDetail.getName());
            scoreMap.put(ProjectBizConst.INDEX_SCORE, thirdTemplateDetail.getIndexScore());
            scoreMap.put(ProjectBizConst.INDEX_DETAIL, thirdTemplateDetail.getIndexDetail());
            scoreMap.put(ProjectBizConst.GRADE_DETAIL, thirdTemplateDetail.getGradeDetail());
            scoreMap.put(ProjectBizConst.SUPPORT_MATERIAL, thirdTemplateDetail.getSupportMaterial());

            PerformanceAppraisalScoreInfo appraisalScoreInfo = scoreInfoMap.get(thirdTemplateDetail.getId());
            // 构建自评和复评打分信息
            if (AppraisalTypeEnum.SELF_APPRAISAL.getCode().equals(appraisalScoreInfo.getAppraisalType())) {
                scoreMap.put(ProjectBizConst.SELF_APPRAISAL_BASIS, appraisalScoreInfo.getAppraisalBasis());
                scoreMap.put(ProjectBizConst.SELF_APPRAISAL_SCORE, appraisalScoreInfo.getAppraisalScore());
            } else if (AppraisalTypeEnum.RE_APPRAISAL.getCode().equals(appraisalScoreInfo.getAppraisalType())) {
                scoreMap.put(appraisalScoreInfo.getAppraisalUserName() + ProjectBizConst.RE_APPRAISAL_BASIS, appraisalScoreInfo.getAppraisalBasis());
                scoreMap.put(appraisalScoreInfo.getAppraisalUserName() + ProjectBizConst.RE_APPRAISAL_SCORE, appraisalScoreInfo.getAppraisalScore());
            } else if (AppraisalTypeEnum.EXPERT_VERIFY.getCode().equals(appraisalScoreInfo.getAppraisalType())) {
                scoreMap.put(appraisalScoreInfo.getAppraisalUserName() + ProjectBizConst.VERIFY_BASIS, appraisalScoreInfo.getAppraisalBasis());
                scoreMap.put(appraisalScoreInfo.getAppraisalUserName() + ProjectBizConst.VERIFY_SCORE, appraisalScoreInfo.getAppraisalScore());
            }

            if (Boolean.TRUE.equals(thirdTemplateDetail.getIsAdditional())) {
                scoreMap.put(ProjectBizConst.IS_ADDITIONAL, CommonEnum.YES.getDesc());
            } else if (Boolean.FALSE.equals(thirdTemplateDetail.getIsAdditional())) {
                scoreMap.put(ProjectBizConst.IS_ADDITIONAL, CommonEnum.NO.getDesc());
            }
            if (Boolean.FALSE.equals(thirdTemplateDetail.getIsAdditional())) {
                exportDataList.add(scoreMap);
            } else {
                exportAdditionalDataList.add(scoreMap);
            }
        }
        exportDataList.addAll(exportAdditionalDataList);
        String fileName = "绩效评价_专家核查_评分明细表";
        ExcelDownUtil.setFileName(fileName, response);
        int[] mergeColumnIndex = {0};
        // 需要从第几行开始合并
        int mergeRowIndex = 2;

        List<ExcelHead<Object>> headList = Lists.newArrayList();
        headList.add(new ExcelHead<>(ProjectBizConst.FIRST_INDEX_NAME, ProjectBizConst.FIRST_INDEX_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.SECOND_INDEX_NAME, ProjectBizConst.SECOND_INDEX_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.THIRD_INDEX_NAME, ProjectBizConst.THIRD_INDEX_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.INDEX_SCORE, ProjectBizConst.INDEX_SCORE_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.INDEX_DETAIL, ProjectBizConst.INDEX_DETAIL_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.GRADE_DETAIL, ProjectBizConst.GRADE_DETAIL_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.SUPPORT_MATERIAL, ProjectBizConst.SUPPORT_MATERIAL_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.SELF_APPRAISAL_BASIS, ProjectBizConst.SELF_APPRAISAL_BASIS_TITLE, StrPool.EMPTY));
        headList.add(new ExcelHead<>(ProjectBizConst.SELF_APPRAISAL_SCORE, ProjectBizConst.SELF_APPRAISAL_SCORE_TITLE, StrPool.EMPTY));
        for (String reUser : reUserList) {
            headList.add(new ExcelHead<>(reUser + ProjectBizConst.RE_APPRAISAL_BASIS, ProjectBizConst.RE_APPRAISAL_BASIS_TITLE, StrPool.EMPTY));
            headList.add(new ExcelHead<>(reUser + ProjectBizConst.RE_APPRAISAL_SCORE, ProjectBizConst.RE_APPRAISAL_SCORE_TITLE, StrPool.EMPTY));
        }

        for (String verifyUser : verifyUserList) {
            headList.add(new ExcelHead<>(verifyUser + ProjectBizConst.VERIFY_BASIS, ProjectBizConst.VERIFY_BASIS_TITLE, StrPool.EMPTY));
            headList.add(new ExcelHead<>(verifyUser + ProjectBizConst.VERIFY_SCORE, ProjectBizConst.VERIFY_SCORE_TITLE, StrPool.EMPTY));
        }
        headList.add(new ExcelHead<>(ProjectBizConst.IS_ADDITIONAL, ProjectBizConst.IS_ADDITIONAL_TITLE, StrPool.EMPTY));

        // 数据导出处理函数
        try {
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setContentType(ContentTypeUtils.APPLICATION_EXCEL);
            ExcelWriterBuilder writerBuilder = EasyExcel.write();
            writerBuilder.file(response.getOutputStream());
            writerBuilder.autoCloseStream(true);
            writerBuilder.registerWriteHandler(new ExcelSheetVerticalCellStyleStrategy());
            writerBuilder.registerWriteHandler(new MultiColumnMergeStrategy(exportDataList.size(), 0, 1));
            writerBuilder.registerWriteHandler(new ExcelFillCellMergeStrategy(mergeRowIndex, mergeColumnIndex));
            writerBuilder.head(ExcelUtils.getHead(reUserList, verifyUserList))
                    .sheet(fileName)
                    .doWrite(ExcelUtils.convertData(headList, exportDataList));
        } catch (IOException e) {
            throw new BizException(e.getMessage());
        }
    }

}
