package thyyxxk.webserver.service.targetmanagement;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.highreport.HighReportDao;
import thyyxxk.webserver.dao.his.targetmanagement.TableDisplayInfoDao;
import thyyxxk.webserver.dao.his.targetmanagement.TableGroupInfoDao;
import thyyxxk.webserver.dao.his.targetmanagement.TargetManagementDao;
import thyyxxk.webserver.dao.his.targetmanagement.ZbReportCycleDao;
import thyyxxk.webserver.dao.his.targetmanagement.ZbReportCycleScoreDao;
import thyyxxk.webserver.dao.his.targetmanagement.ZbZdBaseInfoDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.archive.ArchiveUpload;
import thyyxxk.webserver.entity.highreport.HighReportDto;
import thyyxxk.webserver.entity.highreport.ReportBaseInfo;
import thyyxxk.webserver.entity.highreport.ReportType;
import thyyxxk.webserver.entity.highreport.TableDisplayInfo;
import thyyxxk.webserver.entity.highreport.TableGroupInfo;
import thyyxxk.webserver.entity.highreport.ZbReportCycle;
import thyyxxk.webserver.entity.highreport.ZbReportCycleScore;
import thyyxxk.webserver.entity.highreport.ZbReportMonthScore;
import thyyxxk.webserver.entity.highreport.ZbReportResult;
import thyyxxk.webserver.entity.highreport.ZbReportScoreDto;
import thyyxxk.webserver.entity.highreport.ZdReportType;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.targetmanagement.TargetDictTree;
import thyyxxk.webserver.entity.targetmanagement.TargetManagement;
import thyyxxk.webserver.entity.targetmanagement.ZbZdBaseInfo;
import thyyxxk.webserver.service.archive.ArchiveServer;
import thyyxxk.webserver.service.hutoolcache.UserCache;
import thyyxxk.webserver.utils.DateUtil;
import thyyxxk.webserver.utils.DecimalUtil;
import thyyxxk.webserver.utils.ReportUtil;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;
import thyyxxk.webserver.utils.TargetDictTreeUtil;
import thyyxxk.webserver.utils.TokenUtil;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 指标管理
 * @Author: hsh
 * @CreateTime: 2023-05-30  16:52
 * @Version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TargetManagementService {

    private final TargetManagementDao dao;

    private final ZbZdBaseInfoDao zbZdDao;

    private final HighReportDao reportDao;

    private final UserCache userCache;

    private final TableGroupInfoDao tableDao;

    private final TableDisplayInfoDao displayDao;

    private final ZbReportCycleDao cycleDao;

    private final ZbReportCycleScoreDao scoreDao;

    private final ArchiveServer archiveServer;

    @Value("${is-prod}")
    private boolean isProd;
    private static final String TARGET_PATH = "/testZb";

    /**
     * @description: 查询指标字典基本信息
     * @author: hsh
     * @date: 2023/5/30 17:27
     * @param: [dto]
     * @return: ResultVo<List<ZbZdBaseInfo>>
     **/
    public ResultVo<List<ZbZdBaseInfo>> selectTargetDict(TargetManagement dto) {
        List<ZbZdBaseInfo> list = zbZdDao.selectZbZdBaseInfo(dto);
        return ResultVoUtil.success(list);
    }

    /**
     * @description: 根据id查询指标字典基本信息
     * @author: hsh
     * @date: 2023/7/5 10:58
     * @param: [dto]
     * @return: ResultVo<ZbZdBaseInfo>
     **/
    public ResultVo<ZbZdBaseInfo> selectTargetDictById(TargetManagement dto) {
        ZbZdBaseInfo info = zbZdDao.selectZbZdBaseInfoById(dto);
        return ResultVoUtil.success(info);
    }

    /**
     * @description: 查询指标树
     * @author: hsh
     * @date: 2023/6/2 11:11
     * @param: [dto]
     * @return: ResultVo<List<TargetDictTree>>
     **/
    public ResultVo<List<TargetDictTree>> selectTargetDictTree(TargetManagement dto) {
        List<TargetDictTree> zbList = zbZdDao.selectTargetDictTree(dto);
        // 组装指标树
        List<TargetDictTree> list = assemblyTargetDictTree(zbList, dto.getDept());
        return ResultVoUtil.success(list);
    }

    /**
     * @description: 组装指标字典树
     * @author: hsh
     * @date: 2023/6/2 9:37
     * @param: [list, zbList]
     * @return: void
     **/
    private List<TargetDictTree> assemblyTargetDictTree(@NotNull List<TargetDictTree> zbList, String dept) {
        // 创建树形结构（数据集合作为参数）
        TargetDictTreeUtil treeBuild = new TargetDictTreeUtil(zbList, dept);
        // 原查询结果转换树形结构
        return treeBuild.buildTree();
    }

    public ResultVo<Map<String, Object>> saveTargetDict(ZbZdBaseInfo dto) {
        // 验证sql是否有问题
        String msg = sqlCheckAndVerify(dto);

        // 补充责任科室以及责任人


        if(StringUtil.notBlank(msg)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, msg);
        }

        TargetManagement target = new TargetManagement();
        target.setId(dto.getId());
        target.setPid(dto.getPid());
        ZbZdBaseInfo zdBaseInfo = zbZdDao.selectZbZdBaseInfoById(target);
        int num;
        if(zdBaseInfo != null){
            num = zbZdDao.updateZbZdBaseInfo(dto);
        } else {
            num = zbZdDao.saveZbZdBaseInfo(dto);
        }

        if(num > 0){
            Map<String, Object> m = new HashMap<>();
            m.put("1", "保存指标字典成功！");
            return ResultVoUtil.success(m);
        } else {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标字典失败！");
        }
    }

    /**
     * @description: 更新指标字典数据
     * @author: hsh
     * @date: 2023/6/2 9:29
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> updateTargetDict(ZbZdBaseInfo dto) {
        // 验证sql是否有问题
        String msg = sqlCheckAndVerify(dto);
        if(StringUtil.notBlank(msg)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, msg);
        }

        int num = zbZdDao.updateZbZdBaseInfo(dto);
        if(num > 0){
            return ResultVoUtil.success(ExceptionEnum.SUCCESS, "更新指标字典成功！");
        } else {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "更新指标字典失败");
        }
    }

    /**
     * @description: 验证查询sql是否正确
     * @author: hsh
     * @date: 2023/5/31 10:11
     * @param: [dto]
     * @return: String 错误信息
     **/
    private String sqlCheckAndVerify(@NotNull ZbZdBaseInfo dto) {
        String sqlChild = dto.getCalcChild();
        String sqlMom = dto.getCalcMom();
        String message = "";
        if(StringUtil.isBlank(dto.getId())){
            message = "id不存在，请检查！";
        }
        if(StringUtil.isBlank(dto.getName())){
            message = "指标名称不存在，请检查！";
        }
        if(StringUtil.isBlank(dto.getPid())){
            message = "父id不存在，请检查！";
        }
        if(dto.getScore() == null || dto.getScore().doubleValue() < 0){
            message = "指标总分不存在或者小于0，请检查！";
        }
        String isLeaf = dto.getIsLeaf();
        if("1".equals(isLeaf)){
            // 叶子节点要求填写责任科室，责任人
            if(StringUtil.isBlank(dto.getDeptCode())){
                message = "责任科室未选择，请检查！";
            }
            if(StringUtil.isBlank(dto.getOpId())){
                message = "责任人未选择，请检查！";
            }
            if(StringUtil.isBlank(dto.getDefinition())){
                message = "指标定义不存在，请检查！";
            }
            if(StringUtil.isBlank(dto.getMethod())){
                message = "指标评审方法不存在，请检查！";
            }
            if(StringUtil.isBlank(dto.getScoreRule())){
                message = "指标计分细则不存在，请检查！";
            }
            if(StringUtil.notBlank(sqlChild)){
                if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild))){
                    message = "保存指标字典失败,分子" + ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild);
                }
            }
            if(StringUtil.notBlank(sqlMom)){
                if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(sqlMom))){
                    message = "保存指标字典失败,分母" + ReportUtil.sqlCheckAndVerifyByKeyword(sqlMom);
                }
            }
        }
        return message;
    }

    /**
     * @description: 查询分子分母指标报表结果
     * @author: hsh
     * @date: 2023/7/6 9:31
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> targetSqlExecute(TargetManagement dto) {
        String sqlChild = dto.getCalcChild();
        String sqlMom = dto.getCalcMom();
        if(StringUtil.isBlank(sqlChild)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "计算-分子sql不存在，请检查！");
        } else {
            if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild))){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "分子" + ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild));
            }
        }
        if(StringUtil.notBlank(sqlMom)){
            if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(sqlMom))){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "分母" + ReportUtil.sqlCheckAndVerifyByKeyword(sqlMom));
            }
        }

        // 转换sql的查询条件
        Map<String, ReportBaseInfo> map = ReportUtil.assertReportForTarget(dto);
        ReportBaseInfo r1 = map.get("calcChild");
        ReportBaseInfo r2 = map.get("calcMom");

        // 转换查询dto
        HighReportDto d = ReportUtil.TargetManagementConvertHighReportDto(dto);

        // 计算结果
        Map<String, Object> resultMap = new HashMap<>();
        String child = null;
        String mom = null;
        if(r1 != null){
            String childSql = ReportUtil.callSqlFormat(d, r1.getBaseSql(), r1.getGatherSql(), null, null, null);
            child = dao.targetSqlExecute(childSql);
        }
        if(r2 != null){
            String momSql = ReportUtil.callSqlFormat(d, r2.getBaseSql(), r2.getGatherSql(), null, null, null);
            mom = dao.targetSqlExecute(momSql);
        }

        if (StringUtil.notBlank(child)) {
            resultMap.put("r1", child);
        } else {
            resultMap.put("r1", "无");
        }
        if (StringUtil.notBlank(mom)) {
            resultMap.put("r2", mom);
            if(StringUtil.notBlank(child)){
                resultMap.put("r3", DecimalUtil.divide(new BigDecimal(child), new BigDecimal(mom), 4));
            } else {
                resultMap.put("r3", "无");
            }
        } else {
            resultMap.put("r2", "无");
            if (StringUtil.notBlank(child)) {
                resultMap.put("r3", child);
            } else {
                resultMap.put("r3", "无");
            }
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 根据id查询分子分母指标报表结果
     * @author: hsh
     * @date: 2023/7/6 9:30
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<List<Map<String, Object>>> targetSqlExecuteById(TargetManagement dto) {
        ReportBaseInfo reportChild = dao.selectReportBaseInfoByCalcId(dto.getChildId());
        ReportBaseInfo reportMom = dao.selectReportBaseInfoByCalcId(dto.getMomId());

        if(null ==  reportChild && null == reportMom){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "【" + dto.getName() + "】计算-分子和分母指标都不存在，请指定！");
        }

        if(null ==  dto.getStartTime() || null == dto.getEndTime()){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "【" + dto.getName() + "】查询时间不存在，请检查！");
        }

        // 处理时间（1.时间跨度需要一年一年查询结果； 2.查询时间格式为年月日时分秒: yyyy-MM-DD 24H:mm:ss）
        int start = Integer.parseInt(dto.getStartTime());
        int end = Integer.parseInt(dto.getEndTime());
        // 超过4年只选择4年数据查询
        int endIndex = start + 3;

        List<Map<String, Object>> list = new ArrayList<>();
        for(int i = start; i <= end; i++){
            Map<String, Object> resultMap = new HashMap<>();
            if(i > endIndex){
                break;
            }
            int s = i - start + 1;

            String ks = i + "-01-01 00:00:00";
            String js = i + "-12-31 23:59:59";
            dto.setStartTime(ks);
            dto.setEndTime(js);
            HighReportDto d = ReportUtil.TargetManagementConvertHighReportDto(dto);
            // 计算结果
            String child = null;
            String mom = null;
            if(reportChild != null){
                String childSql = ReportUtil.callSqlFormat(d, reportChild.getBaseSql(), reportChild.getGatherSql(), null, null, null);
                child = dao.targetSqlExecute(childSql);
            }
            if(reportMom != null){
                String momSql = ReportUtil.callSqlFormat(d, reportMom.getBaseSql(), reportMom.getGatherSql(), null, null, null);
                mom = dao.targetSqlExecute(momSql);
            }

            resultMap.put("id", dto.getId());
            resultMap.put("pid", dto.getPid());
            resultMap.put("index", s);
            // 数据统计来源（1：sql统计；2：手动填写输入。）
            resultMap.put("dataType", "1");
            // 统计年份
            resultMap.put("year", i);
            resultMap.put("childLabel", i + "年分子结果");
            resultMap.put("momLabel", i + "年分母结果");
            resultMap.put("calcLabel", i + "年分子/分母的结果");
            if (StringUtil.notBlank(child)) {
                resultMap.put("childResult", child);
            } else {
                resultMap.put("childResult", "无");
            }
            if (StringUtil.notBlank(mom)) {
                resultMap.put("momResult", mom);
                if(StringUtil.notBlank(child)){
                    resultMap.put("calcResult", DecimalUtil.divide(new BigDecimal(child), new BigDecimal(mom), 4));
                } else {
                    resultMap.put("calcResult", "无");
                }
            } else {
                resultMap.put("momResult", "无");
                if (StringUtil.notBlank(child)) {
                    resultMap.put("calcResult", child);
                } else {
                    resultMap.put("calcResult", "无");
                }
            }
            list.add(resultMap);
        }
        return ResultVoUtil.success(list);
    }

    public ResultVo<Map<String, Object>> targetSqlSave(TargetManagement dto) {
        String sqlChild = dto.getCalcChild();
        String sqlMom = dto.getCalcMom();
        if(StringUtil.notBlank(sqlChild)) {
            if (!sqlChild.contains("/") && !(sqlChild.contains("select") || sqlChild.contains("SELECT"))) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "分子sql语句不合法，请检查！");
            }
            if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild))){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "分子" + ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild));
            }
        }
        if(StringUtil.notBlank(sqlMom)){
            if (!sqlMom.contains("/") && !(sqlMom.contains("select") || sqlMom.contains("SELECT"))) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "分母sql语句不合法，请检查！");
            }
            if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild))){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "分母" + ReportUtil.sqlCheckAndVerifyByKeyword(sqlChild));
            }
        }
        try {
            int num = 0;
            // 获取指标字典sql信息
            Map<String, ReportBaseInfo> map = ReportUtil.assertReportForTarget(dto);

            // 查询指标字典是否以及存在分子分母的sql指标报表信息
            ZbZdBaseInfo info = zbZdDao.selectZbZdBaseInfoById(dto);
            if(null != map.get("calcChild")){
                // 已经配置分子sql指标报表信息
                ReportBaseInfo r1 = map.get("calcChild");
                // 更新分子指标报表的sql信息
                if(StringUtil.notBlank(info.getChildId())){
                    dao.deleteReportBaseInfoById(r1.getReportId());
                } else {
                    // 保存分子指标报表的id
                    zbZdDao.updateZbZdBaseInfoCalcId(dto.getId(), dto.getPid() ,r1.getReportId(), null);
                }
                num += dao.insert(r1);
            }
            if(null != map.get("calcMom")){
                ReportBaseInfo r2 = map.get("calcMom");
                if(StringUtil.notBlank(info.getMomId())){
                    dao.deleteReportBaseInfoById(r2.getReportId());
                } else {
                    // 保存分母指标报表的id
                    zbZdDao.updateZbZdBaseInfoCalcId(dto.getId(), dto.getPid(), null, r2.getReportId());
                }
                num += dao.insert(r2);
            }
            Map<String, Object> resultMap = new HashMap<>();
            if(num == 0){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标sql以及报表失败！");
            }
            resultMap.put("cg", "保存指标sql以及报表成功！");
            return ResultVoUtil.success(resultMap);
        } catch (Exception e) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标sql以及报表失败！");
        }

    }

    /**
     * @description: 根据id和父id删除指标字典
     * @author: hsh
     * @date: 2023/6/21 11:05
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> deleteTargetDictById(TargetManagement dto) {
        if(StringUtil.isBlank(dto.getId())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "id不存在，请检查！");
        }
        if(StringUtil.isBlank(dto.getPid())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "父id不存在，请检查！");
        }
        Map<String, Object> resultMap = new HashMap<>();
        int num = zbZdDao.deleteTargetDictById(dto.getId(), dto.getPid());
        if(num == 0){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "删除指标字典失败！");
        }
        resultMap.put("cg", "删除指标字典成功！");
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 查询指标字典的分子分母sql
     * @author: hsh
     * @date: 2023/6/30 15:19
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> selectTargetSql(TargetManagement dto) {
        if (StringUtil.isBlank(dto.getId())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "id不存在，请检查！");
        }
        if (StringUtil.isBlank(dto.getPid())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "父id不存在，请检查！");
        }
        Map<String, Object> resultMap = new HashMap<>();
        ReportBaseInfo reportChild = dao.selectReportBaseInfoByCalcId(dto.getChildId());
        ReportBaseInfo reportMom = dao.selectReportBaseInfoByCalcId(dto.getMomId());
        resultMap.put("reportChild", reportChild);
        resultMap.put("reportMom", reportMom);
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 查询指标字典的分子分母sql的详细内容
     * @author: hsh
     * @date: 2023/6/30 15:20
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> selectTargetSqlDetail(TargetManagement dto) {
        if (StringUtil.isBlank(dto.getId())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "id不存在，请检查！");
        }
        if (StringUtil.isBlank(dto.getPid())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "父id不存在，请检查！");
        }
        Map<String, Object> resultMap = new HashMap<>();

        ReportBaseInfo reportBaseInfo = dao.selectReportBaseInfoById(dto.getId(), dto.getPid());
        if (reportBaseInfo == null) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "查询指标不存在！");
        }
        resultMap.put("report", reportBaseInfo);
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 查询指标报表数据
     * @author: hsh
     * @date: 2023/7/7 10:19
     * @param: [dto]
     * @return: ResultVo<List<Map<String, Object>>>
     **/
    public ResultVo<List<Map<String, Object>>> selectReportDictTree(HighReportDto dto){
        // 查询所有使用的指标报表数据
        List<ReportBaseInfo> list = reportDao.selectReportDictTree();

        // 查询指标类型
        List<ZdReportType> reportTypes = reportDao.selectReportType();
        Map<String, ZdReportType> typeMap = new HashMap<>();
        for (ZdReportType zdReport : reportTypes) {
            typeMap.put(zdReport.getReportType(), zdReport);
        }

        Map<String, List<ReportBaseInfo>> reportMap = list.stream().collect(Collectors.groupingBy(ReportBaseInfo::getReportType));
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> rootMap = new HashMap<>();
        rootMap.put("id", "zbJc");
        rootMap.put("pid", "0");
        rootMap.put("label", "指标监测");
        List<Map<String, Object>> rootChildList = new ArrayList<>();
        for(Map.Entry<String, List<ReportBaseInfo>> entry: reportMap.entrySet()){
            Map<String, Object> map = new HashMap<>();
            List<ReportBaseInfo> l = entry.getValue();
            String type = entry.getKey();
            String reportName = typeMap.get(type) == null ? "" : typeMap.get(type).getReportLabel();
            if(StringUtil.notBlank(reportName)){
                map.put("id", type);
                map.put("pid", "zbJc");
                map.put("label", reportName);
                map.put("sort", typeMap.get(type).getSort());
            } else {
                map.put("id", type);
                map.put("label", ReportType.QT.getName());
                map.put("sort", "999");
            }
            map.put("pid", "zbJc");
            List<Map<String, Object>> child = AssertReportTree(l, type);
            map.put("children", child);
            rootChildList.add(map);
        }
        rootMap.put("children", rootChildList.stream().sorted(Comparator.comparingInt(e -> Integer.parseInt(String.valueOf(e.get("sort"))))).collect(Collectors.toList()));
        resultList.add(rootMap);
        return ResultVoUtil.success(resultList);
    }

    /**
     * @description: 组装指标报表树数据
     * @author: hsh
     * @date: 2023/7/7 11:34
     * @param: [list, type]
     * @return: List<Map<String, Object>>
     **/
    private List<Map<String, Object>> AssertReportTree(List<ReportBaseInfo> list, String type) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for(ReportBaseInfo info : list){
            Map<String, Object> map = new HashMap<>();
            map.put("id", info.getReportId());
            map.put("pid", type);
            map.put("label", info.getReportName());
            resultList.add(map);
        }
        return resultList;
    }

    /**
     * @description: 根据报表id作废指标报表
     * @author: hsh
     * @date: 2023/7/7 16:13
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> deleteReportDictById(TargetManagement dto) {
        if (StringUtil.isBlank(dto.getId())) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "id不存在，请检查！");
        }
        Map<String, Object> resultMap = new HashMap<>();
        int num = reportDao.updateReportDictById(dto.getId());
        if (num == 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "作废指标报表失败！");
        }
        resultMap.put("cg", "作废指标报表成功！");
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 查询指标报表信息
     * @author: hsh
     * @date: 2023/7/7 16:52
     * @param: [dto]
     * @return: ResultVo<List<ReportBaseInfo>>
     **/
    public ResultVo<List<ReportBaseInfo>> selectReportDict(HighReportDto dto) {
        List<ReportBaseInfo> list = reportDao.selectReportDict(dto);
        return ResultVoUtil.success(list);
    }

    /**
     * @description: 查询指标报表类型字典信息
     * @author: hsh
     * @date: 2023/7/11 16:26
     * @param: []
     * @return: ResultVo<List<ZdReportType>>
     **/
    public ResultVo<List<ZdReportType>> selectReportType() {
        List<ZdReportType> list = reportDao.selectReportType();
        return ResultVoUtil.success(list);
    }

    /**
     * @description: 查询报表sql统计总计结果，用来验证报表sql是否编写正确
     * @author: hsh
     * @date: 2023/7/12 16:52
     * @param: [dto]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> reportSqlExecute(TargetManagement dto){
        if(StringUtil.isBlank(dto.getBaseSql())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "基础sql不存在，请检查！");
        }
        if(StringUtil.isBlank(dto.getGatherSql())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "聚合sql不存在，请检查！");
        }
        if(StringUtil.notBlank(ReportUtil.sqlCheckAndVerifyByKeyword(dto.getBaseSql()))){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, ReportUtil.sqlCheckAndVerifyByKeyword(dto.getBaseSql()));
        }
        Map<String, Object> resultMap = new HashMap<>();
        HighReportDto d = ReportUtil.TargetManagementConvertHighReportDto(dto);
        String calcSql = ReportUtil.callSqlFormat(d, dto.getBaseSql(), dto.getGatherSql(), null, null, null);
        String result = dao.targetSqlExecute(calcSql);
        if(StringUtil.notBlank(result)){
            resultMap.put("r1", result);
        } else {
            resultMap.put("r1", "无");
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 查询报表分组类型
     * @author: hsh
     * @date: 2023/7/19 15:25
     * @param: [dto]
     * @return: ResultVo<TableGroupInfo>
     **/
    public ResultVo<TableGroupInfo> selectReportLevel(HighReportDto dto){

        TableGroupInfo info = reportDao.selectTableGroupInfoByLevel(dto.getReportId(), dto.getLevel());
        if(info == null){
            // 查不到给他默认报表分组类型
            if(ReportType.GROUP_KS.getCode().equals(dto.getLevel())) {
                info = reportDao.selectTableGroupInfoByLevel(ReportType.GROUP_KS.getCode(), dto.getLevel());
            } else if(ReportType.GROUP_ZB.getCode().equals(dto.getLevel())) {
                info = reportDao.selectTableGroupInfoByLevel(ReportType.GROUP_ZB.getCode(), dto.getLevel());
            }
        }

        if(null == info){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标分组配置不存在，请检查！");
        }

        return ResultVoUtil.success(info);
    }

    /**
     * @description: 保存指标结果
     * @author: hsh
     * @date: 2023/7/19 15:27
     * @param: [list]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> saveTargetReportResult(List<ZbReportResult> list){
        Map<String, Object> resultMap = new HashMap<>();

        if(list == null || list.isEmpty()){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标结果记录不存在，请检查！");
        }

        UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
        for (ZbReportResult result : list) {
            result.setOp(user.getName() != null ? user.getName().trim() : null);
            result.setOpId(user.getCodeRs());
            result.setOpTime(DateUtil.now());

            // 入库或更新操作
            int n = updateAndSaveTargetReportResult(result);
            if (n <= 0) {
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标结果失败！");
            }
        }
        resultMap.put("cg", "保存指标结果成功");
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 更新单个指标结果
     * @Author hsh
     * @param result 指标结果
     * @return map
     * @Date 2024/12/11 17:21
     */
    public ResultVo<Map<String, Object>> saveTargetReportResultSinge(ZbReportResult result){
        Map<String, Object> resultMap = new HashMap<>();

        if(result == null || StringUtil.isBlank(result.getYear())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标结果记录不存在，请检查！");
        }

        UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
        result.setOp(user.getName() != null ? user.getName().trim() : null);
        result.setOpId(user.getCodeRs());
        result.setOpTime(DateUtil.now());

        // 入库或更新操作
        int n = updateAndSaveTargetReportResult(result);
        if (n <= 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "更新指标结果失败！");
        }
        resultMap.put("cg", "更新指标结果成功");
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 根据id，pid和年度删除指标结果
     * @Author hsh
     * @param result id，pid和年度等指标结果信息
     * @return map
     * @Date 2024/12/11 17:34
     */
    public ResultVo<Map<String, Object>> delTargetReportResultByYear(ZbReportResult result){
        Map<String, Object> resultMap = new HashMap<>();

        if(result == null || StringUtil.isBlank(result.getId()) || StringUtil.isBlank(result.getPid()) || StringUtil.isBlank(result.getYear())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标结果记录不存在，请检查！");
        }

        // 根据id，pid和年度删除指标结果
        int n = reportDao.deleteReportResultById(result.getId(), result.getPid(), result.getYear());
        if (n <= 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "删除指标结果失败！");
        }
        resultMap.put("cg", "删除指标结果成功");
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 先删后保存数据
     * @author: hsh
     * @date: 2023/7/21 10:06
     * @param: [result]
     * @return: int
     **/
    private int updateAndSaveTargetReportResult(ZbReportResult result) {
        if(result == null){
            return 0;
        }
        ZbReportResult r = reportDao.selectReportResultByYear(result.getId(), result.getPid(), result.getYear());
        if(r != null){
            reportDao.deleteReportResultById(result.getId(), result.getPid(), result.getYear());
        }
        return reportDao.saveTargetReportResult(result);
    }

    /**
     * @description: 查询指标报表结果
     * @author: hsh
     * @date: 2023/7/21 11:21
     * @param: [dto]
     * @return: ResultVo<List<ZbReportResult>>
     **/
    public ResultVo<List<ZbReportResult>> selectTargetReportResult(TargetManagement dto) {
        List<ZbReportResult> list = reportDao.selectReportResultById(dto.getId(), dto.getPid(), dto.getStartTime(), dto.getEndTime());
        return ResultVoUtil.success(list);
    }

    /**
     * @description: 保存/更新指标报表基本信息
     * @author: hsh
     * @date: 2023/7/27 9:55
     * @param: [info]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> saveReportBaseInfo(ReportBaseInfo info) {
        Map<String, Object> resultMap = new HashMap<>();

        if(info == null || StringUtil.isBlank(info.getReportId())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "报表详情为空，保存指标详情失败!");
        }

        ReportBaseInfo report = reportDao.selectReportPortalMenu(info.getReportId(), null, null);
        if (report != null) {
            reportDao.deleteReportBaseInfoById(info.getReportId());
        }

        // 手工指标拼接基础sql
        if(ReportUtil.SG.equals(info.getReportType())){
            String bSql = info.getBaseSql();
            info.setBaseSql("select " + bSql + " as sg");
            UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
            // 做一个标识
            info.setDisplayType(user.getCode().trim());
        }

        int n = dao.insert(info);
        if (n <= 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标详情失败!");
        }

        resultMap.put("cg", "保存指标详情成功!");
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @description: 保存/更新指标分组信息
     * @author: hsh
     * @date: 2023/9/26 16:19
     * @param: [info]
     * @return: ResultVo<Map<String,Object>>
     **/
    public ResultVo<Map<String, Object>> saveTableGroupInfo(TableGroupInfo info) {
        Map<String, Object> resultMap = new HashMap<>();

        if(info == null || StringUtil.isBlank(info.getReportId())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标分组信息为空，保存指标分组信息失败!");
        }

        if(ReportType.GROUP_KS.getCode().equals(info.getReportId()) || ReportType.GROUP_ZB.getCode().equals(info.getReportId())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标固定分组信息不允许修改/删除!");
        }

        TableGroupInfo table = reportDao.selectTableGroupInfo(info.getReportId(), null);
        if (table != null) {
            reportDao.deleteTableGroupInfoById(info.getReportId());
        }

        int n = tableDao.insert(info);
        if (n <= 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标分组信息失败!");
        }

        resultMap.put("cg", "保存指标详情成功!");
        return ResultVoUtil.success(resultMap);
    }

    public ResultVo<List<Map<String, Object>>> selectReportLevelDict() {
        List<Map<String, Object>> list = tableDao.selectReportLevelDict();
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 查询指标报表的所有id以及名称（包括增加的手工数据指标）
     * @Author hsh
     * @param reportType 指标报表类型
     * @return list
     * @Date 2024/4/8 10:15
     */
    public ResultVo<List<Map<String, Object>>> selectTargetZbReportId(String reportType) {
        List<Map<String, Object>> list = dao.selectTargetZbReportId(reportType);
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 查询指标报表详情配置
     * @Author hsh
     * @param info 指标报表信息
     * @return list
     * @Date 2024/4/8 10:16
     */
    public ResultVo<List<TableDisplayInfo>> selectTableDisplay(ReportBaseInfo info) {
        return ResultVoUtil.success(displayDao.selectTableDisplayByReportId(info.getReportId(), "patient"));
    }

    /**
     * @Description 更新指标报表详情配置信息
     * @Author hsh
     * @param info 指标报表详情配置信息
     * @return map
     * @Date 2024/4/8 10:16
     */
    public ResultVo<Map<String, Object>> saveTableDisplay(TableDisplayInfo info){

        if(null == info || info.getReportId() == null || info.getLevelId() == null || info.getProp() == null){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表详情配置信息不存在，请检查！");
        }

        Map<String, Object> resultMap = new HashMap<>();
        String reportId = info.getReportId();
        String levelId = info.getLevelId();
        String prop = info.getProp();
        TableDisplayInfo displayInfo = displayDao.selectTableDisplayByProp(reportId, levelId, prop);

        int num;
        try{
            if(null != displayInfo){
                num = displayDao.updateTableDisplayByProp(info);
            } else {
                num = displayDao.insert(info);
            }
            if(num == 0){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标报表详情配置失败！");
            }
            resultMap.put("cg", "保存指标报表详情配置成功！");
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标报表详情配置失败！");
        }
    }

    /**
     * @Description 根据指标报表详情配置prop删除指标报表详情配置信息
     * @Author hsh
     * @param reportId,levelId,prop 报表id,报表等级id,报表配置prop属性
     * @return map
     * @Date 2024/4/8 10:17
     */
    public ResultVo<Map<String, Object>> delTableDisplayByProp(String reportId, String levelId, String prop) {
        if(reportId == null || levelId == null || prop == null){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表详情配置信息不存在，请检查！");
        }

        Map<String, Object> resultMap = new HashMap<>();
        try{
            int num = displayDao.delTableDisplayByProp(reportId, levelId, prop);
            if(num == 0){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "删除指标报表详情配置信息失败！");
            }
            resultMap.put("cg", "删除指标报表详情配置信息成功！");
            return ResultVoUtil.success(resultMap);
        } catch(Exception e){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "删除指标报表详情配置信息失败！");
        }
    }

    /**
     * @Description 查询指标年度周期明细
     * @Author hsh
     * @return list 指标年度周期明细
     * @Date 2024/8/15 9:41
     */
    public ResultVo<List<ZbReportCycle>> selectScoreCycle(){
        List<ZbReportCycle> list = cycleDao.selectScoreCycle();
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 更新指标周期得分-自评分
     * @Author hsh
     * @param score 指标周期得分详情
     * @return map
     * @Date 2024/8/15 10:19
     */
    public ResultVo<Map<String, Object>> updateTargetReportScore(ZbReportCycleScore score){
        Map<String, Object> resultMap = new HashMap<>();
        String id = score.getId();
        String reportCycle = score.getReportCycle();
        if(StringUtil.isBlank(id) || StringUtil.isBlank(reportCycle)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标id或年度周期信息不全，请检查！");
        }
        ZbReportCycleScore s = scoreDao.selectZbReportCycleScoreByReportCycle(id, reportCycle);
        UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
        score.setAuthorId(user.getCode().trim());
        score.setAuthorName(user.getName().trim());
        score.setFlag("1");
        int num;
        if(null != s){
            if("2".equals(s.getFlag())){
                return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标已经内审不能再次更新指标周期自评分，请确认！");
            }
            num = scoreDao.updateTargetReportScoreById(score);
        } else {
            num = scoreDao.insert(score);
        }
        if(num > 0){
            resultMap.put("cg", "更新指标周期自评分成功！");
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 更新指标周期得分-内审得分
     * @Author hsh
     * @param score 指标周期得分详情
     * @return map
     * @Date 2024/12/30 16:45
     */
    public ResultVo<Map<String, Object>> updateTargetReportScoreByShf(ZbReportCycleScore score){
        Map<String, Object> resultMap = new HashMap<>();
        String id = score.getId();
        String reportCycle = score.getReportCycle();
        if(StringUtil.isBlank(id) || StringUtil.isBlank(reportCycle)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标id或年度周期信息不全，请检查！");
        }
        ZbReportCycleScore s = scoreDao.selectZbReportCycleScoreByReportCycle(id, reportCycle);
        if(null == s){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表得分信息不存在，请检查！");
        }
        if("3".equals(s.getFlag())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表退审后未进行自评分不能进行审核，请检查！");
        }
        if(!("1".equals(s.getFlag()) || "2".equals(s.getFlag()))){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表未进行自评分不能进行审核，请检查！");
        }
        UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
        score.setMainId(user.getCode().trim());
        score.setMainName(user.getName().trim());
        int num = scoreDao.updateTargetReportScoreById(score);
        if(num > 0){
            resultMap.put("cg", "更新指标周期内审得分成功！");
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 取消审核指标周期得分-内审得分
     * @Author hsh
     * @param score 指标周期得分详情
     * @return map
     * @Date 2024/12/30 16:45
     */
    public ResultVo<Map<String, Object>> returnTargetReportScoreByShf(ZbReportCycleScore score){
        Map<String, Object> resultMap = new HashMap<>();
        String id = score.getId();
        String reportCycle = score.getReportCycle();
        if(StringUtil.isBlank(id) || StringUtil.isBlank(reportCycle)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标id或年度周期信息不全，请检查！");
        }
        ZbReportCycleScore s = scoreDao.selectZbReportCycleScoreByReportCycle(id, reportCycle);
        if(null == s){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表得分信息不存在，请检查！");
        }
        if(!"2".equals(s.getFlag())){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标报表未进行审核不能取消审核，请检查！");
        }
        UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
        score.setMainId(user.getCode().trim());
        score.setMainName(user.getName().trim());
        int num = scoreDao.returnTargetReportScoreById(score);
        if(num > 0){
            resultMap.put("cg", "取消审核指标周期内审得分成功！");
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 查询指标周期得分
     * @Author hsh
     * @param score 指标周期得分参数
     * @return score 指标周期得分
     * @Date 2024/8/15 15:47
     */
    public ResultVo<ZbReportCycleScore> selectTargetReportScore(ZbReportCycleScore score){
        String id = score.getId();
        String reportCycle = score.getReportCycle();
        if(StringUtil.isBlank(id) || StringUtil.isBlank(reportCycle)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标id或年度周期信息不全，请检查！");
        }
        ZbReportCycleScore zbScore = scoreDao.selectZbReportCycleScoreByReportCycle(id, reportCycle);
        return ResultVoUtil.success(zbScore);
    }

    /**
     * @Description 查询计算指标得分的权限
     * @Author hsh
     * @return map
     * @Date 2024/8/15 16:54
     */
    public ResultVo<Map<String, Object>> selectScoreCyclePermissions(){
        Map<String, Object> resultMap = new HashMap<>();
        String permissions = scoreDao.selectScoreCyclePermissions();
        resultMap.put("qx", permissions);
        if("N".equals(permissions)){
            // 不做计算指标得分的权限限制
            resultMap.put("permissions", 0);
        } else {
            UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
            String code = user.getCode().trim();
            if(permissions.contains(code)){
                // 有权限计算指标得分
                resultMap.put("permissions", 1);
            } else {
                // 没有权限计算指标得分
                resultMap.put("permissions", 2);
            }
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 查询指标得分情况
     * @Author hsh
     * @param dto 指标信息
     * @return list
     * @Date 2024/8/27 16:12
     */
    public ResultVo<List<Map<String, Object>>> selectTargetDictScoreById(ZbReportScoreDto dto){
        String pid = dto.getPid();
        String reportCycle = dto.getReportCycle();
        if(StringUtil.isBlank(pid) || StringUtil.isBlank(reportCycle)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标pid或年度周期信息不全，请检查！");
        }
        List<Map<String, Object>> list = scoreDao.selectTargetDictScoreByPid(pid, reportCycle);
        // 根据pid以及时间查询报表结果
        List<ZbReportResult> resultList = reportDao.selectReportResultByPid(pid, dto.getStartTime(), dto.getEndTime());
        Map<String, List<ZbReportResult>> resultMap = resultList.stream().collect(Collectors.groupingBy(ZbReportResult::getId, Collectors.toList()));

        for (Map<String, Object> map : list){
            String id = String.valueOf(map.get("id"));
            List<ZbReportResult> results = resultMap.get(id);
            if(null != results && !results.isEmpty()){
                for(ZbReportResult r : results){
                    map.put("t_" + r.getYear(), r.getCalcResult());
                }
            } else {
                String s = dto.getStartTime();
                int year = Integer.parseInt(s);
                for(int j = 0; j < 4; j++){
                    int f = year + j;
                    map.put("t_" + f, "");
                }
            }
        }
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 根据指标年度周期查询指标章节总分以及得分
     * @Author hsh
     * @param dto 指标年度周期
     * @return list
     * @Date 2024/8/30 8:58
     */
    public ResultVo<Map<String, Object>> selectTargetTotalScoreInfo(ZbReportScoreDto dto){
        String reportCycle = dto.getReportCycle();
        if(StringUtil.isBlank(reportCycle)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有年度周期，请检查！");
        }
        Map<String, Object> resultMap = new HashMap<>();
        // 查询第二级指标（pid是B）
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<ZbZdBaseInfo> ls = zbZdDao.selectTargetDictScoreBySecond("B");
        // 拼接总分
        Map<String, Object> m1 = new HashMap<>();
        // 拼接名字
        List<Map<String, Object>> mc = new ArrayList<>();
        m1.put("name", "总分");
        List<BigDecimal> zf = new ArrayList<>();
        for (ZbZdBaseInfo zb : ls){
            Map<String, Object> m2 = new HashMap<>();
            zf.add(zb.getScore());
            m2.put(zb.getId(), zb.getName());
            mc.add(m2);
        }
        m1.put("data", zf);
        resultList.add(m1);
        resultMap.put("mc", mc);
        // 查询得分
        List<ZbReportCycleScore> list = scoreDao.selectTargetDictScoreByReportCycle(reportCycle);
        if(null == list || list.isEmpty()){
            // 没有得分就只显示总分
            Map<String, Object> m3 = new HashMap<>();
            m3.put("name", "得分");
            m3.put("data", new int[]{0, 0, 0, 0, 0});
            resultList.add(m3);
            resultMap.put("infoData", resultList);
            return ResultVoUtil.success(resultMap);
        }
        BigDecimal B1 = BigDecimal.ZERO;
        BigDecimal B2 = BigDecimal.ZERO;
        BigDecimal B3 = BigDecimal.ZERO;
        BigDecimal B4 = BigDecimal.ZERO;
        BigDecimal B5 = BigDecimal.ZERO;
        for (ZbReportCycleScore score : list){
            String pid = score.getPid();
            String s = score.getReportScore();
            if(StringUtil.isBlank(s)){
                s = "0";
            }
            if(pid.startsWith("B1")){
                B1 = DecimalUtil.add(B1, new BigDecimal(s));
            } else if(pid.startsWith("B2")){
                B2 = DecimalUtil.add(B2, new BigDecimal(s));
            } else if(pid.startsWith("B3")){
                B3 = DecimalUtil.add(B3, new BigDecimal(s));
            } else if(pid.startsWith("B4")){
                B4 = DecimalUtil.add(B4, new BigDecimal(s));
            } else if(pid.startsWith("B5")){
                B5 = DecimalUtil.add(B5, new BigDecimal(s));
            }
        }
        // 拼接得分
        Map<String, Object> m3 = new HashMap<>();
        m3.put("name", "得分");
        List<BigDecimal> df = new ArrayList<>();
        df.add(B1);
        df.add(B2);
        df.add(B3);
        df.add(B4);
        df.add(B5);
        m3.put("data", df);
        resultList.add(m3);
        resultMap.put("infoData", resultList);
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 根据月份查询指标得分想详细情况
     * @Author hsh
     * @param dto 指标参数
     * @return map
     * @Date 2024/11/20 11:02
     */
    public ResultVo<Map<String, Object>> targetSqlExecuteMonthById(TargetManagement dto) {
        ReportBaseInfo reportChild = dao.selectReportBaseInfoByCalcId(dto.getChildId());
        ReportBaseInfo reportMom = dao.selectReportBaseInfoByCalcId(dto.getMomId());

        if(null ==  reportChild && null == reportMom){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "【" + dto.getName() + "】指标-分子或分母指标都不存在，请联系管理员！");
        }

        if(null ==  dto.getStartTime() || null == dto.getEndTime()){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "【" + dto.getName() + "】查询时间不存在，请检查！");
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", dto.getId());
        resultMap.put("pid", dto.getPid());
        resultMap.put("name", dto.getName());
        resultMap.put("childId", dto.getChildId());
        resultMap.put("momId", dto.getMomId());
        // 数据统计来源（1：sql统计；2：手动填写输入。）
        resultMap.put("dataType", "1");
        // 统计年月
        resultMap.put("month", dto.getStartTime());

        String d1 = dto.getStartTime().substring(0,4);
        String d2 = dto.getStartTime().substring(4,6);
        int year = Integer.parseInt(d1);
        int month = Integer.parseInt(d2);
        YearMonth ym = YearMonth.of(year, month);
        LocalDate js = ym.atEndOfMonth();
        dto.setStartTime(ym + "-01 23:59:59");
        dto.setEndTime(js + " 23:59:59");
        HighReportDto vo = ReportUtil.TargetManagementConvertHighReportDto(dto);
        // 计算结果
        String child = "";
        String mom = "";
        if(null != reportChild){
            String childSql = ReportUtil.callSqlFormat(vo, reportChild.getBaseSql(), reportChild.getGatherSql(), null, null, null);
            child = dao.targetSqlExecute(childSql);
        } else {
            child = "";
        }
        if(null != reportMom){
            String momSql = ReportUtil.callSqlFormat(vo, reportMom.getBaseSql(), reportMom.getGatherSql(), null, null, null);
            mom = dao.targetSqlExecute(momSql);
        } else {
            mom = "";
        }

        if (StringUtil.notBlank(child)) {
            resultMap.put("childResult", child);
        } else {
            resultMap.put("childResult", "");
        }
        if (StringUtil.notBlank(mom)) {
            resultMap.put("momResult", mom);
            if(StringUtil.notBlank(child)){
                resultMap.put("calcResult", DecimalUtil.divide(new BigDecimal(child), new BigDecimal(mom), 4));
            } else {
                resultMap.put("calcResult", "");
            }
        } else {
            resultMap.put("momResult", "");
            if (StringUtil.notBlank(child)) {
                resultMap.put("calcResult", child);
            } else {
                resultMap.put("calcResult", "");
            }
        }
        return ResultVoUtil.success(resultMap);
    }

    /**
     * @Description 根据月份查询指标月度结果以及得分情况
     * @Author hsh
     * @param dto 指标
     * @return score 指标月度结果以及得分情况
     * @Date 2024/11/20 17:15
     */
    public ResultVo<ZbReportMonthScore> selectTargetReportResultByMonth(ZbReportMonthScore dto) {
        ZbReportMonthScore score = reportDao.selectReportResultByMonth(dto.getId(), dto.getPid(), dto.getMonth());
        return ResultVoUtil.success(score);
    }

    /**
     * @Description 保存指标计算结果以及得分情况
     * @Author hsh
     * @param monthScore 指标计算结果以及得分情况
     * @return  map
     * @Date 2024/11/20 17:16
     */
    public ResultVo<Map<String, Object>> saveTargetReportMonthResult(ZbReportMonthScore monthScore){
        Map<String, Object> resultMap = new HashMap<>();
        if(monthScore == null || null == monthScore.getId()){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "指标id不存在，请检查！");
        }

        UserInfo user = userCache.get(TokenUtil.getInstance().getTokenUserId());
        monthScore.setAuthorName(user.getName() != null ? user.getName().trim() : null);
        monthScore.setAuthorId(user.getCode());
        monthScore.setDeptId(user.getDeptCode());
        monthScore.setDeptName(user.getDeptName());
        monthScore.setCreateTime(DateUtil.now());

        // 入库或更新操作
        int n = updateAndSaveTargetReportMonthResult(monthScore);
        if (n <= 0) {
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "保存指标计算结果以及得分情况失败！");
        }
        resultMap.put("cg", "保存指标计算结果以及得分情况成功");
        return ResultVoUtil.success(resultMap);
    }

    private int updateAndSaveTargetReportMonthResult(ZbReportMonthScore monthScore) {
        if(monthScore == null){
            return 0;
        }
        ZbReportMonthScore r = reportDao.selectReportResultByMonth(monthScore.getId(), monthScore.getPid(), monthScore.getMonth());
        if(r != null){
            reportDao.deleteReportResultMonthById(monthScore.getId(), monthScore.getPid(), monthScore.getMonth());
        }
        return reportDao.saveTargetReportMonthResult(monthScore);
    }

    /**
     * @Description 根据月份，指标id查询指标得分详情
     * @Author hsh
     * @param dto 月份，指标id
     * @return list
     * @Date 2024/11/21 11:01
     */
    public ResultVo<List<ZbReportMonthScore>> selectTargetReportMonthScore(TargetManagement dto) {
        List<ZbReportMonthScore> score = reportDao.selectTargetReportMonthResultById(dto.getId(), dto.getPid(), dto.getStartTime(), dto.getEndTime());
        return ResultVoUtil.success(score);
    }

    /**
     * @Description 查询指标周期年度得分汇总情况
     * @Author hsh
     * @param dto 指标参数
     * @return list
     * @Date 2024/11/26 14:56
     */
    public ResultVo<List<Map<String, Object>>> selectTargetYearScoreSummary(TargetManagement dto) {
        List<Map<String, Object>> list = reportDao.selectTargetCycleScore(dto);
        List<ZbReportResult> resultList = reportDao.selectTargetReportResultByCycle(dto.getReportCycle(), dto.getId(), dto.getPid());
        if(null != list && null != resultList && !list.isEmpty() && !resultList.isEmpty()){
            Map<String, List<ZbReportResult>> resultMap = resultList.stream().collect(Collectors.groupingBy(ZbReportResult::getId));
            for(Map<String, Object> map : list){
                String id = String.valueOf(map.get("id"));
                List<ZbReportResult> results = resultMap.get(id);
                if(null != results && !results.isEmpty()){
                    map.put("results", results);
                }
            }
        }
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 查询指标周期月度得分汇总情况
     * @Author hsh
     * @param dto 指标参数
     * @return list
     * @Date 2024/11/27 16:51
     */
    public ResultVo<List<ZbReportMonthScore>> selectTargetMonthScoreSummary(TargetManagement dto) {
        return ResultVoUtil.success(reportDao.selectTargetMonthScoreSummary(dto));
    }

    /**
     * @Description 查询指标固定值（手工填写等）指标
     * @Author hsh
     * @param dto 查询条件
     * @return list
     * @Date 2024/12/4 16:26
     */
    public ResultVo<List<ReportBaseInfo>> selectTargetDictConstantData(TargetManagement dto) {
        List<ReportBaseInfo> list = reportDao.selectTargetDictConstantData(dto);
        return ResultVoUtil.success(list);
    }

    /**
     * @Description 上传指标文件
     * @Author hsh
     * @param result 指标结果信息
     * @return map
     * @Date 2025/5/10 0010 15:48
     */
    public ResultVo<Map<String, Object>> uploadTargetFile(ZbReportResult result){
        Map<String, Object> map = new HashMap<>();
        ZbReportResult re = reportDao.selectReportResultByYear(result.getId(), result.getPid(), result.getYear());
        if(null == re){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到对应的指标结果，请检查！");
        }
        ArchiveServer.UploadResult uploadResult = archiveServer.uploadFile(result.getFile(), TARGET_PATH);
        String url = uploadResult.getPath();
        map.put("url", url);
        String fileId = re.getFileId();
        if(StringUtil.isEmpty(fileId)){
            result.setFileId(uploadResult.getId());
        } else {
            fileId = fileId + "," + uploadResult.getId();
            result.setFileId(fileId);
        }
        reportDao.updateZbReportResultFileIdById(result);
        return ResultVoUtil.success(map);
    }

    /**
     * @Description 查询指标文件
     * @Author hsh
     * @param result 指标信息
     * @return map
     * @Date 2025/5/12 0012 19:29
     */
    public ResultVo<Map<String, Object>> selectTargetFileById(ZbReportResult result){
        Map<String, Object> map = new HashMap<>();
        List<ArchiveUpload> list = new ArrayList<>();
        if(!StringUtil.isEmpty(result.getFileId())){
            String[] f = result.getFileId().split(",");
            for(String id : f){
                if(!StringUtil.isEmpty(id)){
                    ArchiveUpload pu = zbZdDao.selectTargetFileById(id);
                    if(null != pu){
                        pu.setPath(pu.getPath().replace("/mnt/archive", "/thyyarchive"));
                        list.add(pu);
                    }
                }
            }
        }
        if(isProd){
            map.put("targetPath", "/thyyarchive/archive" + TARGET_PATH);
        } else {
            map.put("targetPath", "/thyyarchive/archive-test" + TARGET_PATH);
        }
        map.put("fileList", list);
        return ResultVoUtil.success(map);
    }

    /**
     * @Description 根据文件路径删除文件
     * @Author hsh
     * @param id 文件id
     * @return map
     * @Date 2025/5/13 0013 15:31
     */
    public ResultVo<Map<String, Object>> deleteTargetFileByFileId(String fileId, String id, String pid, String year){
        if(StringUtil.isEmpty(fileId)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到删除的文件id，请检查！");
        }
        if(StringUtil.isEmpty(id) || StringUtil.isEmpty(pid) || StringUtil.isEmpty(year)){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到删除的文件id，请检查！");
        }
        ZbReportResult re = reportDao.selectReportResultByYear(id, pid, year);
        if(null == re){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "没有找到对应的指标结果，请检查！");
        }
        Map<String, Object> map = new HashMap<>();
        try {
            archiveServer.delUploadById(fileId);

            if(null != re.getFileId() && re.getFileId().contains(fileId)){
                // 删除对应指标的fileId
                ZbReportResult result = new ZbReportResult();
                result.setId(id);
                result.setPid(pid);
                result.setYear(year);
                String str = re.getFileId().replace(fileId + ",", "")
                        .replace("," + fileId, "").replace(fileId, "");
                result.setFileId(",".equals(str) ? "" : str);
                reportDao.updateZbReportResultFileIdById(result);
            }
        } catch(Exception e){
            return ResultVoUtil.fail(ExceptionEnum.LOGICAL_ERROR, "根据【" + fileId + "】删除的文件失败，请检查！");
        }
        map.put("cg", "删除指标文件成功！");
        return ResultVoUtil.success(map);
    }

}
