package com.kingdee.eas.custom.performancenew.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.sql.ParserException;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.custom.performancenew.app.orderStatucEnum;
import com.kingdee.eas.custom.performancenew.app.periodTypeEnum;
import com.kingdee.eas.custom.performancenew.app.scoreEnum;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.json.GridDataEntity;
import com.kingdee.shr.base.syssetting.web.handler.DynamicListHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author qingwu
 * @date 2024/4/10
 * @apiNote 绩效管理  专员维护考核人和评分人页面(评分人)  动态列表
 * EmpBatchEnrollListHandler
 */
public class ExaminePFRDynamicListHandlerBF extends DynamicListHandler {
    private static Logger logger =
            Logger.getLogger(ExaminePFRDynamicListHandler.class);

    private  Context ctx = SHRContext.getInstance().getContext();

    /**
     * 获取生效日期过滤器
     * 移除父类方法过滤条件
     *
     * @param effectDate
     * @return
     */
    protected FilterInfo getEffectDateFilter(Date effectDate) {
        return null;
    }

    /**
     * 保存方法
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void saveAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        //列表数据
        String tableData = request.getParameter("tableData");
        logger.error("tableData：" + tableData);
        try {
            JSONArray jsonArray = JSONObject.parseArray(tableData);
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("index");
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    ExamineGradePersonEntryInfo entryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(jsonObject.get("entrys.id").toString()));
                    entryInfo.setIndex(jsonObject.getInteger("entrys.index"));
                    iExamineGradePersonEntry.updatePartial(entryInfo, sic);
                }
                logger.error("jsonArray：" + jsonArray);
            }
            JSONUtils.SUCCESS(true);
        } catch (BOSException e) {
            throw new RuntimeException(e);
        } catch (EASBizException e) {
            throw new RuntimeException(e);
        } catch (SHRWebException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 提交
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    public void customSubmitAction(HttpServletRequest request,
                                   HttpServletResponse response,
                                   ModelMap modelMap) throws BOSException, ParserException, ShrWebBizException {
        String billID = request.getParameter("billId");
        //部门id集合
        String adminIdArray = request.getParameter("adminIdArray");
        if (com.kingdee.util.StringUtils.isEmpty(billID) && com.kingdee.util.StringUtils.isEmpty(adminIdArray)) {
            throw new BOSException("单据id和已选择部门不能为空！");
        }
        try {
            //调用计算得分
            calculateScoreAction(request, response, modelMap);

            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            String[] split = adminIdArray.split(",");
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("orderStatuc");
            Map isSortedMap = null;
            for (int i = 0; i < split.length; i++) {
                String adminId = split[i];
                ExamineGradePersonEntryCollection entryColl = getCurrentPersonEqualsScore(billID, adminId);
                for (int j = 0; j < entryColl.size(); j++) {
                    ExamineGradePersonEntryInfo entryInfo = entryColl.get(j);
                    entryInfo.setOrderStatuc(orderStatucEnum.submitted);
                    iExamineGradePersonEntry.updatePartial(entryInfo, sic);
                }
            }
            JSONUtils.SUCCESS(isSortedMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 过滤提交按钮的行政组织F7数据
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void submitFilterAdminAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String billID = request.getParameter("billId");
        try {
            ExamineGradePersonEntryCollection entrys = getCurrentPersonEqualsScore(billID, null);
            Set set = new HashSet<>();
            StringBuilder sb = new StringBuilder();
            //去重操作
            for (int i = entrys.size() - 1; i >= 0; i--) {
                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entrys.get(i);
                String adminId = examineGradePersonEntryInfo.getAdminOrg().getId().toString();
                if (set.contains(adminId)) {
                    entrys.remove(examineGradePersonEntryInfo);
                } else {
                    set.add(adminId);
                    sb.append("'").append(adminId).append("',");
                }
            }
            // 删除最后一个逗号
            if (sb.length() > 0) {
                sb.deleteCharAt(sb.length() - 1);
            }
            JSONUtils.SUCCESS(sb);
        } catch (ParserException e) {
            throw new RuntimeException(e);
        } catch (BOSException e) {
            throw new RuntimeException(e);
        } catch (SHRWebException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验周期是否解除
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void isValidationPeriodExpiredAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws ShrWebBizException {
        String billID = request.getParameter("billId");
        if (com.kingdee.util.StringUtils.isEmpty(billID)) {
            throw new ShrWebBizException("校验周期是否解除：请联系管理员！！");
        }
        try {
            IExamineGradePerson iExamineGradePerson = ExamineGradePersonFactory.getLocalInstance(ctx);
            JSONUtils.SUCCESS(iExamineGradePerson.getExamineGradePersonInfo(new ObjectUuidPK(billID)).getPeriodStatus());
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (SHRWebException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (EASBizException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 按照顺序排序给页面显示
     *
     * @param request
     * @param response
     * @param gridDataEntity
     * @throws SHRWebException
     */
    @Override
    protected void afterGetListData(HttpServletRequest request, HttpServletResponse response, GridDataEntity gridDataEntity) throws SHRWebException {
        List<Map<String, Object>> rows = gridDataEntity.getRows();
        List<Map<String, Object>> modifiedRows = new ArrayList<>();
        String adminOrgUnitNumber = "adminOrgUnit.number";
        //先排序list数据
        Collections.sort(rows, new Comparator<Map>() {
            @Override
            public int compare(Map o1, Map o2) {
                // 首先按照名称排序
                int nameComparison = o1.get(adminOrgUnitNumber.toLowerCase()).toString().compareTo(o2.get(adminOrgUnitNumber.toLowerCase()).toString());
                if (nameComparison != 0) {
                    return nameComparison;
                }

                // 如果名称相同，则按照编号排序
                return Integer.parseInt(o1.get("entrys.index").toString()) - Integer.parseInt(o2.get("entrys.index").toString());
            }
        });


        super.afterGetListData(request, response, gridDataEntity);
    }


