package com.kingdee.eas.custom.perfweb.portal.handler;

import com.google.gson.Gson;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.query.server.PagingHelper;
import com.kingdee.bos.framework.ejb.EJBFactory;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.sql.KSqlUtil;
import com.kingdee.cbos.process.vm.internal.t.a.Int;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;
import com.kingdee.shr.base.syssetting.app.filter.HRFilterUtils;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;
import com.kingdee.shr.perfweb.app.base.distribution.*;
import com.kingdee.shr.perfweb.app.base.evalplan.*;
import com.kingdee.shr.perfweb.app.base.evalrule.PerformanceRuleInfo;
import com.kingdee.shr.perfweb.app.base.perfmancescore.*;
import com.kingdee.shr.perfweb.app.exception.SHRPerfWebBizException;
import com.kingdee.shr.perfweb.portal.bean.EvaObjBean;
import com.kingdee.shr.perfweb.portal.bean.EvaPerfPeriodBean;
import com.kingdee.shr.perfweb.portal.bean.TeamTargetCommentBean;
import com.kingdee.shr.perfweb.portal.handler.PerfPersonalScoreHandler;
import com.kingdee.shr.perfweb.util.GetEntityInfoUtils;
import com.kingdee.shr.perfweb.util.PerfPortalUtils;
import com.kingdee.shr.perfweb.utils.PerfwebStrUtils;
import com.kingdee.util.db.SQLUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import shaded.org.apache.parquet.Strings;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.kingdee.shr.perfweb.util.PerfPortalUtils.assembleEvaObjBean;

