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.common.EASBizException;
import com.kingdee.eas.custom.expandassess.ExpandAssessEntryCollection;
import com.kingdee.eas.custom.expandassess.ExpandAssessEntryInfo;
import com.kingdee.eas.custom.expandassess.IExpandAssessEntry;
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.performancenew.task.IPerformancenewFacade;
import com.kingdee.eas.custom.performancenew.task.PerformancenewFacadeFactory;
import com.kingdee.eas.custom.projectbonus.web.vo.*;
import com.kingdee.eas.hr.ats.AtsUtil;
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.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.json.GridDataEntity;
import com.kingdee.shr.base.syssetting.web.handler.DynamicListHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.util.StringUtils;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author qingwu
 * @date 2024/4/10
 * @apiNote 绩效管理  专员维护考核人和评分人页面 （专员）
 * EmpBatchEnrollListHandler
 */
public class ExamineZYDynamicListHandler extends DynamicListHandler {

    private Context ctx = SHRContext.getInstance().getContext();
    ExamineScorePersonService adminOrgFilterService = new ExamineScorePersonServiceImpl();

    ///**
    // * 同步考核结果
    // *
    // * @param billID
    // * @param isSynUpLastLevelAndUpLastScore 是否同步修正评分和等级字段
    // * @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("upLastScore");
    //        updateSic.add("lastLevel");
    //        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);
    //                examineGradePersonEntryInfo.setLastScore(updateEntryInfo.getLastScore());
    //                examineGradePersonEntryInfo.setUpLastScore(updateEntryInfo.getUpLastScore());
    //                examineGradePersonEntryInfo.setUpLastLevel(updateEntryInfo.getUpLastLevel());
    //                examineGradePersonEntryInfo.setLastLevel(updateEntryInfo.getLastLevel());
    //                iExamineGradePersonEntry.updatePartial(examineGradePersonEntryInfo, updateSic);
    //            }
    //        }
    //        //保存完之后把所有数据排序查询出来再给顺序赋值
    //        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);
    //                }
    //            });
    //
    //        });
    //        String adminOrgFilter = adminOrgFilterService.getAdminOrgFilter(billID);
    //        String[] split = adminOrgFilter.split(",");
    //        Map isSortedMap = null;
    //        for (int i = 0; i < split.length; i++) {
    //            String adminId = split[i];
    //            ExamineGradePersonEntryCollection entryColl = adminOrgFilterService.getCurrentPersonEqualsScore(billID, adminId.substring(1, adminId.length() - 1));
    //            //校验顺序
    //            isSortedMap = adminOrgFilterService.isSorted(entryColl);
    //            //计算得分
    //            adminOrgFilterService.saveScore(isSortedMap, entryColl);
    //        }
    //    }
    //}