    /**
     * 计算得分
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     */
    public void calculateScoreAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws BOSException {
        String billID = request.getParameter("billId");
        if (com.kingdee.bos.ctrl.swing.StringUtils.isEmpty(billID)) {
            throw new BOSException("单据id不能为空！");
        }
        //部门id集合
        String adminIdArray = request.getParameter("adminIdArray");
        try {
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            String[] split = adminIdArray.split(",");

            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("orderStatuc");
            Map isSortedMap = null;
            for (int i = 0; i < split.length; i++) {
                String adminId = split[i];
                ExamineGradePersonEntryCollection entryColl = getCurrentPersonEqualsScore(billID, adminId);
                //校验顺序
                isSortedMap = isSorted(entryColl);
                //计算得分
                saveScore(isSortedMap, entryColl);
            }
            //try {
            //    //获取当前登录人等于评分人的数据
            //    ExamineGradePersonEntryCollection entrys = getCurrentPersonEqualsScore(billID, null);
            //    //查询评分人是否维护组织绩效得分
            //    Map isSortedMap = isSorted(entrys);
            //    //for (int i = 0; entrys != null && i < entrys.size(); i++) {
            //    //    ExamineGradePersonEntryInfo entry = entrys.get(i);
            //    //    String depName = entry.getAdminOrg().getName();
            //    //    if (entry.getPerformanceScoreOrg() == null) {
            //    //        throw new ShrWebBizException("部门[" + depName + "]未维护组织绩效得分!");
            //    //    }
            //    //}
            //    Map<String, Integer> maxNumberMap = (Map) isSortedMap.get("maxNumberMap");
            //    if (maxNumberMap != null) {
            //        //遍历maxNumberMap
            //        for (String key : maxNumberMap.keySet()) {
            //            ExamineGradePersonEntryCollection entryColl = getCurrentPersonEqualsScore(billID, key);
            //            //校验顺序
            //            Map isSortedMap2 = isSorted(entryColl);
            //            //计算得分
            //            saveScore(isSortedMap2, entryColl);
            //        }
            //    }
            JSONUtils.SUCCESS(isSortedMap);
        } catch (SHRWebException | EASBizException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ParserException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 校验是否存在顺序重复或断层,和保存计算得分
     *
     * @param entrys
     * @return
     */
    private Map isSorted(ExamineGradePersonEntryCollection entrys) throws ShrWebBizException {

        List<ExamineGradePersonEntryInfo> list = new ArrayList<>();
        for (int i = 0; i < entrys.size(); i++) {
            ExamineGradePersonEntryInfo entry = entrys.get(i); // 假设该集合类提供了类似get方法来获取元素
            list.add(entry);
        }
        //先排序list数据
        Collections.sort(list, new Comparator<ExamineGradePersonEntryInfo>() {
            @Override
            public int compare(ExamineGradePersonEntryInfo o1, ExamineGradePersonEntryInfo o2) {
                // 首先按照名称排序
                int nameComparison = o1.getAdminOrg().getId().toString().compareTo(o2.getAdminOrg().getId().toString());
                if (nameComparison != 0) {
                    return nameComparison;
                }
                // 如果名称相同，则按照编号排序
                return o1.getIndex() - o2.getIndex();
            }
        });
        // 使用Map存储每个分类的最大编号
        Map<String, Integer> maxNumberMap = new HashMap<>();
        // for (ExamineGradePersonEntryInfo entryInfo : list) {
        for (int i = 0; i < list.size(); i++) {
            ExamineGradePersonEntryInfo entryInfo = list.get(i);
            AdminOrgUnitInfo adminOrg = entryInfo.getAdminOrg();
            String adminId = adminOrg.getId().toString();
            int order = entryInfo.getIndex();
            Integer maxNumber = maxNumberMap.getOrDefault(adminId, 0);
            // 检查编号是否按顺序且没有断层
            if (order == maxNumber + 1) {
                maxNumberMap.put(adminId, order);
            } else {
                throw new ShrWebBizException("部门[" + adminOrg.getName() + "]中的顺序不是有序或断层的!!");
            }
        }
        return maxNumberMap;
    }

    /**
     * 获取当前登录人等于评分人的数据
     *
     * @param billID
     * @return
     */
    public ExamineGradePersonEntryCollection getCurrentPersonEqualsScore(String billID,
                                                                         String adminID) throws ParserException, BOSException {
        //当前登录员工id
        String currentPersonId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("parent.id", billID));
        filterItems.add(new FilterItemInfo("orderStatuc", "2", CompareType.NOTEQUALS));
        filterItems.add(new FilterItemInfo("scorer.id", currentPersonId));
        if (!StringUtils.isEmpty(adminID)) {
            filterItems.add(new FilterItemInfo("adminOrg.id", adminID));
        }
        SorterItemCollection sorterItemCollection = new SorterItemCollection("adminOrg.id,index");
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, sorterItemCollection);
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        return iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
    }

