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

import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
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.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.notify.INotifyTodo;
import com.kingdee.eas.custom.notify.NotifyTodoFactory;
import com.kingdee.eas.custom.notify.SendContextInfo;
import com.kingdee.eas.custom.notify.bziEnum.SendTypeEnum;
import com.kingdee.eas.custom.performancenew.*;
import com.kingdee.eas.custom.performancenew.app.periodStatusEnum;
import com.kingdee.eas.custom.performancenew.app.periodTypeEnum;
import com.kingdee.eas.custom.performancenew.app.scoreEnum;
import com.kingdee.eas.custom.performancenew.handler.service.ExamineScorePersonService;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author qingwu
 * @date 2024/5/13
 * @apiNote
 */

public class ExamineScorePersonServiceImpl implements ExamineScorePersonService {
    private Context ctx = SHRContext.getInstance().getContext();
    private Logger logger =
            Logger.getLogger(ExamineScorePersonServiceImpl.class);

    @Override
    public void assessPrass(Context ctx, List<ExamineGradePersonEntryInfo> list, String appName, String modelName, String modelId, String subject, String link) throws ShrWebBizException, BOSException, EASBizException {
        IPerson iPerson = PersonFactory.getLocalInstance(ctx);
        INotifyTodo iNotifyTodo = NotifyTodoFactory.getLocalInstance(ctx);
        StringBuilder sb = null;
        List errorList = new ArrayList();
        //发送消息待办
        for (ExamineGradePersonEntryInfo entryInfo : list) {
            //评分人
            PersonInfo person = entryInfo.getScorer();
            //通过评分人Id获取OA用户名
            PersonInfo personInfo = iPerson.getPersonCollection("where id = '" + person.getId() + "'").get(0);
            String oaUserName = personInfo.getString("oaUserName");
            //if (StringUtils.isEmpty(oaUserName)) {
            //    sb = new StringBuilder();
            //    sb.append("[" + personInfo.getName() + "]");
            //    sb.append(",");
            //    break;
            //}
            SendContextInfo sendContextInfo = new SendContextInfo();
            sendContextInfo.setAppName(appName);//视图名称
            sendContextInfo.setModelName(modelName);//模块名
            sendContextInfo.setModelId(modelId);//随机唯一标识
            sendContextInfo.setSubject(subject);//uipk 地址
            sendContextInfo.setLink(link);
            sendContextInfo.setType(SendTypeEnum.notification);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("LoginName", "liucanyu");
            sendContextInfo.setTargets(jsonObject.toString());
            // 使用 Instant 类获取当前时间戳
            Instant instant = Instant.now();
            sendContextInfo.setCreateTime(new Timestamp(instant.toEpochMilli()));
            //发送
            iNotifyTodo.sendTodo(sendContextInfo);
        }
        if (errorList.size() > 0) {
            throw new ShrWebBizException("用户：" + sb.substring(0, sb.lastIndexOf(",")) + "没有OA用户名称");
        }
    }

    @Override
    public void verifyisLock(String id) throws BOSException, ShrWebBizException, EASBizException {
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        ExamineGradePersonEntryInfo examineGradePersonEntryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryCollection("select parent.periodStatus where id = '" + id + "' or parent.id = '" + id + "'").get(0);
        ExamineGradePersonInfo parent = examineGradePersonEntryInfo.getParent();
        if (parent.getPeriodStatus() == periodStatusEnum.periodLock) {
            throw new ShrWebBizException("专员已锁定周期，不可操作");
        }
    }