    /**
     * 催办
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void prassAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws ShrWebBizException {
        String billID = request.getParameter("billId");
        try {
            IPerformancenewFacade iPerformancenewFacade = PerformancenewFacadeFactory.getLocalInstance(ctx);
            JSONUtils.SUCCESS(iPerformancenewFacade.warnScorer(billID));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

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

    /**
     * customDelete  删除
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public void customDeleteAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException, EASBizException {
        //获取删除ID
        String idArray = request.getParameter("idArray");
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        FilterInfo filterInfo = new FilterInfo();
        filterInfo.getFilterItems().add(new FilterItemInfo("id", AtsUtil.toSet(idArray), CompareType.INCLUDE));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
        ExamineGradePersonEntryCollection examineGradePersonEntryCollection = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
        if (examineGradePersonEntryCollection.size() > 0) {
            for (int i = 0; i < examineGradePersonEntryCollection.size(); i++) {
                ExamineGradePersonEntryInfo examineGradePersonEntryInfo = examineGradePersonEntryCollection.get(i);
                if (examineGradePersonEntryInfo.getOrderStatuc() == (orderStatucEnum.submitted) ||
                        examineGradePersonEntryInfo.getOrderStatuc() == (orderStatucEnum.startOrder)) {
                    throw new ShrWebBizException("只能删除未启用排序的数据！！");
                }
            }
        }
        iExamineGradePersonEntry.delete(filterInfo);
    }

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

    @Override
    protected void afterGetListData(HttpServletRequest request, HttpServletResponse response, GridDataEntity gridDataEntity) throws SHRWebException {
        List<Map<String, Object>> rows = gridDataEntity.getRows();
        //封装F7部门对象
        for (int i = 0; i < rows.size(); i++) {
            Map<String, Object> map = rows.get(i);
            Map<String, Object> colNameMap = null;
            //部门
            Object adminOrgID = map.get("adminorg.id");
            if (adminOrgID != null && !StringUtils.isEmpty(adminOrgID.toString())) {
                colNameMap = new HashMap<String, Object>();
                colNameMap.put("id", adminOrgID.toString());
                colNameMap.put("name", map.get("adminorg.name"));
                //部门
                map.put("adminorg.name", colNameMap);
            }
            //考核人
            Object auditorId = map.get("auditor.id");
            if (auditorId != null && !StringUtils.isEmpty(auditorId.toString())) {
                colNameMap = new HashMap<String, Object>();
                colNameMap.put("id", auditorId.toString());
                colNameMap.put("name", map.get("auditor.name"));
                map.put("auditor.name", colNameMap);
            }
            //评分人
            Object scorerId = map.get("scorer.id");
            if (scorerId != null && !StringUtils.isEmpty(scorerId.toString())) {
                colNameMap = new HashMap<String, Object>();
                colNameMap.put("id", scorerId.toString());
                colNameMap.put("name", map.get("scorer.name"));
                //部门
                map.put("scorer.name", colNameMap);
            }
        }
    }

    /**
     * 获取默认编辑列
     *
     * @param request
     * @return
     */
    protected Map<String, Map<String, Object>> getDefultEditColumnsSetting(HttpServletRequest request) {
        try {
            Map<String, Map<String, Object>> result = new HashMap();
            //部门
            EditColumnInfo editColumnAuditorInfo4 = new EditColumnInfo();
            editColumnAuditorInfo4.setName("adminorg.name");
            //必填
            editColumnAuditorInfo4.setRequired(true);
            EditOptions editoptions4 = editColumnAuditorInfo4.getEditoptions();
            F7Json f7Json4 = editoptions4.getF7Json();
            SubWidgetOptions subWidgetOptions4 = f7Json4.getSubWidgetOptions();
            subWidgetOptions4.setUipk("shr.AllAdminOrgUnit.F7");
            subWidgetOptions4.setTitle("请选择部门");
            subWidgetOptions4.setQuery("");
            result.put("adminorg.name", editColumnAuditorInfo4.convertToMap());
            //考核人
            EditColumnInfo editColumnAuditorInfo2 = new EditColumnInfo();
            //必填
            editColumnAuditorInfo2.setRequired(true);
            editColumnAuditorInfo2.setName("auditor.name");
            EditOptions editoptions2 = editColumnAuditorInfo2.getEditoptions();
            F7Json f7Json2 = editoptions2.getF7Json();
            SubWidgetOptions subWidgetOptions2 = f7Json2.getSubWidgetOptions();
            subWidgetOptions2.setUipk("com.kingdee.eas.basedata.person.app.PersonQwEx.F7");
            subWidgetOptions2.setTitle("请选择考核人");
            //subWidgetOptions2.setQuery("com.kingdee.eas.hr.emp.emp_page.QwCostomPersonQuery");
            subWidgetOptions2.setQuery("com.kingdee.eas.hr.emp.app.PersonWebListQuery");
            result.put("auditor.name", editColumnAuditorInfo2.convertToMap());
            //评分人
            EditColumnInfo editColumnAuditorInfo3 = new EditColumnInfo();
            //必填
            editColumnAuditorInfo3.setRequired(true);
            editColumnAuditorInfo3.setName("scorer.name");
            EditOptions editoptions3 = editColumnAuditorInfo3.getEditoptions();
            F7Json f7Json3 = editoptions3.getF7Json();
            SubWidgetOptions subWidgetOptions3 = f7Json3.getSubWidgetOptions();
            subWidgetOptions3.setUipk("com.kingdee.eas.basedata.person.app.PersonQwEx.F7");
            subWidgetOptions3.setTitle("请选择评分人");
            //subWidgetOptions3.setQuery("com.kingdee.eas.hr.emp.emp_page.QwCostomPersonQuery");
            subWidgetOptions3.setQuery("com.kingdee.eas.hr.emp.app.PersonWebListQuery");
            result.put("scorer.name", editColumnAuditorInfo3.convertToMap());
            //状态枚举
            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());
            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>();
            int succeedNum = 0;
            int errorNum = 0;
            for (int i = 0; i < dataList.size(); i++) {
                Map<String, String> map = dataList.get(i);
                ExamineGradePersonEntryInfo entryInfo;
                SelectorItemCollection updSic;
                String fid = map.get("fid");
                //保存修改数据
                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");

                //修改值
                String value = map.get("value");
                //值类型
                String type = map.get("type");
                updSic.add(colName);
                entryInfo.put(colName, value);
            }
            List list = new ArrayList();
            for (String id : updEntryCols.keySet()) {
                //修改的实体
                ExamineGradePersonEntryInfo entryInfo = updEntryCols.get(id);
                //修改的字段
                SelectorItemCollection updSic = updSics.get(id);
                String msg = updSic.toString();
                String[] split = msg.split(",");
                Map map = new HashMap();
                for (int i = 0; i < split.length; i++) {
                    String s = split[i];
                    if (s.equals("auditor") || s.equals("adminorg")) {
                        map.put(s, s);
                    }
                }
                Boolean is = true;
                if (map.get("auditor") != null && map.get("adminorg") != null) {
                    is = existsByAssessorAndAdminOrg(entryInfo, list);
                }
                if (map.get("auditor") != null && map.get("adminorg") == null) {
                    ExamineGradePersonEntryInfo examineGradePersonEntryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(entryInfo.getId()));
                    entryInfo.put("adminOrg", examineGradePersonEntryInfo.getAdminOrg().getId());
                    is = existsByAssessorAndAdminOrg(entryInfo, list);
                }
                if (map.get("auditor") == null && map.get("adminorg") != null) {
                    ExamineGradePersonEntryInfo examineGradePersonEntryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(entryInfo.getId()));
                    entryInfo.put("assessor", examineGradePersonEntryInfo.getAuditor().getId());
                    is = existsByAssessorAndAdminOrg(entryInfo, list);
                }
                if (is) {
                    iExamineGradePersonEntry.updatePartial(entryInfo, updSic);
                    succeedNum++;
                } else {
                    errorNum++;
                }

            }
            StringBuilder sb = new StringBuilder();
            sb.append("成功修改" + succeedNum + "条数据\n修改失败" + errorNum + "条数据");
            if (errorNum > 0) {
                sb.append(",失败原因：数据重复！！");
            }
            JSONUtils.SUCCESS(sb);
            //iExamineGradePersonEntry.updatePartial(entryInfo, updSic);
            //JSONUtils.SUCCESS("成功修改" + dataList.size() + "条数据");
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }

    }

    private Boolean existsByAssessorAndAdminOrg(ExamineGradePersonEntryInfo entryInfo, List list) throws BOSException, EASBizException {
        IExamineGradePersonEntry iExamineGradePersonEntry = ExamineGradePersonEntryFactory.getLocalInstance(ctx);
        ExamineGradePersonEntryInfo examineGradePersonEntryInfo = iExamineGradePersonEntry.getExamineGradePersonEntryInfo(new ObjectUuidPK(entryInfo.getId()));
        FilterInfo filterInfo = new FilterInfo();
        filterInfo.getFilterItems().add(new FilterItemInfo("parent.id", examineGradePersonEntryInfo.getParent().getId()));
        filterInfo.getFilterItems().add(new FilterItemInfo("auditor.id", entryInfo.get("auditor")));
        filterInfo.getFilterItems().add(new FilterItemInfo("adminOrg.id", entryInfo.get("adminOrg")));
        EntityViewInfo entityViewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
        ExamineGradePersonEntryCollection examineGradePersonEntryCollection = iExamineGradePersonEntry.getExamineGradePersonEntryCollection(entityViewInfo);
        //判断是否存在
        if (examineGradePersonEntryCollection.size() > 0) {
            ExamineGradePersonEntryInfo entryinfo = examineGradePersonEntryCollection.get(0);
            list.add(entryinfo.getAuditor().getName());
            return false;
        }
        return true;
    }

    @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));
                filterInfo.mergeFilter(customFilter, "AND");
            }
            return filterInfo;
        } catch (BOSException e) {
            e.printStackTrace();
            throw new SHRWebException(e);
        }
    }

    /**
     * 锁定周期
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void periodLockAction(HttpServletRequest request,
                                 HttpServletResponse response,
                                 ModelMap modelMap) throws BOSException, EASBizException, ShrWebBizException {
        try {
            String billId = request.getParameter("billId");
            ExamineGradePersonEntryCollection entrys = getCurrentPersonEqualsScore(billId, null);
            for (int i = 0; entrys != null && i < entrys.size(); i++) {
                ExamineGradePersonEntryInfo entry = entrys.get(i);
                if (entry.getOrderStatuc() != orderStatucEnum.submitted) {
                    throw new ShrWebBizException(entry.getAdminOrg().getName() + "的[" + entry.getAuditor().getName() + "] 排序状态为未提交，不可锁定周期！");
                }
            }
            ExamineGradePersonFactory.getLocalInstance(ctx).periodLock(billId);
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        } catch (ParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解除周期
     *
     * @param request
     * @param response
     * @param modelMap
     */
    public void periodUnlockAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws EASBizException, ShrWebBizException {
        try {
            String billId = request.getParameter("billId");
            ExamineGradePersonFactory.getLocalInstance(ctx).periodUnlock(billId);
        } catch (BOSException e) {
            throw new ShrWebBizException(e.getMessage());
        }
    }

    /**
     * 反启动排序
     */
    public void closeOrderAction(HttpServletRequest request,
                                 HttpServletResponse response,
                                 ModelMap modelMap) throws ShrWebBizException {
        String entryId = request.getParameter("entryId");
        try {
            if (StringUtils.isEmpty(entryId)) {
                throw new ShrWebBizException("请勾选需要反启用的数据！！");
            }
            ExamineGradePersonFactory.getLocalInstance(ctx).closeOrder(entryId);
        } catch (BOSException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 启动排序
     */
    public void startOrderAction(HttpServletRequest request,
                                 HttpServletResponse response,
                                 ModelMap modelMap) throws SHRWebException {
        try {
            Set<String> set = new HashSet<>();
            List<ExamineGradePersonEntryInfo> list = new ArrayList();
            String billId = request.getParameter("billId");


            ExamineGradePersonEntryCollection entrys = getCurrentPersonEqualsScore(billId, null);
            for (int i = 0; entrys != null && i < entrys.size(); i++) {
                ExamineGradePersonEntryInfo entry = entrys.get(i);
                if (!set.contains(entry.getScorer().getId().toString())) {
                    set.add(entry.getScorer().getId().toString());
                    list.add(entry);
                }
                if (entry.getAdminOrg() == null || entry.getAuditor() == null || entry.getScorer() == null) {
                    throw new ShrWebBizException("[部门/考核人/评分人]数据不可为空，请检查数据!!");
                }
                String depName = entry.getAdminOrg().getName();
                if (entry.getPerformanceScoreOrg() == null) {
                    throw new ShrWebBizException("部门[" + depName + "] 没有维护组织绩效得分!");
                }
            }
            ExamineGradePersonFactory.getLocalInstance(ctx).startOrder(billId);
            //同步绩效结果
            adminOrgFilterService.synEvaluationResultAction(billId, false);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e.getMessage());
        }
    }

    /**
     * 获取分录数据
     *
     * @param billID
     * @return
     */
    public ExamineGradePersonEntryCollection getCurrentPersonEqualsScore(String billID,
                                                                         String adminID) throws ParserException, BOSException {

        SelectorItemCollection sic = new SelectorItemCollection();
        sic.add("*");
        sic.add("adminOrg.*");
        sic.add("auditor.*");
        sic.add("performanceScoreOrg.*");
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("parent.id", billID));
        if (!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);
    }

}
