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

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.custom.perfweb.portal.handler.PerfBatchScoreHandlerEx;
import com.kingdee.eas.custom.perfweb.utils.FeishuPushHelper;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.util.app.DbUtil;
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.evalplan.*;
import com.kingdee.shr.perfweb.app.base.evalrule.*;
import com.kingdee.shr.perfweb.app.common.BusinessOpTypeEnum;
import com.kingdee.shr.perfweb.app.common.GeneralTaskPoolFactory;
import com.kingdee.shr.perfweb.app.common.GeneralTaskPoolInfo;
import com.kingdee.shr.perfweb.app.common.YesOrNotEnum;
import com.kingdee.shr.perfweb.app.resource.SHRPerfWebResource;
import com.kingdee.shr.perfweb.app.workflow.*;
import com.kingdee.shr.perfweb.app.workflow.TaskStatusEnum;
import com.kingdee.shr.perfweb.portal.handler.PerfBatchScoreHandler;
import com.kingdee.shr.perfweb.util.GetEntityInfoUtils;
import com.kingdee.shr.perfweb.util.PersonInchargeUtils;
import com.kingdee.shr.perfweb.util.SHRPerfWebResourceUtil;
import com.kingdee.shr.perfweb.utils.PerfwebThreadPoolUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

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

/**
 * 类名称: PerfBatchScoreHandlerEx
 * 功能描述: 个人目标评价提交后发起飞书待办
 * 创建日期: 2026-06-15 10:54
 * 作    者: 青梧
 * 版    本: 1.0
 */
public class PerfBatchScoreHandlerNewEx extends PerfBatchScoreHandlerEx {
    private Logger logger = LoggerFactory.getLogger(PerfBatchScoreHandlerNewEx.class);