    /**
     * 保存计算得分
     *
     * @param maxNumberMap key 部门ID 人数
     * @param entrys
     * @throws BOSException
     * @throws EASBizException
     */
    private void saveScore(Map<String, Integer> maxNumberMap,
                           ExamineGradePersonEntryCollection entrys)
            throws BOSException, EASBizException, ShrWebBizException {
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        IExamineGradePerson iExamineGradePerson = ExamineGradePersonFactory.getLocalInstance(ctx);
        //遍历maxNumberMap
        for (String key : maxNumberMap.keySet()) {
            //部门人数
            int depPersonNum = maxNumberMap.get(key);
            logger.debug("Key: " + key + ", Value: " + depPersonNum);
            if (depPersonNum > 5) {
                //获取得分数据
                Map<String, List<String>> scoreLevelMap = getScoreLevelList(depPersonNum);
                for (int i = 0; i < entrys.size(); i++) {
                    saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);
                }
            } else if (depPersonNum == 5) {
                //人数等于5个时的逻辑校验

            } else {
                //获取主表的数据
                ExamineGradePersonInfo examineGradePersonInfo =
                        iExamineGradePerson.getExamineGradePersonInfo("where id = '" + entrys.get(0).getParent().getId() + "'");
                //判断周期类型是年度的话直接计算
                if (examineGradePersonInfo.getPeriodType() == periodTypeEnum.year) {
                    //获取得分数据
                    Map<String, List<String>> scoreLevelMap = getScoreLevelList(depPersonNum);
                    for (int i = 0; i < entrys.size(); i++) {
                        saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);
                    }
                } else {
                    //判断是否是1季度 1季度直接计算
                    if (examineGradePersonInfo.getQuarter() == 1) {
                        //获取得分数据
                        Map<String, List<String>> scoreLevelMap = getScoreLevelList(depPersonNum);
                        for (int i = 0; i < entrys.size(); i++) {
                            saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);
                        }
                    } else {
                        //周期考核人员少于5个人是获取上个季度该部门的人员
                        //创建分录集合对象
                        ExamineGradePersonEntryCollection entryCollection = new ExamineGradePersonEntryCollection();
                        //把少于5个人的数据先拿出来存到一个新的对象里面
                        entryCollection = entrys;
                        //存储当前人员等级
                        ExamineGradePersonEntryCollection dqEntryCollection = new ExamineGradePersonEntryCollection();
                        dqEntryCollection = entrys;
                        //存储上个季度的得分等级
                        List upList = new ArrayList();
                        //查询本年度上季度该部门的人
                        FilterInfo filterInfo = new FilterInfo();
                        FilterItemCollection filterItems = filterInfo.getFilterItems();
                        filterItems.add(new FilterItemInfo("periodType", "2", CompareType.EQUALS));
                        filterItems.add(new FilterItemInfo("year", examineGradePersonInfo.getYear()));
                        filterItems.add(new FilterItemInfo("quarter", examineGradePersonInfo.getQuarter() - 1));
                        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
                        ExamineGradePersonCollection upExamineGradePersonColl = iExamineGradePerson.getExamineGradePersonCollection(entityViewInfo);
                        if (upExamineGradePersonColl.size() > 0) {
                            ExamineGradePersonInfo upExamineGradePersonInfo = upExamineGradePersonColl.get(0);
                            for (int i = 0; i < upExamineGradePersonInfo.getEntrys().size(); i++) {
                                entryCollection.add(upExamineGradePersonInfo.getEntrys().get(i));
                                upList.add(upExamineGradePersonInfo.getEntrys().get(i).getScore());
                            }
                        }
                        //修改计算得分和领导计算得分
                        SelectorItemCollection sic = new SelectorItemCollection();
                        sic.add("score");
                        sic.add("scoreLeader");
                        sic.add("afterScoreNumMap");
                        //获取得分数据
                        Map<String, List<String>> scoreLevelMap = getScoreLevelList(entryCollection.size());
                        for (int i = 0; i < dqEntryCollection.size(); i++) {
                            //saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);
                            ExamineGradePersonEntryInfo examineGradePersonEntryInfo =
                                    iExamineGradePersonEntry.getExamineGradePersonEntryInfo("select * ,performanceScoreOrg.* where id = '" + entrys.get(i).getId().toString() + "'");
                            if (key.equals(examineGradePersonEntryInfo.getAdminOrg().getId().toString())) {
                                //获取得分级别
                                String name = examineGradePersonEntryInfo.getPerformanceScoreOrg().getName();
                                //获取顺序号
                                int index = examineGradePersonEntryInfo.getIndex();
                                List<String> listArray = scoreLevelMap.get(name);
                                //删除上个季度的评分等级获取当前季度人员得分等级
                                subtractArrays(listArray, upList);
                                //通过顺序号获取listArray里面的数据  index-1对应下标
                                String scoreLeavel = listArray.get(index - 1);
                                //获取得分对应人数
                                Map numMap = (Map) scoreLevelMap.get("numMap");
                                //累计得分人数
                                Map addupScore = (Map) numMap.get(name);
                                //修改的数据
                                examineGradePersonEntryInfo.setScore(scoreEnum.getEnum(scoreLeavel));
                                examineGradePersonEntryInfo.setScoreLeader(scoreEnum.getEnum(scoreLeavel));
                                examineGradePersonEntryInfo.setAfterScoreNumMap(addupScore.toString());
                                iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, sic);
                            }
                        }
                    }
                }

            }
        }
    }

    // 实现数组的减法操作
    private static void subtractArrays(List<String> array1, List<String> array2) {
        // 使用迭代器遍历第一个数组，安全进行删除操作
        Iterator<String> iterator = array1.iterator();
        while (iterator.hasNext()) {
            String item = iterator.next();
            // 如果第二个数组中包含当前元素，则从第一个数组中移除
            if (array2.contains(item)) {
                iterator.remove();
                // 从第二个数组中移除该元素，以避免多次移除相同元素
                array2.remove(item);
            }
        }
    }

    /**
     * 修改保存计算得分
     *
     * @param entrys
     * @param iExamineGradePersonEntry
     * @param key
     * @param i
     * @param scoreLevelMap
     * @throws BOSException
     * @throws EASBizException
     */
    private void saveExamineScorer(ExamineGradePersonEntryCollection entrys, IExamineGradePersonEntry iExamineGradePersonEntry, String key, int i, Map<String, List<String>> scoreLevelMap) throws BOSException, EASBizException, ShrWebBizException {
        //修改计算得分和领导计算得分
        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("score");
        sic.add("scoreLeader");
        sic.add("afterScoreNumMap");
        ExamineGradePersonEntryInfo examineGradePersonEntryInfo =
                iExamineGradePersonEntry.getExamineGradePersonEntryInfo("select * ,performanceScoreOrg.* where id = '" + entrys.get(i).getId().toString() + "'");
        if (key.equals(examineGradePersonEntryInfo.getAdminOrg().getId().toString())) {
            //获取得分级别
            String name = examineGradePersonEntryInfo.getPerformanceScoreOrg().getName();
            //获取顺序号
            int index = examineGradePersonEntryInfo.getIndex();
            List<String> listArray = scoreLevelMap.get(name);
            //通过顺序号获取listArray里面的数据  index-1对应下标
            String scoreLeavel = listArray.get(index - 1);
            //获取得分对应人数
            Map numMap = (Map) scoreLevelMap.get("numMap");
            //累计得分人数
            Map addupScore = (Map) numMap.get(name);
            //修改的数据
            examineGradePersonEntryInfo.setScore(scoreEnum.getEnum(scoreLeavel));
            examineGradePersonEntryInfo.setScoreLeader(scoreEnum.getEnum(scoreLeavel));
            examineGradePersonEntryInfo.setAfterScoreNumMap(addupScore.toString());
            iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, sic);
        }
    }

    /**
     * 获取得分级别
     *
     * @param num 人数
     */
    public Map getScoreLevelList(int num) {
        try {
            IPersonRelationOrg iPersonRelationOrg = PersonRelationOrgFactory.getLocalInstance(ctx);
            //组织绩效与个人绩效分布对应关系
            PersonRelationOrgCollection personRelationOrgCollection = iPersonRelationOrg.getPersonRelationOrgCollection();
            Map scoreLevelMap = new HashMap<>();
            //评分人数
            Map numMap = new HashMap<>();
            Map numMap2 = null;
            for (int i = 0; i < personRelationOrgCollection.size(); i++) {
                PersonRelationOrgInfo personRelationOrgInfo = personRelationOrgCollection.get(i);
                Integer ratioPerformanceA = personRelationOrgInfo.getMeritA();
                Integer ratioPerformanceBplus = personRelationOrgInfo.getMeritBplus();
                Integer ratioPerformanceB = personRelationOrgInfo.getMeritB();
                Integer ratioPerformanceBminus = personRelationOrgInfo.getMeritBminus();
                Integer ratioPerformanceC = personRelationOrgInfo.getMeritC();
                Integer ratioPerformanceD = personRelationOrgInfo.getMeritD();

                double a = jsbfb(ratioPerformanceA, num);
                double bPlus = jsbfb(ratioPerformanceBplus, num);
                double b = jsbfb(ratioPerformanceB, num);
                double bMinus = jsbfb(ratioPerformanceBminus, num);
                double c = jsbfb(ratioPerformanceC, num);
                double d = jsbfb(ratioPerformanceD, num);
                if (a > 0) {
                    a = (int) Math.round(a);
                }
                if (d > 0.55) {
                    d = Math.round(d);
                }
                if (c > 0.55) {
                    c = Math.round(c);
                }
                if (bMinus > 0.55) {
                    bMinus = Math.round(bMinus);
                } else {
                    bMinus = 0.0;
                }
                //B+的余数是否大于等于B的余数
                if (compareTheSize(bPlus, b)) {
                    bPlus = Math.round(bPlus);
                    if (c > 0) {
                        b = num - a - bPlus - c;
                    } else if (d > 0) {
                        b = num - a - bPlus - d;
                    } else if (bMinus > 0) {
                        b = num - a - bPlus - bMinus;
                    }

                    //if (a != 0 && bPlus != 0 && b != 0 && bMinus != 0) {

                    //}
                    if (a != 0 || b != 0 || bPlus != 0 || bMinus != 0 || c != 0 || d != 0) {
                        b = num - a - bPlus - bMinus;
                    } else {
                        b = 0.0;
                    }
                } else {
                    b = Math.round(b);

                    if (c > 0.55) {
                        bPlus = num - a - b - c;
                    } else if (d > 0.55) {
                        bPlus = num - a - b - d;
                    } else if (bMinus > 0) {
                        bPlus = num - a - -bMinus;
                    }
                    if (a != 0 || b != 0 || bPlus != 0 || bMinus != 0 || c != 0 || d != 0) {
                        bPlus = num - a - b - bMinus;
                    } else {
                        bPlus = 0.0;
                    }
                }
                List scoreLevelList = new ArrayList();
                List numList = new ArrayList();
                if (a != 0) {
                    getScoreLevel(scoreLevelList, (int) a, "A");
                    scoreLevelMap.put(personRelationOrgInfo.getName(), scoreLevelList);
                }
                if (bPlus != 0) {
                    getScoreLevel(scoreLevelList, (int) bPlus, "B+");
                    scoreLevelMap.put(personRelationOrgInfo.getName(), scoreLevelList);

                }
                if (b != 0) {
                    getScoreLevel(scoreLevelList, (int) b, "B");
                    scoreLevelMap.put(personRelationOrgInfo.getName(), scoreLevelList);

                }
                if (bMinus != 0) {
                    getScoreLevel(scoreLevelList, (int) bMinus, "B-");
                    scoreLevelMap.put(personRelationOrgInfo.getName(), scoreLevelList);

                }
                if (c != 0) {
                    getScoreLevel(scoreLevelList, (int) c, "C");
                    scoreLevelMap.put(personRelationOrgInfo.getName(), scoreLevelList);

                }
                if (d != 0) {
                    getScoreLevel(scoreLevelList, (int) d, "D");
                    scoreLevelMap.put("D", scoreLevelList);
                }
                numMap2 = new HashMap();
                numMap2.put("A", a);
                numMap2.put("B+", bPlus);
                numMap2.put("B", b);
                numMap2.put("B-", bMinus);
                numMap2.put("C", c);
                numMap2.put("D", d);
                numMap.put(personRelationOrgInfo.getName(), numMap2);
            }
            scoreLevelMap.put("numMap", numMap);
            System.out.println("scoreLevelMap" + scoreLevelMap);
            logger.error("scoreLevelMap:" + scoreLevelMap);
            return scoreLevelMap;
        } catch (BOSException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取得分级别
     */
    public void getScoreLevel(List list, int num, String scoreLevel) {
        for (int i = 0; i < num; i++) {
            list.add(scoreLevel);
        }
    }

    public double jsbfb(double percentage, Integer num2) {
        return percentage / 100 * num2; // 将百分比转换为小数
    }

    public boolean compareTheSize(double num1, double num2) {
        int num1Digit = (int) (num1 * 10) % 10;
        int num2Digit = (int) (num2 * 10) % 10;
        if (num1Digit < num2Digit) {
            return false;
        } else {
            return true;
        }
    }


    @Override
    protected FilterInfo assembleFilterInfo(HttpServletRequest request, Map<String, String> params, Map filterCondition, Date effectDate) throws SHRWebException {
        FilterInfo quickFilter = null;
        FilterInfo settingFilter = null;
        FilterInfo customFilter = null;
        if (filterCondition != null) {
            quickFilter = this.convertQuickFilterInfo((String) filterCondition.get("quickFilter"));
            settingFilter = this.convertFilterInfo((String) filterCondition.get("settingFilter"));
            customFilter = this.convertCustomFilterInfo((String) filterCondition.get("customFilter"));
        }
        String custom_params = request.getParameter("custom_params");
        if (!StringUtils.isEmpty(custom_params)) {
            customFilter = new FilterInfo();
            Map customParams = JSONUtils.convertJsonToObject(custom_params);
            String examineGradePersonId = (String) customParams.get("examineGradePersonId");
            customFilter.getFilterItems().add(new FilterItemInfo("periodicQuarter.id", examineGradePersonId));
            customFilter.getFilterItems().add(new FilterItemInfo("entrys.orderStatuc", "2", CompareType.NOTEQUALS));
        }
        FilterInfo advanceFilter = this.getAdvanceFilter(request);
        FilterInfo filterInfo = new FilterInfo();

        try {
            //FilterInfo defaultFilterInfo = this.getDefaultFilter(request, (HttpServletResponse) null);
            FilterInfo domainFilterInfo = this.getDomainFilter(request);
            FilterInfo treeDomainFilter = this.getTreeDomainFilter(request, (Map) filterCondition.get("tree_params"));
            //FilterInfo effectDateFilter = this.getEffectDateFilter(effectDate);
            //FilterInfo fastFilter = this.getFastFilter(request);
            String filter = (String) params.get("filter");
            if (!StringUtils.isEmpty(filter)) {
                filterInfo.mergeFilter(new FilterInfo(filter), "AND");
            }

            //filterInfo.mergeFilter(defaultFilterInfo, "AND");
            filterInfo.mergeFilter(domainFilterInfo, "AND");
            filterInfo.mergeFilter(treeDomainFilter, "AND");
            filterInfo.mergeFilter(quickFilter, "AND");
            filterInfo.mergeFilter(settingFilter, "AND");
            //filterInfo.mergeFilter(effectDateFilter, "AND");
            filterInfo.mergeFilter(customFilter, "AND");
            //filterInfo.mergeFilter(fastFilter, "AND");
            filterInfo.mergeFilter(advanceFilter, "AND");
            return filterInfo;
        } catch (BOSException var16) {
            throw new SHRWebException(var16);
        } catch (ParserException var17) {
            throw new SHRWebException(var17.getMessage(), var17);
        }
    }


}
