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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.CharsetUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
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.util.ExcelDownUtil;
import com.hz.pm.api.performance.constant.ProjectBizConst;
import com.hz.pm.api.performance.enumration.AppraisalTypeEnum;
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.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.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

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

    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, ProjectBizConst.REAPPRAISAL_ROLE));
        if (Objects.isNull(role)) {
            throw new BizException("登录用户没有复评员角色!");
        }

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

        // 从绩效评价 项目表中获取已经完成单位自评的项目
        List<PerformanceAppraisalProject> paps = performanceAppraisalProjectService.list().stream()
                .filter(p -> Objects.nonNull(p.getSelfAppraisalScoreTime())).collect(Collectors.toList());

        // 已存在的评价计划添加的评价项目都未完成单位自评
        if (CollUtil.isEmpty(paps)) {
            return PageVo.empty();
        }
        Set<Long> paIds = paps.stream().map(PerformanceAppraisalProject::getAppraisalId).collect(Collectors.toSet());

        // 获取评价计划关联的分组信息
        List<PerformanceAppraisalProjectGroup> groups = groupService.list(Wrappers.lambdaQuery(PerformanceAppraisalProjectGroup.class)
                .in(PerformanceAppraisalProjectGroup::getAppraisalId, paIds));
        // 获取当前登录复评员所在的分组信息
        List<PerformanceAppraisalProjectGroup> groupList = groups.stream().filter(g -> {
            String reAppraisalUsers = g.getReAppraisalUsers();
            List<String> empCodeList = Lists.newArrayList();
            if (reAppraisalUsers.contains(StrPool.COMMA)) {
                empCodeList.addAll(Arrays.asList(reAppraisalUsers.split(StrPool.COMMA)));
            } else {
                empCodeList.add(reAppraisalUsers);
            }
            return empCodeList.contains(employeeCode);
        }).collect(Collectors.toList());
        // 当前登录复评员用户，没有参加评价计划
        if (CollUtil.isEmpty(groupList)) {
            return PageVo.empty();
        }
        // 获取分组所在的评价计划ID
        List<Long> appraisalIds = groupList.stream().map(PerformanceAppraisalProjectGroup::getAppraisalId).collect(Collectors.toList());
        // 因为同一个复评员只能出现在一个计划的一个分组中，所以分组信息可按照评价计划ID进行分组
        Map<Long, PerformanceAppraisalProjectGroup> groupMap = groupList.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.setReAppraisalGroupId(group.getId());
                vo.setReAppraisalGroupName(group.getName());
            }
            return vo;
        }).collect(Collectors.toList());
        return PageVo.of(res, page.getTotal());
    }

    /**
     * 是否可以复评
     *
     * @param userId      \
     * @param projectCode \
     * @param appraisalId \
     * @return \
     */
    private Boolean checkCanReAppraisal(String userId, String projectCode, Long appraisalId) {
        // 首次复评(复评打分时间为空)
        // 从绩效评价打分信息表中查询打分类型为复评、打分人员为当前登录复评用户的打分信息
        // 如果没有相关的打分信息，说明是当前登录复评用户是首次复评
        List<PerformanceAppraisalScoreInfo> scoreInfos = performanceAppraisalScoreInfoService.list(Wrappers.lambdaQuery(PerformanceAppraisalScoreInfo.class)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalType, AppraisalTypeEnum.RE_APPRAISAL.getCode())
                .eq(PerformanceAppraisalScoreInfo::getAppraisalProjectCode, projectCode)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalId, appraisalId)
                .eq(PerformanceAppraisalScoreInfo::getAppraisalUserId, userId));
        if (CollUtil.isEmpty(scoreInfos)) {
            return true;
        }
        return Boolean.FALSE;
    }

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

        UserInfoDetails userDetail = LoginUserUtil.loginUserDetail();
        String employeeCode = userDetail.getEmployeeCode();

        // 获取分组内的项目信息
        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::getIsReAppraisal, Boolean.TRUE)
                .eq(PerformanceAppraisalProject::getIsCompleteSelfAppraisal, 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.setCanReAppraisal(checkCanReAppraisal(employeeCode, appraisalProject.getProjectCode(), appraisalId));
                    if (Boolean.TRUE.equals(appraisalProject.getIsCompleteReAppraisal())) {
                        // 完成复评的项目可以进行核查
                        vo.setCanVerify(Boolean.TRUE);
                    }
                    vo.setGroupId(groupId);
                    return vo;
                })
                .collect(Collectors.toList());
        return PageVo.of(res, page.getTotal());
    }

    @Transactional(rollbackFor = Exception.class)
    public String submitReAppraisal(ProjectAppraisalDTO param) {
        UserInfoDetails userDetail = LoginUserUtil.loginUserDetail();
        String userIdStr = String.valueOf(userDetail.getMhUserId());
        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::getProjectId, appraisalProjectId)
                .eq(PerformanceAppraisalProject::getProjectCode, appraisalProjectCode));

        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.RE_APPRAISAL.getCode());
            scoreInfo.setTemplateDetailId(templateDetail.getId());
            scoreInfo.setTemplateId(templateDetail.getTemplateId());
            scoreInfo.setAppraisalUserId(userIdStr);
            scoreInfo.setAppraisalUserName(username);
            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 reAppraisalTotalScore = appraisalInfoList.stream()
                    .map(ProjectAppraisalInfoDTO::getScore)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal lastReappraisalTotalScore;
            // 判断项目所在分组内其他复评人员是否已经打分
            if (Objects.nonNull(appraisalProject.getReAppraisalTotalScore())) {
                // 已经进行了复评，计算两个分值的平均分
                BigDecimal add = reAppraisalTotalScore.add(appraisalProject.getReAppraisalTotalScore());
                lastReappraisalTotalScore = add.divide(BigDecimal.valueOf(2));
            } else {
                // 还没有进行过复评
                lastReappraisalTotalScore = reAppraisalTotalScore;
            }
            appraisalProject.setReAppraisalTotalScore(lastReappraisalTotalScore);
            // 取最新地复评打分时间
            appraisalProject.setReAppraisalScoreTime(LocalDateTime.now());
            // 判断当前复评人是否为该评价项目所在分组的复评人员中的最后一个复评人
            judgeCompleteReAppraisal(group, appraisalProject);
            appraisalProject.setUpdateOn(LocalDateTime.now());
            appraisalProject.setUpdateBy(username);
            performanceAppraisalProjectService.updateById(appraisalProject);
            return "提交成功";
        }
        return "提交失败";
    }

    private void judgeCompleteReAppraisal(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.RE_APPRAISAL.getCode()));
        // 判断打分人员是否为分组内的复评人员
        if (CollUtil.isNotEmpty(scoreInfoList)) {
            Set<String> users = scoreInfoList.stream().map(PerformanceAppraisalScoreInfo::getAppraisalUserId).collect(Collectors.toSet());
            if (CollUtil.isNotEmpty(users)) {
                String reAppraisalUsers = group.getReAppraisalUsers();
                String join = String.join(StrPool.COMMA, users);
                if (join.equals(reAppraisalUsers)) {
                    // 标记项目完成复评
                    appraisalProject.setIsCompleteReAppraisal(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 = null;
        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;
        }
        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);
        Assert.notEmpty(templates, "该项目匹配不到指标模板，请返回上一页或者刷新重试。");
        if (templates.size() > 1) {
            throw new BizException("当前项目匹配到多个模板，请返回模板库检查模板配置!");
        }
        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()))
                .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());

        // 筛选出所有打分的三级指标模板详情ID
        for (PerformanceAppraisalScoreInfo scoreInfo : scoreInfoList) {
            HashMap<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());
            }

            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));
        }
        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, Lists.newArrayList()))
                    .sheet(fileName)
                    .doWrite(ExcelUtils.convertData(headList, exportDataList));
        } catch (IOException e) {
            throw new BizException(e.getMessage());
        }
    }
}