    public void submitScoreAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException, BOSException {
        Context ctx = SHRContext.getInstance().getContext();
        Map<String, Object> res = new HashMap();
        String[] evaObjIds = request.getParameter("evaObjIds").split(",");
        String[] gradeTaskNodeIds = request.getParameter("gradeTaskNodeIds").split(",");
        int succCount = 0;
        int failedCount = 0;
        String result = null;
        IGradeTargetInst iGradeTargetInst = null;
        IRecordTarget iRecordTarget = null;
        IIndicatorTarget iIndicatorTarget = null;
        IGradeTaskNodeInst iGradeTaskNodeInst = null;

        try {
            iRecordTarget = RecordTargetFactory.getLocalInstance(ctx);
            iGradeTargetInst = GradeTargetInstFactory.getLocalInstance(ctx);
            iIndicatorTarget = IndicatorTargetFactory.getLocalInstance(ctx);
            iGradeTaskNodeInst = GradeTaskNodeInstFactory.getLocalInstance(ctx);
        } catch (BOSException e1) {
            this.logger.error("", e1);
        }

        FilterInfo filter = new FilterInfo();
        filter.getFilterItems().add(new FilterItemInfo("id", new HashSet(Arrays.asList(gradeTaskNodeIds)), CompareType.INCLUDE));
        EntityViewInfo viewInfo = new EntityViewInfo();
        SelectorItemCollection selector = viewInfo.getSelector();
        selector.add("wfNode.id");
        selector.add("evaObj.id");
        selector.add("id");
        selector.add("evaObjName");
        selector.add("*");
        selector.add("evaObj.*");
        selector.add("period.*");
        viewInfo.setFilter(filter);
        GradeTaskNodeInstCollection gtnInstColl = null;

        try {
            gtnInstColl = iGradeTaskNodeInst.getGradeTaskNodeInstCollection(viewInfo);
        } catch (BOSException e1) {
            this.logger.error("", e1);
        }

        Map<String, GradeTaskNodeInstInfo> gtnInstMap = new HashMap();
        if (!gtnInstColl.isEmpty()) {
            int gtnInstSize = gtnInstColl.size();

            for (int m = 0; m < gtnInstSize; ++m) {
                gtnInstMap.put(gtnInstColl.get(m).getId().toString(), gtnInstColl.get(m));
            }
        }

        FilterInfo wfNodeFilter = new FilterInfo();
        EntityViewInfo wfNodeViewInfo = new EntityViewInfo();
        SelectorItemCollection wfNodeSic = wfNodeViewInfo.getSelector();
        wfNodeSic.add("wholeComment");
        wfNodeSic.add("targetComment");
        wfNodeSic.add("indicatorComment");
        wfNodeSic.add("perfGradeEvaluate");
        wfNodeSic.add("needScore");
        wfNodeSic.add("id");
        wfNodeSic.add("workflow.id");
        wfNodeViewInfo.setFilter(wfNodeFilter);
        WFNodeDefCollection wfNodeColl = null;

        try {
            wfNodeColl = WFNodeDefFactory.getLocalInstance(ctx).getWFNodeDefCollection(wfNodeViewInfo);
        } catch (BOSException e1) {
            this.logger.error("", e1);
        }

        Map<String, WFNodeDefInfo> wfNodeMap = new HashMap();
        if (!wfNodeColl.isEmpty()) {
            int wfNodeSize = wfNodeColl.size();

            for (int m = 0; m < wfNodeSize; ++m) {
                wfNodeMap.put(wfNodeColl.get(m).getId().toString(), wfNodeColl.get(m));
            }
        }

        List<String[]> paramsList = new ArrayList();
        CoreBaseCollection gtaskColl = new CoreBaseCollection();
        // 按 wfLevel 收集提交成功的人员，批量提交后统一推送飞书待办
        Map<Integer, FeishuPushHelper.FeishuBatchContext> feishuBatchByWfLevel = new HashMap<>();

        for (int i = 0; i < evaObjIds.length; ++i) {
            GradeTaskNodeInstInfo gradeTaskNodeInstInfo = (GradeTaskNodeInstInfo) gtnInstMap.get(gradeTaskNodeIds[i]);
            WFNodeDefInfo nodeDefInfo = (WFNodeDefInfo) wfNodeMap.get(gradeTaskNodeInstInfo.getWfNode().getId().toString());
            String wholeComment = nodeDefInfo.getWholeComment() == null ? "2" : nodeDefInfo.getWholeComment().getValue();
            String indicatorComment = nodeDefInfo.getIndicatorComment() == null ? "2" : nodeDefInfo.getIndicatorComment().getValue();
            String perfGradeEvaluate = nodeDefInfo.getPerfGradeEvaluate() == null ? "0" : nodeDefInfo.getPerfGradeEvaluate().getValue();
            String targetComment = nodeDefInfo.getTargetComment() == null ? "2" : nodeDefInfo.getTargetComment().getValue();
            String isNeedScore = nodeDefInfo.getNeedScore() == null ? "2" : nodeDefInfo.getNeedScore().getValue();
            WholeCommentInfo wholeCommentInfo = GetEntityInfoUtils.getWholeCommentInfo(ctx, gradeTaskNodeIds[i]);
            String comment = wholeCommentInfo.getComment();
            String grade = wholeCommentInfo.getGrade();
            boolean targetcommentflag = true;
            Set<String> gradeTargetInstSet = new HashSet();
            PersonInchargeUtils.targetCommentVerify(ctx, gradeTaskNodeIds[i], gradeTargetInstSet, targetComment);
            if (!CollectionUtils.isEmpty(gradeTargetInstSet)) {
                targetcommentflag = false;
            }

            if ((!StringUtils.isEmpty(grade) || !indicatorComment.equals("1") || !perfGradeEvaluate.equals("1")) && (!wholeComment.equals("1") || !StringUtils.isEmpty(comment)) && targetcommentflag) {
                StringBuffer notNeedScoreAreaIdSb = new StringBuffer("(''");
                PerformanceRuleInfo ruleInfo = GetEntityInfoUtils.getPerformanceRuleInfoByEvaObj(ctx, gradeTaskNodeInstInfo.getEvaObj().getId().toString());
                EvaluFormAreaBaseCollection areaBaseColl = GetEntityInfoUtils.getEvaluFormAreaBaseCollection(ctx, ruleInfo.getId().toString());
                if (null != areaBaseColl && areaBaseColl.size() > 0) {
                    int areaSize = areaBaseColl.size();

                    for (int j = 0; j < areaSize; ++j) {
                        if (areaBaseColl.get(j).getCanRate().getValue() != 1) {
                            notNeedScoreAreaIdSb.append(",'").append(areaBaseColl.get(j).getId().toString()).append("'");
                        }
                    }
                }

                notNeedScoreAreaIdSb.append(")");
                if (isNeedScore.equals("2")) {
                    StringBuffer indicatorSb = new StringBuffer(" where evaObj='");
                    indicatorSb.append(gradeTaskNodeInstInfo.getEvaObj().getId().toString()).append("' and workFlow='").append(nodeDefInfo.getWorkflow().getId().toString()).append("' and (qualiOrRation=").append(0).append(" or (qualiOrRation=").append(1).append(" and scoringFormula is null))").append(" and rejection=0").append(" and areaBase not in ").append(notNeedScoreAreaIdSb.toString());
                    StringBuffer recordSb = new StringBuffer(" where evaObj='");
                    recordSb.append(gradeTaskNodeInstInfo.getEvaObj().getId().toString()).append("' and workFlow='").append(nodeDefInfo.getWorkflow().getId().toString()).append("'").append(" and areaBase not in ").append(notNeedScoreAreaIdSb.toString());
                    HashSet<String> needVerifyIdSet = new HashSet(16);
                    IndicatorTargetCollection indicatorColl = null;

                    try {
                        indicatorColl = iIndicatorTarget.getIndicatorTargetCollection(indicatorSb.toString());
                    } catch (BOSException e) {
                        this.logger.error("", e);
                    }

                    RecordTargetCollection recordColl = null;

                    try {
                        recordColl = iRecordTarget.getRecordTargetCollection(recordSb.toString());
                    } catch (BOSException e) {
                        this.logger.error("", e);
                    }

                    if (null != indicatorColl && indicatorColl.size() > 0) {
                        int indicatorSize = indicatorColl.size();

                        for (int j = 0; j < indicatorSize; ++j) {
                            needVerifyIdSet.add(indicatorColl.get(j).getId().toString());
                        }
                    }

                    if (null != recordColl && recordColl.size() > 0) {
                        int recordSize = recordColl.size();

                        for (int k = 0; k < recordSize; ++k) {
                            needVerifyIdSet.add(recordColl.get(k).getId().toString());
                        }
                    }

                    try {
                        HashSet<String> gtiSet = new HashSet(8);
                        GradeTargetInstCollection gtiColl = iGradeTargetInst.getGradeTargetInstCollection(" where gradeTaskNode='" + gradeTaskNodeInstInfo.getId().toString() + "'");
                        if (null != gtiColl && gtiColl.size() > 0) {
                            int gtiSize = gtiColl.size();

                            for (int n = 0; n < gtiSize; ++n) {
                                gtiSet.add(gtiColl.get(n).getTarget());
                            }
                        }

                        Iterator<String> needVerifyIt = needVerifyIdSet.iterator();

                        while (needVerifyIt.hasNext()) {
                            String targetId = (String) needVerifyIt.next();
                            if (!gtiSet.contains(targetId)) {
                                needVerifyIt.remove();
                            }
                        }
                    } catch (Exception e) {
                        this.logger.error("", e);
                    }

                    StringBuffer targetInstSb = new StringBuffer(" where gradeTaskNode='");
                    targetInstSb.append(gradeTaskNodeIds[i]).append("' and targetScore is not null");
                    HashSet<String> validTargetIdSet = new HashSet(16);
                    GradeTargetInstCollection targetInstColl = null;

                    try {
                        targetInstColl = iGradeTargetInst.getGradeTargetInstCollection(targetInstSb.toString());
                    } catch (BOSException e) {
                        this.logger.error("", e);
                    }

                    if (null != targetInstColl && targetInstColl.size() > 0) {
                        int targetSize = targetInstColl.size();

                        for (int m = 0; m < targetSize; ++m) {
                            validTargetIdSet.add(targetInstColl.get(m).getTarget());
                        }
                    }

                    needVerifyIdSet.removeAll(validTargetIdSet);
                    if (needVerifyIdSet.size() > 0) {
                        ++failedCount;
                        continue;
                    }
                }

                String[] submitIdParmas = new String[1];
                submitIdParmas[0] = gradeTaskNodeIds[i];
                paramsList.add(submitIdParmas);
                GeneralTaskPoolInfo generalTaskPoolInfo = new GeneralTaskPoolInfo();
                generalTaskPoolInfo.setBusinessId(evaObjIds[i]);
                generalTaskPoolInfo.setBusinessType(BusinessOpTypeEnum.BATCHSUBMITSCORE);
                generalTaskPoolInfo.setDealStatus(TaskStatusEnum.UNDEAL);
                generalTaskPoolInfo.setIsAlreadyDeal(YesOrNotEnum.NO);
                generalTaskPoolInfo.setLock(YesOrNotEnum.NO);
                generalTaskPoolInfo.setGradeTaskNodeInst(gradeTaskNodeIds[i]);
                gtaskColl.add(generalTaskPoolInfo);
                ++succCount;
                // 收集提交成功的人员，按 wfLevel 分组，待批量落库后统一推送飞书
                int wfLevel = gradeTaskNodeInstInfo.getWfLevel();
                FeishuPushHelper.FeishuBatchContext batchContext = feishuBatchByWfLevel.computeIfAbsent(wfLevel, k -> new FeishuPushHelper.FeishuBatchContext());
                batchContext.getEvaObjSet().add(evaObjIds[i]);
                if (batchContext.getPeriod() == null && gradeTaskNodeInstInfo.getPeriod() != null) {
                    batchContext.setPeriod(gradeTaskNodeInstInfo.getPeriod());
                }
            } else {
                ++failedCount;
            }
        }
        try {
            if (paramsList.size() > 0) {
                GeneralTaskPoolFactory.getLocalInstance(ctx).addnew(gtaskColl);
                DbUtil.executeBatch(ctx, "update T_EVA_GradeTaskNodeInst set FScoreStatus='2' where FID=?", paramsList);
                PerfwebThreadPoolUtils.submitScore(ctx);

            }
        } catch (Exception e) {
            this.logger.error("", e);
        }

        if (!feishuBatchByWfLevel.isEmpty()) {
            sendFeishuByWfLevel(ctx, feishuBatchByWfLevel);
        }
        if (succCount == evaObjIds.length) {
            res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.SUBMITSUCCESSNOTICE, ctx, new Object[]{succCount}));
        } else {
            res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.label890, ctx, new Object[]{succCount, failedCount}));
        }

        JSONUtils.writeJson(response, res);
    }

    private void sendFeishuByWfLevel(Context ctx, Map<Integer, FeishuPushHelper.FeishuBatchContext> feishuBatchByWfLevel) {
        try {
            FeishuPushHelper.sendOnceByWfLevel(ctx, feishuBatchByWfLevel);
        } catch (Exception e) {
            logger.error("飞书推送异常（不影响提交）", e);
        }
    }
}