public class PerfPersonalScoreHandlerEx extends PerfPersonalScoreHandler {
    private static Logger logger = LoggerFactory.getLogger(PerfPersonalScoreHandler.class);
    public void getDistributionInfoAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        HashMap resultMap = new HashMap();
        try {
            String periodId = request.getParameter("periodId");
            Assert.notNull(periodId);
            IPerfPeriod iPerfPeriod = PerfPeriodFactory.getLocalInstance(ctx);
            PerfPeriodInfo perfPeriodInfo = iPerfPeriod.getPerfPeriodInfo("select id,name,perfPlan.id,perfPlan.name,perfRule.id,perfRule.name,perfRule.*  where id ='" + periodId + "' ");
            Map<String, PerfScorLevelDefineInfo> leveMap = new LinkedHashMap();
            Map<String, Integer> leveStrMap = new LinkedHashMap();
            if (perfPeriodInfo != null) {
                PerformanceRuleInfo perfRule = perfPeriodInfo.getPerfRule();
                if (perfRule != null) {
                    PerfScoreLevelInfo perfRate = perfRule.getPerfRate();
                    if (perfRate != null) {
                        PerfScorLevelDefineCollection perfLevelDefInfoCol = perfRate.getPerfLevelDefInfo();
                        if (perfLevelDefInfoCol == null || perfLevelDefInfoCol.size() <= 0) {
                            IPerfScorLevelDefine iPerfScorLevelDefine = PerfScorLevelDefineFactory.getLocalInstance(ctx);
                            perfLevelDefInfoCol = iPerfScorLevelDefine.getPerfScorLevelDefineCollection("  where perfScoreLevel='" + perfRate.getId().toString() + "' order by showNumber ASC ");
                        }

                        if (perfLevelDefInfoCol != null && perfLevelDefInfoCol.size() > 0) {
                            for (int i = 0; i < perfLevelDefInfoCol.size(); ++i) {
                                PerfScorLevelDefineInfo perfScorLevelDefineInfo = perfLevelDefInfoCol.get(i);
                                leveMap.put(perfScorLevelDefineInfo.getId().toString(), perfScorLevelDefineInfo);
                            }
                        }
                    }
                }
            }

            Set<Map.Entry<String, PerfScorLevelDefineInfo>> entries = leveMap.entrySet();
            Iterator var21 = entries.iterator();

            while (var21.hasNext()) {
                Map.Entry<String, PerfScorLevelDefineInfo> entry = (Map.Entry) var21.next();
                leveStrMap.put(((PerfScorLevelDefineInfo) entry.getValue()).getPerfLevelName(), 0);
            }

            String personId = HRFilterUtils.getCurrentPersonId(ctx);
            StringBuffer selectBuf = new StringBuffer("SELECT t.fid as taskNodeId, FEvaobjId,FScoreStatus, FNODEGRADE  FROM T_EVA_GradeTaskNodeInst t INNER JOIN T_EVA_PerfevaObject o ON ");
            selectBuf.append(" t.FEvaobjId=o.FID ").append(" WHERE t.FNodeHandlerID='").append(personId).append("'").append(" AND t.FIsEffective='").append("1").append("'").append(" AND t.FScoreStatus not in ('").append("3").append("') ").append(" AND t.FPeriodID ='").append(periodId).append("'").append(" AND t.FIsSelf=").append(0);
            IRowSet rowSet = DbUtil.executeQuery(ctx, selectBuf.toString());
            if (perfPeriodInfo != null) {
                resultMap.put("perfPeriod", perfPeriodInfo.getName());
            }

            if (perfPeriodInfo.getPerfPlan() != null) {
                resultMap.put("perfPlan", perfPeriodInfo.getPerfPlan().getName());
            }

            resultMap.put("all", rowSet.size());
            HashSet scoredSet = new HashSet();

            try {
                while (rowSet.next()) {
                    String status = rowSet.getString("FScoreStatus");
                    if ("1".equalsIgnoreCase(status) || "2".equalsIgnoreCase(status) || "5".equalsIgnoreCase(status)) {
                        scoredSet.add(rowSet.getString("taskNodeId"));
                        String grade = rowSet.getString("FNODEGRADE");
                        if (StringUtils.isNotBlank(grade)) {
                            leveStrMap.put(grade, leveStrMap.get(grade) == null ? 0 : (Integer) leveStrMap.get(grade) + 1);
                        }
                    }
                }
            } catch (SQLException var18) {
                throw new BOSException(var18);
            }


            IDistribution iDistribution = DistributionFactory.getLocalInstance(ctx);
            DistributionInfo distributionInfo = iDistribution.getDistributionInfo("select * where number ='01' ");
            IDistributionDefine iDistributionDefine = DistributionDefineFactory.getLocalInstance(ctx);
            FilterInfo filterInfo = new FilterInfo();
            filterInfo.getFilterItems().add(new FilterItemInfo("distribution.number", "01"));
//            SelectorItemCollection sic = new SelectorItemCollection();
//            sic.add("");
            EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
            // coll = iDistributionDefine.getDistributionDefineCollection("select *,refDefine.id,refDefine.name,refDefine.number, distribution.perfScoreLevel.perfScoreInfo.* where distribution ='" + id + "' order by index asc");
            DistributionDefineCollection defineCollection = iDistributionDefine.getDistributionDefineCollection(viewInfo);
            // 获取总数（从resultMap中获取）
            int total = (Integer) resultMap.get("all");

            // 创建分布规则集合（改为Map结构）
            Map<String, Integer> distributionRules = new LinkedHashMap<>();

            // 已分配的人数
            int allocatedCount = 0;

            for (int i = 0; i < defineCollection.size(); i++) {
                DistributionDefineInfo defineInfo = defineCollection.get(i);

                // 获取上下限并转换为整数百分比
                BigDecimal upLimit = defineInfo.getScaleUpLimit().setScale(0, RoundingMode.HALF_UP);
                BigDecimal downLimit = defineInfo.getScaleDownLimit().setScale(0, RoundingMode.HALF_UP);

                // 计算比例范围
                BigDecimal range = downLimit.subtract(upLimit);

                // 计算推荐人数
                int recommendCount = Math.round(total * range.divide(BigDecimal.valueOf(100)).floatValue());

                // 防止推荐人数超过剩余人数
                int remaining = total - allocatedCount;
                recommendCount = Math.min(recommendCount, remaining);

                // 确保推荐人数非负
                recommendCount = Math.max(0, recommendCount);

                // 更新已分配人数
                allocatedCount += recommendCount;

                // 构建规则数据
                String levelName = defineInfo.getPerfLevel();
                distributionRules.put(levelName, recommendCount); // 使用绩效等级作为键，推荐人数作为值
            }

            // 处理最后一个等级的剩余人数
            if (allocatedCount < total) {
                String lastLevel = distributionRules.keySet().iterator().next(); // 获取最后一个等级
                int lastRecommendCount = distributionRules.get(lastLevel);
                distributionRules.put(lastLevel, lastRecommendCount + (total - allocatedCount)); // 补足剩余人数
            }

            // 按照leveStrMap的顺序重新排序distributionRules
            Map<String, Integer> sortedDistributionRules = new LinkedHashMap<>();
            // 遍历leveStrMap的键，按照顺序构建新的Map
            for (String level : leveStrMap.keySet()) {
                if (distributionRules.containsKey(level)) {
                    sortedDistributionRules.put(level, distributionRules.get(level));
                }
            }

            // 将结果放入响应
            resultMap.put("distributionRules", sortedDistributionRules);

            resultMap.put("scored", scoredSet.size());
            resultMap.put("unScored", rowSet.size() - scoredSet.size());
            resultMap.put("leveStrMap", leveStrMap);
            JSONUtils.writeJson(response, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SHRWebException(new SHRPerfWebBizException(SHRPerfWebBizException.LOADNORMALDISTRIBUTIONINFOERR));
        }
    }

    public void getTeamTargetCommentListByPeriodAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        String json = getTeamTargetCommentList(request, response, ctx);
        JSONUtils.writeJson(response, json);
    }

    public void getTeamTargetCommentListByPeriod2Action(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        String json = getTeamTargetCommentListScore(request, response, ctx);
        JSONUtils.writeJson(response, json);
    }

    public static String getTeamTargetCommentList(HttpServletRequest request, HttpServletResponse response, Context ctx) {
        try {
            String personId = HRFilterUtils.getCurrentPersonId(ctx);
            String personalScoreSearchIdList = request.getParameter("personalScoreSearchIdList");
            String isOrg = request.getParameter("isOrg");
            String orgVal = "0";
            if (StringUtils.isNotEmpty(isOrg)) {
                orgVal = isOrg;
            }

            Set<String> periodSet = new HashSet();
            String periodId = request.getParameter("period");
            String isTeamEvalu = request.getParameter("isTeamEvalu");
            String isBatchView = request.getParameter("isBatchView");
            if (StringUtils.isEmpty(isBatchView) && !StringUtils.isEmpty(periodId)) {
                String[] periodArr = periodId.split(",");
                periodSet = new HashSet(Arrays.asList(periodArr));
            } else if (StringUtils.isEmpty(isTeamEvalu) || !isTeamEvalu.equals("1") || !StringUtils.isEmpty(periodId)) {
                periodSet = getTeamEvaPeriodSet(ctx, personId, orgVal, (String)null);
            }

            if (((Set)periodSet).size() < 1) {
                return "";
            } else {
                String evaObjName = request.getParameter("evaObjName");
                String periodSb = "(" + PerfwebStrUtils.convertListToString(((Set)periodSet).toArray()) + ")";
                StringBuilder gradeTaskNodeConditionSb = (new StringBuilder(" WHERE FNodeHandlerID='")).append(personId).append("' AND FIsEffective='").append("1")
                        .append("' AND FScoreStatus in ('").append("1").append("')").append(" AND t.FIsSelf=").append(0).append(" and t.FPeriodID in")
                        .append(periodSb).append(" and o.FIsOrg=").append(orgVal);
                int i;
                if (!StringUtils.isEmpty(evaObjName)) {
                    StringBuilder evaObjBuilder = new StringBuilder("(''");
                    IPerfEvaObject iPerfEvaObject = PerfEvaObjectFactory.getLocalInstance(ctx);
                    PerfEvaObjectCollection evaObjColl = iPerfEvaObject.getPerfEvaObjectCollection(" where name like '%" + evaObjName + "%'");
                    if (evaObjColl != null && evaObjColl.size() > 0) {
                        for(i = 0; i < evaObjColl.size(); ++i) {
                            evaObjBuilder.append(",'").append(evaObjColl.get(i).getId().toString()).append("'");
                        }
                    }

                    evaObjBuilder.append(")");
                    gradeTaskNodeConditionSb.append(" and t.FEvaObjID in ").append(evaObjBuilder);
                }

                if (!StringUtils.isEmpty(personalScoreSearchIdList)) {
                    String decode = URLDecoder.decode(personalScoreSearchIdList);
                    String[] split = decode.split(",");
                    StringBuilder sb = new StringBuilder(" ");
                    sb.append(" (");

                    for(i = 0; i < split.length; ++i) {
                        sb.append("'").append(split[i]).append("'").append(",");
                    }

                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(") ");
                    gradeTaskNodeConditionSb.append(" and t.FID in ").append(sb);
                }

                int rows = 8;
                String reqRows = request.getParameter("rows");
                if (!StringUtils.isEmpty(reqRows) && !reqRows.equals("null")) {
                    rows = Integer.parseInt(request.getParameter("rows"));
                }

                return assembleTeamTargetCommentData(ctx, (Set)periodSet, rows, gradeTaskNodeConditionSb.toString(), request, response);
            }
        } catch (Exception var18) {
            logger.error("Exception: ", var18);
            return null;
        }
    }

    public static String getTeamTargetCommentListScore(HttpServletRequest request, HttpServletResponse response, Context ctx) {
        try {
            String personId = HRFilterUtils.getCurrentPersonId(ctx);
            String personalScoreSearchIdList = request.getParameter("personalScoreSearchIdList");
            String isOrg = request.getParameter("isOrg");
            String orgVal = "0";
            if (StringUtils.isNotEmpty(isOrg)) {
                orgVal = isOrg;
            }

            Set<String> periodSet = new HashSet();
            String periodId = request.getParameter("period");
            String isTeamEvalu = request.getParameter("isTeamEvalu");
            String isBatchView = request.getParameter("isBatchView");
            if (StringUtils.isEmpty(isBatchView) && !StringUtils.isEmpty(periodId)) {
                String[] periodArr = periodId.split(",");
                periodSet = new HashSet(Arrays.asList(periodArr));
            } else if (StringUtils.isEmpty(isTeamEvalu) || !isTeamEvalu.equals("1") || !StringUtils.isEmpty(periodId)) {
                periodSet = getTeamEvaPeriodSet(ctx, personId, orgVal, (String)null);
            }

            if (((Set)periodSet).size() < 1) {
                return "";
            } else {
                String evaObjName = request.getParameter("evaObjName");
                String periodSb = "(" + PerfwebStrUtils.convertListToString(((Set)periodSet).toArray()) + ")";
                StringBuilder gradeTaskNodeConditionSb = (new StringBuilder(" WHERE FNodeHandlerID='")).append(personId).append("' AND FIsEffective='").append("1")
                        .append("' AND FScoreStatus in ('").append("2").append("','").append("5").append("')").append(" AND t.FIsSelf=")
                        .append(0).append(" and t.FPeriodID in").append(periodSb).append(" and o.FIsOrg=").append(orgVal);
                int i;
                if (!StringUtils.isEmpty(evaObjName)) {
                    StringBuilder evaObjBuilder = new StringBuilder("(''");
                    IPerfEvaObject iPerfEvaObject = PerfEvaObjectFactory.getLocalInstance(ctx);
                    PerfEvaObjectCollection evaObjColl = iPerfEvaObject.getPerfEvaObjectCollection(" where name like '%" + evaObjName + "%'");
                    if (evaObjColl != null && evaObjColl.size() > 0) {
                        for(i = 0; i < evaObjColl.size(); ++i) {
                            evaObjBuilder.append(",'").append(evaObjColl.get(i).getId().toString()).append("'");
                        }
                    }

                    evaObjBuilder.append(")");
                    gradeTaskNodeConditionSb.append(" and t.FEvaObjID in ").append(evaObjBuilder);
                }

                if (!StringUtils.isEmpty(personalScoreSearchIdList)) {
                    String decode = URLDecoder.decode(personalScoreSearchIdList);
                    String[] split = decode.split(",");
                    StringBuilder sb = new StringBuilder(" ");
                    sb.append(" (");

                    for(i = 0; i < split.length; ++i) {
                        sb.append("'").append(split[i]).append("'").append(",");
                    }

                    sb.deleteCharAt(sb.length() - 1);
                    sb.append(") ");
                    //gradeTaskNodeConditionSb.append(" and t.FID in ").append(sb);
                }

                int rows = 8;
                String reqRows = request.getParameter("rows");
                if (!StringUtils.isEmpty(reqRows) && !reqRows.equals("null")) {
                    rows = Integer.parseInt(request.getParameter("rows"));
                }

                return assembleTeamTargetCommentData(ctx, (Set)periodSet, rows, gradeTaskNodeConditionSb.toString(), request, response);
            }
        } catch (Exception var18) {
            logger.error("Exception: ", var18);
            return null;
        }
    }

    public static Set<String> getTeamEvaPeriodSet(Context ctx, String personId, String isOrg, String pageType) {
        Set<String> periodSet = new HashSet();
        StringBuilder periodSQLBuilder = (new StringBuilder("select gtni.FPeriodID from  T_EVA_GradeTaskNodeInst gtni ")).append(" LEFT JOIN T_EVA_PerfEvaObject peo ON gtni.FEVAOBJID= peo.FID  where gtni.FNodeHandlerID='").append(personId).append("' and gtni.FIsEffective='").append("1").append("' and gtni.FScoreStatus<>'").append("2").append("' ");
        if (pageType == null) {
            pageType = "1";
        }

        if (!pageType.equals("1") && !pageType.equals("3")) {
            if (pageType.equals("5")) {
                periodSQLBuilder.append(" and gtni.FIsSelf=").append(1);
            }
        } else {
            periodSQLBuilder.append(" and gtni.FIsSelf=").append(0);
        }

        periodSQLBuilder.append("  and peo.FIsOrg= ?");

        try {
            IRowSet rs = DbUtil.executeQuery(ctx, periodSQLBuilder.toString(), new Object[]{isOrg});
            if (rs != null) {
                while(rs.next()) {
                    String period = rs.getString("FPeriodID");
                    if (!StringUtils.isEmpty(period)) {
                        periodSet.add(period);
                    }
                }
            }
        } catch (BOSException var8) {
            logger.error("BOSException: ", var8);
        } catch (SQLException var9) {
            logger.error("SQLException: ", var9);
        }

        return periodSet;
    }

    public static String assembleTeamTargetCommentData(Context ctx, Set<String> periodSet, int rows, String gradeTaskNodeCondition, HttpServletRequest request, HttpServletResponse response) throws BOSException, IOException {
        TeamTargetCommentBean teamBean = new TeamTargetCommentBean();
        int totalCount = 0;
        int totalPage;
        String evaObjId = request.getParameter("evaObj");
        PerfEvaObjectInfo evaObjInfo = null;
        if (!StringUtils.isEmpty(evaObjId)) {
            evaObjInfo = GetEntityInfoUtils.getPerfEvaObjectInfo(ctx, evaObjId);
        }

        LinkedList<EvaPerfPeriodBean> evaPerfPeriodBeanList = new LinkedList();
        LinkedList<Map<String, String>> periodList = new LinkedList();
        Iterator<String> iterator = periodSet.iterator();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        FilterInfo filter = new FilterInfo();
        filter.getFilterItems().add(new FilterItemInfo("id", periodSet, CompareType.INCLUDE));
        EntityViewInfo viewInfo = new EntityViewInfo();
        SelectorItemCollection selector = viewInfo.getSelector();
        selector.add("id");
        selector.add("perfPlan.id");
        selector.add("perfPlan.name");
        selector.add("pStartDate");
        selector.add("pEndDate");
        viewInfo.setFilter(filter);
        SorterItemCollection sorterItemCollection = new SorterItemCollection();
        sorterItemCollection.add(new SorterItemInfo("id"));
        viewInfo.setSorter(sorterItemCollection);
        PerfPeriodCollection periodColl = PerfPeriodFactory.getLocalInstance(ctx).getPerfPeriodCollection(viewInfo);
        int periodSize = periodColl.size();
        Map<String, PerfPlanInfo> periodPlanMap = new HashMap(16);

        int k;
        for(k = 0; k < periodSize; ++k) {
            periodPlanMap.put(periodColl.get(k).getId().toString(), periodColl.get(k).getPerfPlan());
        }

        for(k = 0; k < periodSize; ++k) {
            PerfPeriodInfo periodInfo = periodColl.get(k);
            Map<String, String> periodMap = new HashMap();
            if (periodInfo.getId() != null) {
                periodMap.put("periodId", periodInfo.getId().toString());
                if (null != periodInfo.getPStartDate()) {
                    periodMap.put("startDate", sdf.format(periodInfo.getPStartDate()));
                }

                if (null != periodInfo.getPEndDate()) {
                    periodMap.put("endDate", sdf.format(periodInfo.getPEndDate()));
                }

                if (null != periodInfo.getPerfPlan().getId()) {
                    PerfPlanInfo perfPlanInfo = (PerfPlanInfo)periodPlanMap.get(periodInfo.getId().toString());
                    if (null != perfPlanInfo.getId()) {
                        periodMap.put("planName", perfPlanInfo.getName());
                        periodMap.put("planId", perfPlanInfo.getId().toString());
                    }
                }

                if (null != evaObjInfo && evaObjInfo.getPeriod().getId().toString().equals(periodInfo.getId().toString())) {
                    periodList.addFirst(periodMap);
                } else {
                    periodList.add(periodMap);
                }
            }
        }

        Map<String, String> firstPeriodMap = (Map)periodList.get(0);
        periodList.remove(0);
        periodList.addFirst(firstPeriodMap);
        totalCount = totalCount + assembleEvaPerfPeriodBeanListData(ctx, rows, gradeTaskNodeCondition, periodList, evaPerfPeriodBeanList, request, response);
        totalPage = calcPageCount(totalCount, rows);
        teamBean.setTotalCount(totalCount);
        teamBean.setTotalPage(totalPage);
        teamBean.setEvaPerfPeriodBeanList(evaPerfPeriodBeanList);
        Gson gson = new Gson();
        String json = gson.toJson(teamBean);
        return json;
    }

    protected static int assembleEvaPerfPeriodBeanListData(Context ctx, Set<String> periodSet, int rows, String gradeTaskNodeCondition, Map<String, String> periodMap, LinkedList<EvaPerfPeriodBean> evaPerfPeriodBeanList, HttpServletRequest request, HttpServletResponse response) throws BOSException {
        int evaCountPerPeriod = 0;
        EvaPerfPeriodBean evaPerfPeriodBean = new EvaPerfPeriodBean();
        LinkedList<EvaObjBean> evaObjBeanList = new LinkedList();
        StringBuffer evaCountPerPeriodSQL = (new StringBuffer("SELECT COUNT(1) FROM T_EVA_GradeTaskNodeInst t INNER JOIN T_EVA_PerfevaObject o ON t.FEvaobjId=o.FID ")).append(gradeTaskNodeCondition);
        if (!CollectionUtils.isEmpty(periodMap)) {
            evaCountPerPeriodSQL.append(" and t.FPeriodID='").append((String)periodMap.get("periodId")).append("'");
        }

        IRowSet evaCountPerPeriodSet = DbUtil.executeQuery(ctx, evaCountPerPeriodSQL.toString());

        try {
            if (evaCountPerPeriodSet != null && evaCountPerPeriodSet.next()) {
                evaCountPerPeriod = evaCountPerPeriodSet.getInt(1);
                if (evaCountPerPeriod == 0) {
                    return 0;
                }
            }
        } catch (SQLException var27) {
            logger.error("SQLException: ", var27);
        }

        int page = 1;
        String reqPage = request.getParameter("page");
        if (!StringUtils.isEmpty(reqPage) && !reqPage.equals("null")) {
            page = Integer.valueOf(request.getParameter("page"));
        }

        int start = (page - 1) * rows;
        String evaObjId = request.getParameter("evaObj");
        String nodeHandlerId = HRFilterUtils.getCurrentPersonId(ctx);
        Connection conn = null;
        IRowSet taskNodeSet = null;

        String sql;
        try {
            sql = null;
            StringBuffer selectSQL;
            if (!StringUtils.isEmpty(evaObjId) && page == 1) {
                int replaceRows = rows - 1;
                selectSQL = new StringBuffer();
                selectSQL.append(" SELECT FID,FWfLevel,FEvaObjID,FNodeSumScore,FNodeGrade,FCreateTime,FWfNodeID from T_EVA_GradeTaskNodeInst g ").append(" WHERE FEvaObjID='").append(evaObjId).append("' AND FNodeHandlerID='").append(nodeHandlerId).append("' and FIsEffective='1' and FScoreStatus in ('1','5') and g.FIsSelf=0");
                if (!CollectionUtils.isEmpty(periodMap)) {
                    selectSQL.append(" and g.FPeriodID='").append((String)periodMap.get("periodId")).append("'");
                }

                selectSQL.append("order by FWfLevel desc");
                taskNodeSet = DbUtil.executeQuery(ctx, selectSQL.toString());
                assembleEvaObjBean(ctx, taskNodeSet, evaObjBeanList, request, response);
                selectSQL = (new StringBuffer("SELECT FID,FWfLevel,FEvaObjID,FNodeSumScore,FNodeGrade,FCreateTime,FWfNodeID from T_EVA_GradeTaskNodeInst t")).append(gradeTaskNodeCondition);
                if (!CollectionUtils.isEmpty(periodMap)) {
                    selectSQL.append(" and t.FPeriodID='").append((String)periodMap.get("periodId")).append("'");
                }

                selectSQL.append(" and FEvaObjID not in ('").append(evaObjId).append("') order by FCreateTime desc,FWfLevel desc");
                selectSQL = new StringBuffer(selectSQL.toString().replaceFirst("SELECT", "SELECT TOP " + replaceRows));
                taskNodeSet = DbUtil.executeQuery(ctx, selectSQL.toString());
                assembleEvaObjBean(ctx, taskNodeSet, evaObjBeanList, request, response);
            } else {
                selectSQL = (new StringBuffer("SELECT FID,FWfLevel,FEvaObjID,FNodeSumScore,FNodeGrade,FCreateTime,FWfNodeID from T_EVA_GradeTaskNodeInst t")).append(gradeTaskNodeCondition);
                if (!CollectionUtils.isEmpty(periodMap)) {
                    selectSQL.append(" and FPeriodID='").append((String)periodMap.get("periodId")).append("'");
                }

                selectSQL.append(" order by FCreateTime desc,FWfLevel desc");
                conn = EJBFactory.getConnection(ctx);
                sql = (new PagingHelper()).getPagingSqlNoOptmize(KSqlUtil.getDbType(conn), selectSQL.toString().trim(), start, rows);
                taskNodeSet = DbUtil.executeQuery(ctx, sql);
                assembleEvaObjBean(ctx, taskNodeSet, evaObjBeanList, request, response);
            }
        } catch (Exception var28) {
            logger.error("Exception: ", var28);
        } finally {
            SQLUtils.cleanup(taskNodeSet, (Statement)null, conn);
        }

        if (!CollectionUtils.isEmpty(periodMap)) {
            evaPerfPeriodBean.setPlanId((String)periodMap.get("planId"));
            evaPerfPeriodBean.setPlanName((String)periodMap.get("planName"));
            evaPerfPeriodBean.setPeriodId((String)periodMap.get("periodId"));
            evaPerfPeriodBean.setStartDate((String)periodMap.get("startDate"));
            evaPerfPeriodBean.setEndDate((String)periodMap.get("endDate"));
            sql = (String)periodMap.get("planId");
            PerformanceRuleInfo ruleInfo = GetEntityInfoUtils.getPerformanceRuleInfoByPeriodId(ctx, (String)periodMap.get("periodId"));
            evaPerfPeriodBean.setScoreWay(ruleInfo.getScoringWay().getValue());
        }

        evaPerfPeriodBean.setEvaCountPerPeriod(evaCountPerPeriod);
        evaPerfPeriodBean.setEvaObjBeanList(evaObjBeanList);
        evaPerfPeriodBeanList.add(evaPerfPeriodBean);
        return evaCountPerPeriod;
    }

    protected static int assembleEvaPerfPeriodBeanListData(Context ctx, int rows, String gradeTaskNodeCondition, LinkedList<Map<String, String>> periodList, LinkedList<EvaPerfPeriodBean> evaPerfPeriodBeanList, HttpServletRequest request, HttpServletResponse response) throws BOSException {
        int evaCountPerPeriod = 0;
        LinkedList<EvaObjBean> evaObjBeanList = new LinkedList();
        int page = 1;
        String reqPage = request.getParameter("page");
        if (!StringUtils.isEmpty(reqPage) && !reqPage.equals("null")) {
            page = Integer.parseInt(reqPage);
        }

        int start = (page - 1) * rows;
        String evaObjId = request.getParameter("evaObj");
        Connection conn = null;
        IRowSet taskNodeSet = null;
        String periodFilterSql = "";
        Map<String, PerformanceRuleInfo> performanceMap = null;
        String periodId;
        if (!CollectionUtils.isEmpty(periodList)) {
            Set<String> periodIds = new HashSet();
            Iterator iterator = periodList.iterator();

            while(iterator.hasNext()) {
                Map<String, String> next = (Map)iterator.next();
                periodId = (String)next.get("periodId");
                periodIds.add(periodId);
            }

            String join = Strings.join((String[])periodIds.toArray(new String[0]), "','");
            periodFilterSql = " ('" + join + "') ";
            performanceMap = GetEntityInfoUtils.getPerformanceRuleInfoByPeriodIdS(ctx, periodIds);
        }

        try {
            StringBuilder evaCountPerPeriodSQL = (new StringBuilder("SELECT COUNT(1) FROM T_EVA_GradeTaskNodeInst t left JOIN T_EVA_PerfevaObject o ON t.FEvaobjId=o.FID ")).append(" left join T_EVA_WFNodeDef d on t.FWfNodeID = d.FID").append(" left join T_EVA_PWorkFlowDef f on d.fworkflow = f.FID").append(gradeTaskNodeCondition);
            if (StringUtils.isNotBlank(periodFilterSql)) {
                evaCountPerPeriodSQL.append(" and t.FPeriodID in ").append(periodFilterSql);
            }

            IRowSet evaCountPerPeriodSet = DbUtil.executeQuery(ctx, evaCountPerPeriodSQL.toString());
            if (evaCountPerPeriodSet.next()) {
                evaCountPerPeriod = evaCountPerPeriodSet.getInt(1);
                if (evaCountPerPeriod == 0) {
                    byte var34 = 0;
                    return var34;
                }
            }

            StringBuilder selectSql = (new StringBuilder("SELECT t.FID,t.FWfLevel,t.FEvaObjID,t.FNodeSumScore,t.FNodeGrade,t.FCreateTime,t.FWfNodeID,")).append("d.FPerfGradeEvaluate, d.FNeedScore, f.fconcurrent ").append(" from T_EVA_GradeTaskNodeInst t").append(" left join T_EVA_PerfEvaObject o on t.FEvaObjID = o.FID").append(" left join T_EVA_WFNodeDef d on t.FWfNodeID = d.FID").append(" left join T_EVA_PWorkFlowDef f on d.fworkflow = f.FID").append(gradeTaskNodeCondition);
//            if (StringUtils.isNotBlank(periodFilterSql)) {
//                selectSql.append(" and t.FPeriodID in ").append(periodFilterSql);
//            }

            if (!StringUtils.isEmpty(evaObjId) && page == 1) {
                periodId = selectSql.toString();
                selectSql.append(" and t.FEvaObjID = '").append(evaObjId).append("'");
                taskNodeSet = DbUtil.executeQuery(ctx, selectSql.toString());
                assembleEvaObjBean(ctx, taskNodeSet, evaObjBeanList, request, response);
                selectSql = new StringBuilder(periodId);
                selectSql.append(" and t.FEvaObjID <> '").append(evaObjId).append("'");
                selectSql.append(" order by t.FPeriodID asc,o.FNumber asc");
                selectSql = new StringBuilder(selectSql.toString().replaceFirst("SELECT", "SELECT TOP " + (rows - 1)));
                taskNodeSet = DbUtil.executeQuery(ctx, selectSql.toString());
            } else {
                selectSql.append(" and t.FEvaObjID <> '").append(evaObjId).append("'");
                selectSql.append(" order by t.FPeriodID asc,o.FNumber asc");
                conn = EJBFactory.getConnection(ctx);
                periodId = (new PagingHelper()).getPagingSqlNoOptmize(KSqlUtil.getDbType(conn), selectSql.toString().trim(), start - 1, rows);
                taskNodeSet = DbUtil.executeQuery(ctx, periodId);
            }

            assembleEvaObjBean(ctx, taskNodeSet, evaObjBeanList, request, response);
        } catch (Exception var26) {
            logger.error("Exception: ", var26);
        } finally {
            SQLUtils.cleanup(taskNodeSet, (Statement)null, conn);
        }

        EvaPerfPeriodBean evaPerfPeriodBean;
        if (!CollectionUtils.isEmpty(periodList)) {
            for(Iterator var29 = periodList.iterator(); var29.hasNext(); evaPerfPeriodBeanList.add(evaPerfPeriodBean)) {
                Map<String, String> periodInfo = (Map)var29.next();
                evaPerfPeriodBean = new EvaPerfPeriodBean();
                periodId = (String)periodInfo.get("periodId");
                evaPerfPeriodBean.setPlanId((String)periodInfo.get("planId"));
                evaPerfPeriodBean.setPlanName((String)periodInfo.get("planName"));
                evaPerfPeriodBean.setPeriodId(periodId);
                evaPerfPeriodBean.setStartDate((String)periodInfo.get("startDate"));
                evaPerfPeriodBean.setEndDate((String)periodInfo.get("endDate"));
                evaPerfPeriodBean.setEvaCountPerPeriod(evaCountPerPeriod);
                LinkedList<EvaObjBean> evaObjBeanListTmp = new LinkedList();
                if (!CollectionUtils.isEmpty(evaObjBeanList)) {
                    Iterator var22 = evaObjBeanList.iterator();

                    while(var22.hasNext()) {
                        EvaObjBean evaObjBean = (EvaObjBean)var22.next();
                        if (evaObjBean.getPeriod().equals(periodId)) {
                            evaObjBeanListTmp.add(evaObjBean);
                        }
                    }
                }

                evaPerfPeriodBean.setEvaObjBeanList(evaObjBeanListTmp);
                if (performanceMap != null && performanceMap.size() > 0) {
                    PerformanceRuleInfo ruleInfo = (PerformanceRuleInfo)performanceMap.get(periodId);
                    if (ruleInfo != null) {
                        evaPerfPeriodBean.setScoreWay(ruleInfo.getScoringWay().getValue());
                    }
                }
            }
        }

        return evaCountPerPeriod;
    }

    public static int calcPageCount(int total, int pageRows) {
        int totalPage = 0;
        if (total > 0) {
            if (total % pageRows == 0) {
                totalPage = total / pageRows;
            } else {
                totalPage = total / pageRows + 1;
            }
        }

        return totalPage;
    }
}