    /**
     * 过滤组织
     */
    @Override
    public String getAdminOrgFilter(String billID, boolean isSynUpLastLevelAndUpLastScore) {
        try {
            ExamineGradePersonEntryCollection entrys = getCurrentPersonEqualsScore(billID, null, isSynUpLastLevelAndUpLastScore);
            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);
            }
            return sb.toString();
        } catch (ParserException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (BOSException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取当前登录人等于评分人的数据
     *
     * @param billID
     * @return
     */
    public ExamineGradePersonEntryCollection getCurrentPersonEqualsScore(String billID, String adminID, boolean isScorer) throws ParserException, BOSException {
        //当前登录员工id
        String currentPersonId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
        SelectorItemCollection sic = new SelectorItemCollection();

        sic.add("*");
        sic.add("adminOrg.*");
        sic.add("performanceScoreOrg.*");
        sic.add("auditor.*");
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("parent.id", billID));
        filterItems.add(new FilterItemInfo("orderStatuc", "2", CompareType.NOTEQUALS));
        if (isScorer) {
            filterItems.add(new FilterItemInfo("scorer.id", currentPersonId));
        }
        if (!com.kingdee.util.StringUtils.isEmpty(adminID)) {
            filterItems.add(new FilterItemInfo("adminOrg.id", adminID));
        }
        SorterItemCollection sorterItemCollection = new SorterItemCollection("adminOrg.id,index");
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, sic, sorterItemCollection);
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        return iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
    }


    /**
     * 校验是否存在顺序重复或断层,和保存计算得分
     *
     * @param entrys
     * @return
     */
    @Override
    public 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<String, Object> map = new HashMap();
        // 使用Map存储每个分类的最大编号
        Map<String, Integer> maxNumberMap = new HashMap<>();
        // 使用Map存储每个分类的得分等级
        Map<String, String> adminGradeMap = 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();
            String scoreGrade = entryInfo.getPerformanceScoreOrg().getName();
            Integer maxNumber = maxNumberMap.getOrDefault(adminId, 0);
            // 检查编号是否按顺序且没有断层
            if (order == maxNumber + 1) {
                maxNumberMap.put(adminId, order);
                adminGradeMap.put(adminId, scoreGrade);
            } else {
                throw new ShrWebBizException("部门[" + adminOrg.getName() + "] 中的顺序不符合规则index!!");
            }
        }
        map.put("maxNumberMap", maxNumberMap);
        map.put("adminGradeMap", adminGradeMap);
        return map;
    }

    @Override
    public void saveScore(Map<String, Object> map,
                          ExamineGradePersonEntryCollection entrys)
            throws BOSException, EASBizException, ShrWebBizException {
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        IExamineGradePerson iExamineGradePerson = ExamineGradePersonFactory.getLocalInstance(ctx);
        Map<String, Integer> maxNumberMap = (Map) map.get("maxNumberMap");
        Map<String, String> adminGradeMap = (Map) map.get("adminGradeMap");
        if (maxNumberMap != null) {
            //遍历maxNumberMap
            for (String key : maxNumberMap.keySet()) {
                //部门人数
                int depPersonNum = maxNumberMap.get(key);
                //获取组织得分
                String adminOrgScore = adminGradeMap.get(key);
                //判断是否存在B-
                Boolean isBMinus = false;
                if (depPersonNum > 5) {
                    //获取得分数据
                    Map<String, List<String>> scoreLevelMap = getScoreLevelList(depPersonNum, adminOrgScore);
                    for (int i = 0; i < entrys.size(); i++) {
                        //修改保存计算得分
                        saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);

                    }
                } else {
                    //获取主表的数据
                    ExamineGradePersonInfo examineGradePersonInfo =
                            iExamineGradePerson.getExamineGradePersonInfo("where id = '" + entrys.get(0).getParent().getId() + "'");
                    //判断周期类型是年度的话直接计算
                    if (examineGradePersonInfo.getPeriodType() == periodTypeEnum.year) {
                        //获取得分数据
                        Map<String, List<String>> scoreLevelMap = getScoreLevelList(depPersonNum, adminOrgScore);
                        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, adminOrgScore);
                            for (int i = 0; i < entrys.size(); i++) {
                                //修改保存计算得分
                                saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);
                            }
                        } else {

                            //创建分录集合对象 累计上季度和本季度
                            ExamineGradePersonEntryCollection entryCollection = new ExamineGradePersonEntryCollection();
                            //把少于5个人的数据先拿出来存到一个新的对象里面
                            entryCollection = entrys;
                            //存储当前季度数据
                            ExamineGradePersonEntryCollection dqEntryCollection = new ExamineGradePersonEntryCollection();
                            for (int i = 0; i < entrys.size(); i++) {
                                dqEntryCollection.add(entrys.get(i));
                            }
                            //存储上个季度的得分等级
                            List upList = new ArrayList();
                            //查询本年度上季度该部门的人
                            FilterInfo filterInfo = new FilterInfo();
                            FilterItemCollection filterItems = filterInfo.getFilterItems();
                            filterItems.add(new FilterItemInfo("parent.periodType", "2", CompareType.EQUALS));
                            filterItems.add(new FilterItemInfo("parent.year", examineGradePersonInfo.getYear()));
                            filterItems.add(new FilterItemInfo("adminOrg.id", key));
                            filterItems.add(new FilterItemInfo("parent.quarter", examineGradePersonInfo.getQuarter() - 1));
                            EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
                            //上个季度集合
                            ExamineGradePersonEntryCollection upExamineGradePersonEntryColl = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
                            if (upExamineGradePersonEntryColl.size() > 0) {
                                //ExamineGradePersonInfo upExamineGradePersonInfo = upExamineGradePersonColl.get(0);
                                //for (int i = 0; i < upExamineGradePersonInfo.getEntrys().size(); i++) {
                                for (int i = 0; i < upExamineGradePersonEntryColl.size(); i++) {
                                    entryCollection.add(upExamineGradePersonEntryColl.get(i));
                                    switch (upExamineGradePersonEntryColl.get(i).getScoreLeader().toString()) {
                                        case "A":
                                            upList.add("1");
                                            break;
                                        case "B+":
                                            upList.add("2");
                                            break;
                                        case "B":
                                            upList.add("3");
                                            break;
                                        case "B-":
                                            upList.add("4");
                                            break;
                                        case "C":
                                            upList.add("5");
                                            break;
                                        case "D":
                                            upList.add("6");
                                            break;

                                    }
                                }

                                if (dqEntryCollection.size() == 5) {
                                    //upExamineGradePersonInfo 当前年度上个季度部门一样的数据
                                    isBMinus = isNotExistBMinus(upExamineGradePersonEntryColl);
                                    //dqEntryCollection当前季度数据
                                    isBMinus = isNotExistBMinus(dqEntryCollection);
                                }
                            }


                            //修改计算得分和领导计算得分
                            SelectorItemCollection sic = new SelectorItemCollection();
                            sic.add("score");
                            sic.add("scoreLeader");
                            sic.add("afterScoreNumMap");
                            //获取得分数据
                            Map<String, List<String>> scoreLevelMap = getScoreLevelList(entryCollection.size(), adminOrgScore);
                            for (int i = 0; i < dqEntryCollection.size(); i++) {
                                //saveExamineScorer(entrys, iExamineGradePersonEntry, key, i, scoreLevelMap);
                                ExamineGradePersonEntryInfo examineGradePersonEntryInfo =
                                        iExamineGradePersonEntry.getExamineGradePersonEntryInfo("select * ,performanceScoreOrg.* where id = '" + dqEntryCollection.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);
                                    //人员恰好等于五人是判断上个季度是否有B-没有这本周期必须要有一个B-
                                    if (dqEntryCollection.size() == 5 && !isBMinus) {
                                        listArray.set(listArray.size() - 1, "4");
                                    }
                                    //通过顺序号获取listArray里面的数据  index-1对应下标
                                    String scoreLeavel = listArray.get(index - 1);

                                    //累计得分人数
                                    Map addupScore = new HashMap();
                                    getListArrayGradeNum(listArray, addupScore);


                                    //修改的数据
                                    examineGradePersonEntryInfo.setScore(scoreEnum.getEnum(scoreLeavel));
                                    examineGradePersonEntryInfo.setScoreLeader(scoreEnum.getEnum(scoreLeavel));
                                    examineGradePersonEntryInfo.setAfterScoreNumMap(addupScore.toString());
                                    iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, sic);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取得分级别
     *
     * @param num       人数
     * @param scoreType 组织绩效得分类型 A B+ B B- C D
     */
    public Map getScoreLevelList(int num, String scoreType) {
        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);
                if (!personRelationOrgInfo.getName().equals(scoreType)) {
                    continue;
                }
                Integer ratioPerformanceA = personRelationOrgInfo.getMeritA();
                Integer ratioPerformanceBplus = personRelationOrgInfo.getMeritBplus();
                Integer ratioPerformanceB = personRelationOrgInfo.getMeritB();
                Integer ratioPerformanceBminus = personRelationOrgInfo.getMeritBminus();
                Integer ratioPerformanceC = personRelationOrgInfo.getMeritC();
                Integer ratioPerformanceD = personRelationOrgInfo.getMeritD();

                //计算保留一位小数  formatDecimalOneDecimalPlace留一位小数
                //jsbfb 将百分比转换为小数
                double a = formatDecimalOneDecimalPlace(jsbfb(ratioPerformanceA, num));
                double bPlus = formatDecimalOneDecimalPlace(jsbfb(ratioPerformanceBplus, num));
                double b = formatDecimalOneDecimalPlace(jsbfb(ratioPerformanceB, num));
                double bMinus = formatDecimalOneDecimalPlace(jsbfb(ratioPerformanceBminus, num));
                double c = formatDecimalOneDecimalPlace(jsbfb(ratioPerformanceC, num));
                double d = formatDecimalOneDecimalPlace(jsbfb(ratioPerformanceD, num));

                //存进去map里面用来区分排序后是什么对应什么等级
                Map<String, Double> map = new HashMap();
                map.put("A", a);
                map.put("B+", bPlus);
                map.put("B", b);
                map.put("B-", bMinus);
                map.put("C", c);
                map.put("D", d);
                System.out.println(map.toString());
                //对比相等的数据获取等级优先级
                List<String> scoreGrade = new ArrayList();
                scoreGrade.add("A");
                scoreGrade.add("B+");
                scoreGrade.add("B");
                scoreGrade.add("B-");
                scoreGrade.add("C");
                scoreGrade.add("D");

                List<Map.Entry<String, Double>> list = new LinkedList<>(map.entrySet());

                Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
                    @Override
                    public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
                        // 提取小数点后一位进行比较
                        double o1Value = extractDecimalDigit(o1.getValue());
                        double o2Value = extractDecimalDigit(o2.getValue());
                        return Integer.compare((int) o2Value, (int) o1Value);
                    }
                });
                logger.debug("删除前" + list);
                // 删除值为0的数据
                Iterator<Map.Entry<String, Double>> iterator = list.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Double> entry = iterator.next();
                    if (entry.getValue() == 0) {
                        iterator.remove();
                    }
                }

                logger.debug("删除后" + list);
                //存储每个得分的人数如：{A=1, B=4, C=0, D=0, B+=2}
                Map<String, Integer> scoreMap = new HashMap();
                //计算人数是否多出或少了
                int personNum = 0;
                //获取最后一个数据的
                Map.Entry<String, Double> stringDoubleEntry = list.get(list.size() - 1);
                for (int q = 0; q < list.size(); q++) {
                    Map.Entry<String, Double> upMap = list.get(q);
                    if (q != list.size() - 1) {
                        Map.Entry<String, Double> pgMap = list.get(q + 1);
                        String upKey = upMap.getKey();
                        double upValue = extractDecimalDigit(upMap.getValue());
                        String pg = pgMap.getKey();
                        double pgValue = extractDecimalDigit(pgMap.getValue());
                        if (upValue >= pgValue) {
                            int upMapValue = (int) Math.round(upMap.getValue());
                            personNum += upMapValue;
                            //累计人数大于总人数计算的等级-1
                            if (personNum > num) {
                                scoreMap.put(upMap.getKey(), --upMapValue);
                            } else {
                                scoreMap.put(upMap.getKey(), upMapValue);
                            }
                        }
                    } else {
                        if (num > personNum) {
                            //最后一个数做尾差 总人数-以上已经评分的人数
                            scoreMap.put(upMap.getKey(), num - (personNum));
                        } else if (num == personNum) {
                            scoreMap.put(upMap.getKey(), 0);
                        } else {
                            scoreMap.put(upMap.getKey(), num - (--personNum));
                        }

                    }
                }

                List scoreLevelList = new ArrayList();
                System.out.println(scoreMap);
                for (String key : scoreMap.keySet()) {
                    //得分人数
                    Integer scorePersonNum = scoreMap.get(key);
                    if (key.equals("A")) {
                        getScoreLevel(scoreLevelList, scorePersonNum, "1");
                    }
                    if (key.equals("B+")) {
                        getScoreLevel(scoreLevelList, scorePersonNum, "2");
                    }
                    if (key.equals("B")) {
                        getScoreLevel(scoreLevelList, scorePersonNum, "3");
                    }
                    if (key.equals("B-")) {
                        getScoreLevel(scoreLevelList, scorePersonNum, "4");
                    }
                    if (key.equals("C")) {
                        getScoreLevel(scoreLevelList, scorePersonNum, "5");
                    }
                    if (key.equals("D")) {
                        getScoreLevel(scoreLevelList, scorePersonNum, "6");
                    }
                    numMap2 = new HashMap<>();
                    numMap2.put(key, scorePersonNum);
                    numMap.put(key, numMap2);
                }
                scoreLevelMap.put(personRelationOrgInfo.getName(), scoreLevelList);
                scoreLevelMap.put("numMap", numMap);
                List orderScore = (List) scoreLevelMap.get(personRelationOrgInfo.getName());
                orderScore.sort(null);
                logger.debug("scoreLevelMap:" + scoreLevelMap);
                return scoreLevelMap;
            }
        } catch (BOSException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

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

    /**
     * 修改保存计算得分
     *
     * @param entrys
     * @param iExamineGradePersonEntry
     * @param key
     * @param i
     * @param scoreLevelMap
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    public 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里面的数据  i标ndex-1对应下
            String scoreLeavel = listArray.get(index - 1);
            //获取得分对应人数
            Map<String, Map<String, Integer>> numMap = (Map) scoreLevelMap.get("numMap");
            //累计得分人数
            Map addupScore = new HashMap();
            for (String numMapkey : numMap.keySet()) {
                Map<String, Integer> numMapValue = numMap.get(numMapkey);
                Integer numMapValue2 = null;
                for (String numMap2 : numMapValue.keySet()) {
                    numMapValue2 = numMapValue.get(numMap2);
                }
                addupScore.put(numMapkey, numMapValue2);

            }
            //修改的数据
            examineGradePersonEntryInfo.setScore(scoreEnum.getEnum(scoreLeavel));
            if (examineGradePersonEntryInfo.getScoreLeader() == null) {
                examineGradePersonEntryInfo.setScoreLeader(scoreEnum.getEnum(scoreLeavel));
            }
            examineGradePersonEntryInfo.setAfterScoreNumMap(addupScore.toString());
            iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, sic);
        }
    }

    /**
     * 获取保留一位小数
     *
     * @param number
     * @return
     */
    public double formatDecimalOneDecimalPlace(double number) {
        // 创建DecimalFormat对象，指定保留一位小数但不进行四舍五入
        DecimalFormat df = new DecimalFormat("#.0");

        // 格式化数字
        String formattedNumber = df.format(number);

        // 将字符串转换为double类型
        double roundedNumber = Double.parseDouble(formattedNumber);
        return roundedNumber;
    }

    /**
     * 判断是否存在B-
     *
     * @return
     */
    public boolean isNotExistBMinus(ExamineGradePersonEntryCollection entryCollection) {
        //人数等于5循环判断上季度和本季度是否有B-
        for (int i = 0; i < entryCollection.size(); i++) {
            ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entryCollection.get(i);
            if (examineGradePersonEntryInfo.getScore() != null) {
                if (examineGradePersonEntryInfo.getScore().equals("4")) {
                    return true;
                }
            }

        }
        return false;
    }

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

    /**
     * 获取上季度和当前季度的和 减去当前季度的等级 得到的就是当前季度等级和个人数 进行遍历出来
     *
     * @param listArray
     * @param addupScore
     */
    public void getListArrayGradeNum(List<String> listArray, Map addupScore) {
        Map<String, Integer> countMap = new HashMap<>();
        for (String num : listArray) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }

        // 输出各类型的个数
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            logger.debug("数字 " + entry.getKey() + " 出现了 " + entry.getValue() + " 次");
            if (entry.getKey().equals("1")) {
                addupScore.put("A", entry.getValue());
            }
            if (entry.getKey().equals("2")) {
                addupScore.put("B+", entry.getValue());
            }
            if (entry.getKey().equals("3")) {
                addupScore.put("B", entry.getValue());
            }
            if (entry.getKey().equals("4")) {
                addupScore.put("B-", entry.getValue());
            }
            if (entry.getKey().equals("5")) {
                addupScore.put("C", entry.getValue());
            }
            if (entry.getKey().equals("6")) {
                addupScore.put("D", entry.getValue());
            }
        }
    }

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

    /**
     * 提取小数点后一位
     *
     * @param value
     * @return
     */
    private double extractDecimalDigit(double value) {
        return ((value * 10) % 10);
    }

    /**
     * 同步考核结果
     *
     * @param billID
     * @param isSynUpLastLevelAndUpLastScore 是否同步修正评分和等级字段 true=评分人 false = 专员
     * @throws BOSException
     * @throws EASBizException
     * @throws ShrWebBizException
     * @throws SQLException
     * @throws ParserException
     */
    public void synEvaluationResultAction(String billID, boolean isSynUpLastLevelAndUpLastScore) throws BOSException, EASBizException, ShrWebBizException, SQLException, ParserException {
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("id", billID));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
        IExamineGradePerson iExamineGradePerson = ExamineGradePersonFactory.getLocalInstance(ctx);
        ExamineGradePersonCollection examineGradePersonCollection = iExamineGradePerson.getExamineGradePersonCollection(entityViewInfo);
        StringBuilder sb = new StringBuilder();
        if (examineGradePersonCollection.size() > 0) {
            ExamineGradePersonInfo examineGradePersonInfo = examineGradePersonCollection.get(0);
            int quarter = examineGradePersonInfo.getQuarter();
            int year = examineGradePersonInfo.getYear();
            periodTypeEnum periodType = examineGradePersonInfo.getPeriodType();
            String value = periodType.getValue();
            sb.append(year).append("0" + quarter).append(value.equals("1") ? "M" : "J");
            //查询最高得分和评级
            String sql = "select \n" +
                    "FPersonID as person,\n" +
                    "FPeriodNumber as periodNumber,\n" +
                    "FLastSumScore as lastSumScore,\n" +
                    "FLastGradeLevel as lastGradeLevel\n" +
                    " from T_EVA_EVARESULTSUMMARY resultSummary where FPersonID in (\n" +
                    "select  CFAuditorID from CT_PER_ExamineGradePersonEntry where FParentID ='" + billID + "')\n" +
                    "and  resultSummary.FPeriodTimeNumber = '" + sb.toString() + "'\n and FBillState='3'";

            IRowSet iRowSet = DbUtil.executeQuery(ctx, sql);
            SelectorItemCollection updateSic = new SelectorItemCollection();
            updateSic.add("lastScore");
            updateSic.add("lastLevel");
            updateSic.add("upLastScore");
            updateSic.add("upLastLevel");

            ExamineGradePersonEntryCollection entrys = examineGradePersonInfo.getEntrys();
            ExamineGradePersonEntryInfo entryInfo = null;
            Map<String, ExamineGradePersonEntryInfo> map = new HashMap();

            //保存最高评级和得分
            while (iRowSet.next()) {
                String person = iRowSet.getString("person");
                String lastSumScore = iRowSet.getString("lastSumScore");
                String periodNumber = iRowSet.getString("periodNumber");
                String lastGradeLevel = iRowSet.getString("lastGradeLevel");
                entryInfo = new ExamineGradePersonEntryInfo();
                if (lastSumScore != null || !lastSumScore.equals("")) {
                    entryInfo.setLastScore(new BigDecimal(lastSumScore));
                    entryInfo.setUpLastScore(new BigDecimal(lastSumScore));
                }
                if (lastGradeLevel != null || !lastGradeLevel.equals("")) {
                    String scoreEnumValue = getscoreEnum(lastGradeLevel);
                    if (scoreEnumValue == "") {
                        throw new ShrWebBizException("绩效结果评级装换失败！");
                    }
                    scoreEnum anEnum = scoreEnum.getEnum(scoreEnumValue);
                    entryInfo.setLastLevel(anEnum);
                    entryInfo.setUpLastLevel(anEnum);
                }
                map.put(person, entryInfo);
            }
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            for (int i = 0; i < entrys.size(); i++) {
                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entrys.get(i);
                String string = examineGradePersonEntryInfo.getAuditor().getId().toString();
                if (map.containsKey(string)) {
                    ExamineGradePersonEntryInfo updateEntryInfo = map.get(string);
                    //启动排序同步修正字段，如修正字段有数据则不同步
                    //if (!isSynUpLastLevelAndUpLastScore) {
                    //
                    //} else {
                    //    if (examineGradePersonEntryInfo.getUpLastScore() != updateEntryInfo.getLastScore()) {
                    //        updateSic.removeObject("upLastScore");
                    //    }
                    //    if (examineGradePersonEntryInfo.getUpLastLevel().getValue() != updateEntryInfo.getLastLevel().getValue()) {
                    //        updateSic.removeObject("upLastLevel");
                    //    }
                    //}
                    if (isSynUpLastLevelAndUpLastScore) {
                        if (examineGradePersonEntryInfo.getUpLastScore() != null || examineGradePersonEntryInfo.getLastScore() != null) {
                            if (examineGradePersonEntryInfo.getUpLastScore().compareTo(examineGradePersonEntryInfo.getLastScore()) != 0) {
                                updateSic.removeObject("upLastScore");
                            }
                        }
                        if (examineGradePersonEntryInfo.getUpLastLevel() != null) {
                            if (examineGradePersonEntryInfo.getUpLastLevel() != examineGradePersonEntryInfo.getLastLevel()) {
                                updateSic.removeObject("upLastLevel");
                            }
                        }
                    }
                    examineGradePersonEntryInfo.setUpLastScore(updateEntryInfo.getUpLastScore());
                    examineGradePersonEntryInfo.setUpLastLevel(updateEntryInfo.getUpLastLevel());
                    examineGradePersonEntryInfo.setLastScore(updateEntryInfo.getLastScore());
                    examineGradePersonEntryInfo.setLastLevel(updateEntryInfo.getLastLevel());
                    iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, updateSic);

                }
            }
            //维护顺序
            maintainIndex(billID);
            String adminOrgFilter = getAdminOrgFilter(billID, isSynUpLastLevelAndUpLastScore);
            String[] split = adminOrgFilter.split(",");
            Map isSortedMap = null;
            for (int i = 0; i < split.length; i++) {
                String adminId = split[i];
                ExamineGradePersonEntryCollection entryColl = getCurrentPersonEqualsScore(billID, adminId.substring(1, adminId.length() - 1), isSynUpLastLevelAndUpLastScore);
                //校验顺序
                isSortedMap = isSorted(entryColl);
                //计算得分
                saveScore(isSortedMap, entryColl);
            }
        }
    }

    public void maintainIndex(String billID) throws BOSException {
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        //保存完之后把所有数据排序查询出来再给顺序赋值
        ExamineGradePersonEntryCollection examineGradePersonEntryCollection =
                iExamineGradePersonEntry.getExamineGradePersonEntryCollection("where parent.id = '" + billID + "'");
        SelectorItemCollection updateIndex = new SelectorItemCollection();
        updateIndex.add("index");
        //通过部门排序
        List<ExamineGradePersonEntryInfo> list = new ArrayList();
        for (int i = 0; i < examineGradePersonEntryCollection.size(); i++) {
            list.add(examineGradePersonEntryCollection.get(i));
        }
        Map<String, List<ExamineGradePersonEntryInfo>> groupedByType = list.stream()
                .collect(Collectors.groupingBy(org -> org.getAdminOrg().getId().toString()));

        groupedByType.forEach((type, orgList) -> {
            List<ExamineGradePersonEntryInfo> sortedList = orgList;
            sortedList.sort((o1, o2) -> {
                // 检查 getLastLevel 是否为空
                if (o1.getUpLastLevel() == null && o2.getUpLastLevel() == null) {
                    return 0; // 如果两者都为空，则认为相等
                } else if (o1.getUpLastLevel() == null) {
                    return 1; // o1 的 getLastLevel 为空，排在后面
                } else if (o2.getUpLastLevel() == null) {
                    return -1; // o2 的 getLastLevel 为空，排在后面
                }

                // 现在可以安全地比较 getLastLevel
                int compareNum1 = o1.getUpLastLevel().compareTo(o2.getUpLastLevel());
                if (compareNum1 == 0) {
                    // 如果 getLastLevel 相等，再比较 getLastScore
                    // 检查 getLastLevel 是否为空
                    if (o1.getUpLastScore() == null && o2.getUpLastScore() == null) {
                        return 0; // 如果两者都为空，则认为相等
                    } else if (o1.getUpLastScore() == null) {
                        return 1; // o1 的 getLastScore 为空，排在后面
                    } else if (o2.getUpLastScore() == null) {
                        return -1; // o2 的 getLastScore 为空，排在后面
                    }
                    // 现在可以安全地比较 getLastScore，注意反序排列
                    return o2.getUpLastScore().compareTo(o1.getUpLastScore());
                }
                return compareNum1;
            });

            // 使用 forEachOrdered 设置编号
            IntStream.range(0, sortedList.size())
                    .forEachOrdered(i -> sortedList.get(i).setIndex(i + 1));

            System.out.println("Type: " + type);
            sortedList.forEach(System.out::println);
            System.out.println();
            sortedList.forEach(entry -> {
                try {
                    iExamineGradePersonEntry.updatePartial(entry, updateIndex);
                } catch (BOSException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } catch (EASBizException e) {
                    throw new RuntimeException(e);
                }
            });

        });
    }

    public String getscoreEnum(String score) {
        switch (score) {
            case "A":
                return "1";
            case "B+":
                return "2";
            case "B":
                return "3";
            case "B-":
                return "4";
            case "C":
                return "5";
            case "D":
                return "6";
            default:
                return "";
        }
    }

}
