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

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.bos.util.BOSUuid;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.person.PersonInfo;
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.custom.performancenew.handler.service.ExamineScorePersonService;
import com.kingdee.eas.custom.performancenew.handler.service.impl.ExamineScorePersonServiceImpl;
import com.kingdee.eas.custom.projectbonus.web.vo.*;
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.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.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;

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

    private static Logger logger =
            Logger.getLogger(ExaminePFRDynamicListHandler.class);

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

    ExamineScorePersonService adminOrgFilterService = new ExamineScorePersonServiceImpl();

    //判断是否是提交
    private boolean isSubmitStatus = false;

    /**
     * 比较差异
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws ShrWebBizException
     */
    public void verifyIsEmptyAction(HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelMap modelMap) throws BOSException, 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 {
            String[] split = adminIdArray.split(",");
            for (int i = 0; i < split.length; i++) {
                String adminId = split[i];
                ExamineGradePersonEntryCollection entryColl = adminOrgFilterService.getCurrentPersonEqualsScore(billID, adminId,true);
                for (int j = 0; j < entryColl.size(); j++) {
                    ExamineGradePersonEntryInfo entryInfo = entryColl.get(j);
                    if (entryInfo.getUpLastLevel() == null || entryInfo.getUpLastScore() == null || entryInfo.getScoreLeader() == null) {
                        throw new ShrWebBizException("部门[" + entryInfo.getAdminOrg().getName() + "]其中修正绩效标准得分，修正绩效标准等级，领导计算得分不能为空！");
                    }
                }
            }
        } catch (ParserException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (SHRWebException e) {
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 比较差异
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws ShrWebBizException
     */
    public void contrastDifferenceAction(HttpServletRequest request,
                                         HttpServletResponse response,
                                         ModelMap modelMap) throws BOSException, 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(",");
            List list = new ArrayList();
            for (int i = 0; i < split.length; i++) {
                String adminId = split[i];
                ExamineGradePersonEntryCollection entryColl = adminOrgFilterService.getCurrentPersonEqualsScore(billID, adminId,true);
                for (int j = 0; j < entryColl.size(); j++) {
                    Map map = new HashMap();
                    ExamineGradePersonEntryInfo entryInfo = entryColl.get(j);


                    if (!entryInfo.getUpLastLevel().equals(entryInfo.getLastLevel())
                            || entryInfo.getUpLastScore().compareTo(entryInfo.getLastScore()) != 0
                            || !entryInfo.getScoreLeader().equals(entryInfo.getScore())
                    ) {
                        PersonInfo auditor = entryInfo.getAuditor();//考核人
                        AdminOrgUnitInfo adminOrg = entryInfo.getAdminOrg();//部门
                        map.put("auditor.name", auditor.getName());
                        map.put("auditor.number", auditor.getNumber());
                        map.put("adminorg.name", adminOrg.getName());
                        map.put("entrys.lastscore", entryInfo.getLastScore());
                        map.put("entrys.uplastscore", entryInfo.getUpLastScore());
                        map.put("entrys.lastlevel", entryInfo.getLastLevel());
                        map.put("entrys.uplastlevel", entryInfo.getUpLastLevel());
                        map.put("entrys.scoreleader", entryInfo.getScoreLeader());
                        map.put("entrys.score", entryInfo.getScore());
                        list.add(map);
                    }
                }
            }
            JSONUtils.SUCCESS(list);
        } catch (ParserException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (SHRWebException e) {
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 同步标准绩效结果
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws BOSException
     * @throws EASBizException
     * @throws ShrWebBizException
     */
    public void synStandPerformResultAction(HttpServletRequest request,
                                            HttpServletResponse response,
                                            ModelMap modelMap) throws BOSException, EASBizException, SHRWebException, ParserException, SQLException {
        //同步绩效结果
        adminOrgFilterService.synEvaluationResultAction(request.getParameter("billId"), true);
        JSONUtils.SUCCESS(true);

    }

    /**
     * 操作时校验周期是否锁定
     */
    public void verifyisLockAction(HttpServletRequest request,
                                   HttpServletResponse response,
                                   ModelMap modelMap) throws BOSException, EASBizException, ShrWebBizException {
        adminOrgFilterService.verifyisLock(request.getParameter("billId"));
    }


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

    /**
     * 获取默认编辑列
     *
     * @param request
     * @return
     */
    protected Map<String, Map<String, Object>> getDefultEditColumnsSetting(HttpServletRequest request) {
        try {
            Map<String, Map<String, Object>> result = new HashMap();
            //状态枚举
            EditColumnInfo stateEditColumn = new EditColumnInfo();
            stateEditColumn.setName("entrys.scoreLeader");
            stateEditColumn.setFormatter("shrselect");
            stateEditColumn.setEdittype("shrselect");
            stateEditColumn.setType("shrselect");
            EditOptions stateEditoptions = stateEditColumn.getEditoptions();
            stateEditoptions.setUrlSource("com.kingdee.eas.custom.performancenew.app.scoreEnum");
            SelectJson selectJson = stateEditoptions.getSelectJson();
            selectJson.setId("setScoreLeader");//方法名称
            selectJson.setName("scoreLeader");//属性名称
            selectJson.setEnumSource("com.kingdee.eas.custom.performancenew.app.scoreEnum");
            result.put("entrys.scoreLeader", stateEditColumn.convertToMap());
            //状态枚举
            EditColumnInfo stateEditColumn1 = new EditColumnInfo();
            stateEditColumn1.setName("entrys.upLastLevel");
            stateEditColumn1.setFormatter("shrselect");
            stateEditColumn1.setEdittype("shrselect");
            stateEditColumn1.setType("shrselect");
            EditOptions stateEditoptions1 = stateEditColumn1.getEditoptions();
            stateEditoptions1.setUrlSource("com.kingdee.eas.custom.performancenew.app.scoreEnum");
            SelectJson selectJson1 = stateEditoptions1.getSelectJson();
            selectJson1.setId("setUpLastLevel");//方法名称
            selectJson1.setName("upLastLevel");//属性名称
            selectJson1.setEnumSource("com.kingdee.eas.custom.performancenew.app.scoreEnum");
            result.put("entrys.upLastLevel", stateEditColumn1.convertToMap());

            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 动态表单保存
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     * @returnA
     */
    public void saveDynGridAction(HttpServletRequest request,
                                  HttpServletResponse response,
                                  ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        try {
            List<Map<String, String>> dataList = (List) JSONUtils.convertJsonToObject(request.getParameter("modi"), List.class);
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            //待更新数据集合
            Map<String, ExamineGradePersonEntryInfo> updEntryCols = new HashMap<String, ExamineGradePersonEntryInfo>();
            //待更新字段
            Map<String, SelectorItemCollection> updSics = new HashMap<String, SelectorItemCollection>();
            String entryId = null;
            String billId = null;
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, String> map = dataList.get(i);
                ExamineGradePersonEntryInfo entryInfo;
                SelectorItemCollection updSic;
                String fid = map.get("fid");
                billId = map.get("billId");

                //保存修改数据
                if (updEntryCols.containsKey(fid)) {
                    entryInfo = updEntryCols.get(fid);
                } else {
                    entryInfo = new ExamineGradePersonEntryInfo();
                    entryInfo.setId(BOSUuid.read(fid));
                    updEntryCols.put(fid, entryInfo);
                }
                //保存修改字段
                if (updSics.containsKey(fid)) {
                    updSic = updSics.get(fid);
                } else {
                    updSic = new SelectorItemCollection();
                    updSics.put(fid, updSic);
                }
                //字段名称
                String colName = map.get("column");
                if ("scoreleader".equals(colName)) {
                    entryId = fid;
                }
                //修改值
                Object value = map.get("value");
                //值类型
                String type = map.get("type");
                if ("Integer".equals(type)) {
                    value = Double.parseDouble(value.toString());
                }
                if ("BigDecimal".equals(type) && (value == null || value.equals(""))) {
                    value = BigDecimal.ZERO;
                }
                updSic.add(colName);
                entryInfo.put(colName, value);
            }
            for (String id : updEntryCols.keySet()) {
                //修改的实体
                ExamineGradePersonEntryInfo entryInfo = updEntryCols.get(id);
                //修改的字段
                SelectorItemCollection updSic = updSics.get(id);
                iExamineGradePersonEntry.updatePartial(entryInfo, updSic);
            }
            if (!StringUtils.isEmpty(entryId)) {

                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(entryId));
                //获取修改领导计算得分这条数据的考核周期和部门
                ExamineGradePersonInfo parent = examineGradePersonEntryInfo.getParent();
                AdminOrgUnitInfo adminOrg = examineGradePersonEntryInfo.getAdminOrg();
                //每次修改领导计算得分是重新计算得分人数到afterScoreNumMap这个字段上面
                updateAfterScoreNumMap(parent.getId().toString(), adminOrg.getId().toString());
            }
            adminOrgFilterService.maintainIndex(billId);
            JSONUtils.SUCCESS("成功修改" + dataList.size() + "条数据");
        } catch (
                Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 每次修改领导计算得分是重新计算得分人数到afterScoreNumMap这个字段上面
     */
    public void updateAfterScoreNumMap(String billId, String adminOrgId) {
        SelectorItemCollection updateSic = new SelectorItemCollection();
        updateSic.add("afterScoreNumMap");
        List listA = new ArrayList();
        List listBplus = new ArrayList();
        List listB = new ArrayList();
        List listBmins = new ArrayList();
        List listC = new ArrayList();
        List listD = new ArrayList();
        Map<String, Integer> map = new HashMap();
        try {
            IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
            ExamineGradePersonEntryCollection currentPersonEqualsScore = adminOrgFilterService.getCurrentPersonEqualsScore(billId, adminOrgId,true);
            for (int i = 0; i < currentPersonEqualsScore.size(); i++) {
                ExamineGradePersonEntryInfo entrysInfo = currentPersonEqualsScore.get(i);
                if (entrysInfo.getScoreLeader() != null) {
                    switch (entrysInfo.getScoreLeader().toString()) {
                        case "A":
                            listA.add(entrysInfo);
                            map.put("A", listA.size());
                            break;
                        case "B+":
                            listBplus.add(entrysInfo);
                            map.put("B+", listBplus.size());
                            break;
                        case "B":
                            listB.add(entrysInfo);
                            map.put("B", listB.size());
                            break;
                        case "B-":
                            listBmins.add(entrysInfo);
                            map.put("B-", listBmins.size());
                            break;
                        case "C":
                            listC.add(entrysInfo);
                            map.put("C", listC.size());
                            break;
                        case "D":
                            listD.add(entrysInfo);
                            map.put("D", listD.size());
                            break;
                    }
                }
            }
            //修改数据
            for (int i = 0; i < currentPersonEqualsScore.size(); i++) {
                ExamineGradePersonEntryInfo entrysInfo = currentPersonEqualsScore.get(i);
                entrysInfo.setAfterScoreNumMap(map.toString());
                iExamineGradePersonEntry.updatePartial(entrysInfo, updateSic);
            }
        } catch (BOSException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (EASBizException e) {
            throw new RuntimeException(e);
        } catch (ParserException 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和已选择部门不能为空！");
        }
        isSubmitStatus = true;
        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];
                //每次修改领导计算得分是重新计算得分人数到afterScoreNumMap这个字段上面
                updateAfterScoreNumMap(billID, adminId);
                ExamineGradePersonEntryCollection entryColl = adminOrgFilterService.getCurrentPersonEqualsScore(billID, adminId,true);
                //校验顺序
                isSortedMap = isSorted(entryColl);
                //计算得分
                saveScore(isSortedMap, entryColl);
                for (int j = 0; j < entryColl.size(); j++) {
                    ExamineGradePersonEntryInfo entryInfo = entryColl.get(j);
                    entryInfo.setOrderStatuc(orderStatucEnum.submitted);
                    iExamineGradePersonEntry.updatePartial(entryInfo, sic);
                }
            }
            JSONUtils.SUCCESS(split.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(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 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 {
            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 = adminOrgFilterService.getCurrentPersonEqualsScore(billID, adminId,true);
                //校验顺序
                isSortedMap = isSorted(entryColl);
                //计算得分
                saveScore(isSortedMap, entryColl);
            }
            JSONUtils.SUCCESS(isSortedMap);
        } catch (SHRWebException | EASBizException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (ParserException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 保存计算得分
     *
     * @param map    key 部门ID 人数 和部门等级
     * @param entrys
     * @throws BOSException
     * @throws EASBizException
     */
    private 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);
                logger.debug("Key: " + key + ", Value: " + depPersonNum);
                //获取组织得分
                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);
                                    if (!isBMinus) {
                                        //dqEntryCollection当前季度数据
                                        isBMinus = isNotExistBMinus(dqEntryCollection);
                                    }
                                }
                            }


                            //修改计算得分和领导计算得分
                            SelectorItemCollection sic = new SelectorItemCollection();
                            sic.add("score");
                            if (!isSubmitStatus) {
                                sic.add("scoreLeader");
                            }
                            sic.add("afterScoreNumMap");
                            //获取得分数据
                            Map<String, List<String>> scoreLevelMap = getScoreLevelList(entryCollection.size(), adminOrgScore);
                            //只进一次循环
                            boolean isTrue = true;
                            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);
                                    //判断长度是否相等
                                    //if (dqEntryCollection.size() == 5 && !isBMinus) {
                                    //    listArray.set(listArray.size() - 1, "4");
                                    //}
                                    for (int j = 0; j < upList.size(); j++) {
                                        listArray.remove(listArray.size() - 1);
                                    }
                                    //在循环只需要循环一次
                                    if (isTrue) {
                                        isTrue = false;
                                        //人员恰好等于五人是判断上个季度是否有B-没有这本周期必须要有一个B-
                                        if (dqEntryCollection.size() == 5 && !isBMinus) {
                                            //4=B- 3=B 循环判断B或者B-的下标在哪里，在给下一个下标赋值为B-
                                            for (int z = listArray.size() - 1; z >= 0; z--) {
                                                String str = listArray.get(z);
                                                if (str == "4" || str == "3") {
                                                    //如果最后一个值就是或者B-就
                                                    if (listArray.size() == z + 1) {
                                                        listArray.set(z, "4");
                                                    } else {
                                                        listArray.set(z + 1, "4");
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }

                                    //通过顺序号获取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 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());
            }
        }
    }

    /**
     * 判断是否存在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.getScoreLeader().getValue().equals("4")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 过滤提交按钮的行政组织F7数据
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void submitFilterAdminAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws
            SHRWebException {
        String billID = request.getParameter("billId");
        JSONUtils.SUCCESS(adminOrgFilterService.getAdminOrgFilter(billID,true));
    }

///**
    // * 过滤提交按钮的行政组织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) {
    //        e.printStackTrace();
    //        throw new RuntimeException(e);
    //    } catch (BOSException e) {
    //        throw new RuntimeException(e);
    //    } catch (SHRWebException e) {
    //        throw new RuntimeException(e);
    //    }
    //}

    /**
     * 实现数组的减法操作
     *
     * @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
     */
    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");
        //提交进来的不需要修改领导计算得分
        if (!isSubmitStatus) {
            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));
            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 value
     * @return
     */
    private double extractDecimalDigit(double value) {
        return ((value * 10) % 10);
    }

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

    /**
     * 获取保留一位小数
     *
     * @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;
    }

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

    /**
     * 校验是否存在顺序重复或断层,和保存计算得分
     *
     * @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<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() + "] 中的顺序不符合规则!!");
            }
        }
        map.put("maxNumberMap", maxNumberMap);
        map.put("adminGradeMap", adminGradeMap);
        return map;
    }

    ///**
    // * 获取当前登录人等于评分人的数据
    // *
    // * @param billID
    // * @return
    // */
    //public ExamineGradePersonEntryCollection getCurrentPersonEqualsScore(String billID, String adminID) throws ParserException, BOSException {
    //    //当前登录员工id
    //    String currentPersonId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
    //    SelectorItemCollection sic = new SelectorItemCollection();
    //
    //    sic.add("*");
    //    sic.add("adminOrg.*");
    //    sic.add("performanceScoreOrg.*");
    //    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 (!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
     */
    private void getHheFilteredData(ExamineGradePersonEntryCollection entrys) {
        //当前登录员工id
        String currentPersonId = ContextUtil.getCurrentUserInfo(ctx).getPerson().getId().toString();
        for (int i = entrys.size() - 1; i >= 0; i--) {
            ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entrys.get(i);
            //评分人id
            String scorerId = examineGradePersonEntryInfo.getScorer().getId().toString();
            //排序的数据
            orderStatucEnum orderStatus = examineGradePersonEntryInfo.getOrderStatuc();
            if (!currentPersonId.equals(scorerId)) {
                entrys.remove(examineGradePersonEntryInfo);
            }
        }
        //过滤显示已启动排序的数据
        for (int i = entrys.size() - 1; i >= 0; i--) {
            ExamineGradePersonEntryInfo examineGradePersonEntryInfo = entrys.get(i);
            //排序的数据
            orderStatucEnum orderStatus = examineGradePersonEntryInfo.getOrderStatuc();
            if (orderStatus == null || !orderStatus.equals(orderStatucEnum.startOrder)) {
                entrys.remove(examineGradePersonEntryInfo);
            }
        }
    }

    @Override
    protected FilterInfo assembleFilterInfo(HttpServletRequest request, Map<String, String> params,
                                            Map filterCondition, Date effectDate) throws SHRWebException {
        FilterInfo filterInfo = super.assembleFilterInfo(request, params, filterCondition, effectDate);
        try {

            String custom_params = request.getParameter("custom_params");
            if (!StringUtils.isEmpty(custom_params)) {
                FilterInfo 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.id", null, CompareType.NOTEQUALS));
                customFilter.getFilterItems().add(new FilterItemInfo("entrys.orderStatuc", "2", CompareType.NOTEQUALS));
                filterInfo.mergeFilter(customFilter, "AND");
            }
            return filterInfo;
        } catch (BOSException e) {
            e.printStackTrace();
            throw new SHRWebException(e);
        }
    }

}
