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

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.eas.custom.perfweb.portal.handler.PerfPersonalScoreHandlerEx;
import com.kingdee.eas.custom.perfweb.utils.FeishuMessageUtil;
import com.kingdee.eas.custom.perfweb.utils.PerfEvaObjectUtil;
import com.kingdee.eas.custom.perfweb.utils.UrlParamUtil;
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.PerfPeriodInfo;
import com.kingdee.shr.perfweb.app.resource.SHRPerfWebResource;
import com.kingdee.shr.perfweb.app.workflow.*;
import com.kingdee.shr.perfweb.bean.PerfScoreList;
import com.kingdee.shr.perfweb.util.SHRPerfWebResourceUtil;
import com.kingdee.shr.perfweb.util.ServerResponseConst;
import com.kingdee.shr.perfweb.utils.RequestUtils;
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.*;

/**
 * 类名称: PerfPersonalScoreHandlerEx
 * 功能描述: 单人评分列表提交后发送飞书消息
 * 创建日期: 2026-06-15 11:15
 * 作    者: 青梧
 * 版    本: 1.0
 */
public class PerfPersonalScoreHandlerNewEx extends PerfPersonalScoreHandlerEx {
    private Logger logger = LoggerFactory.getLogger(PerfPersonalScoreHandlerNewEx.class);

    public void submitScoreAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        Map<String, Object> res = new HashMap();
        String scoreObj = RequestUtils.getParameter(request, "scoreObj");
        Gson gson = new Gson();
        List<PerfScoreList> perfScoreList = (List) gson.fromJson(scoreObj, (new TypeToken<List<PerfScoreList>>() {
        }).getType());
        String result = "200";
        if (CollectionUtils.isEmpty(perfScoreList)) {
            result = "500";
            res.put("msg", "data is null");
        } else {
            for (int i = 0; i < perfScoreList.size(); ++i) {
                PerfScoreList scoreList = (PerfScoreList) perfScoreList.get(i);
                String gradeTaskNodeId = scoreList.getGradeTaskNode();
                GradeTaskNodeInstInfo gradeTaskNodeInstInfo = getGradeTaskNodeInstInfoById(ctx, gradeTaskNodeId);
                String scoreStatus = "1";
                if (gradeTaskNodeInstInfo != null) {
                    if (gradeTaskNodeInstInfo.getScoreStatus() != null) {
                        scoreStatus = gradeTaskNodeInstInfo.getScoreStatus().getValue();
                    }

                    if (!scoreStatus.equals("2") && gradeTaskNodeInstInfo.getTaskStatus() == TaskStatusEnum.DEALING) {
                        result = PerfWorkFlowFacadeControllerBean.getInstance().submitScore(ctx, scoreList);
                        if (result.equals("200")) {
                            res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.NODEEVALUATESUBMITSUCCESS, ctx));
                            // ===== 提交成功后发送飞书消息 =====
                            // currentHandlerMap : key=evaObjId$workFlowId, value=处理人姓名（逗号分隔）
                            Map<String, String> currentHandlerMap = new HashMap<>();
                            // evaObjHandlerMap  : key=evaObjId$workFlowId, value=处理人PersonId集合
                            Map<String, Set<String>> evaObjHandlerMap = new HashMap<>();
                            // workNodeNameMap   : key=evaObjId$workFlowId, value=节点名称集合
                            Map<String, Set<String>> workNodeNameMap = new HashMap<>();
                            // workFlowNameMap   : key=workFlowId, value=流程名称
                            Map<String, String> workFlowNameMap = new HashMap<>();
                            //考核对象
                            Set<String> evaObjSet = new LinkedHashSet<>();
                            evaObjSet.add(gradeTaskNodeInstInfo.getEvaObj().getId().toString());
                            PerfPeriodInfo period = gradeTaskNodeInstInfo.getPeriod();
                            int wfLevel = gradeTaskNodeInstInfo.getWfLevel();
                            if (!evaObjSet.isEmpty()) {
                                PerfEvaObjectUtil.getBatchCurrentNodeHandersForEvaObj(ctx, evaObjSet, currentHandlerMap, evaObjHandlerMap, workNodeNameMap, workFlowNameMap, String.valueOf(wfLevel + 1));
                            }
                            String messageUrl = UrlParamUtil.buildPerfPortalFeishuMessageUrl();
                            String workFlowName = workFlowNameMap.isEmpty() ? "" : workFlowNameMap.values().iterator().next();
                            Map<String, Integer> submitWfLevelMap = new HashMap<>();
                            submitWfLevelMap.put(gradeTaskNodeInstInfo.getEvaObj().getId().toString(), wfLevel);
                            FeishuMessageUtil.sendAfterScoreSubmit(ctx, submitWfLevelMap, evaObjHandlerMap, evaObjSet, period, messageUrl, workFlowName, messageUrl);
                        } else if (result.equals(ServerResponseConst.INVALID)) {
                            res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.SUBMITERRASNODEHANDLERREASSINED, ctx));
                        } else {
                            res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.NODEEVALUATESUBMITFAILED, ctx));
                        }
                    } else {
                        result = "500";
                        res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.CURRENTWORKFLOWENDED, ctx));
                    }
                } else {
                    result = "500";
                    res.put("msg", SHRPerfWebResourceUtil.getRes(SHRPerfWebResource.CURRENTWORKFLOWRESETED, ctx));
                }
            }
        }

        res.put("result", result);
        JSONUtils.writeJson(response, res);
    }

    public GradeTaskNodeInstInfo getGradeTaskNodeInstInfoById(Context ctx, String id) {
        GradeTaskNodeInstInfo gradeTaskNodeInstInfo = null;

        try {
            IGradeTaskNodeInst igradeTaskNodeInst = GradeTaskNodeInstFactory.getLocalInstance(ctx);
            GradeTaskNodeInstCollection gradeTaskNodeInstColl = igradeTaskNodeInst.getGradeTaskNodeInstCollection("select *,period.*,nodeHandler.name, wfNode.workflow.*, wfNode.wfNodeAreaExtendConfig.* where id='" + id + "'");
            if (gradeTaskNodeInstColl != null && gradeTaskNodeInstColl.size() > 0) {
                gradeTaskNodeInstInfo = gradeTaskNodeInstColl.get(0);
            }
        } catch (BOSException e) {
            logger.error("【PERFWEB】-GETINDICATORTARGETINSTERR", e);
        }
        return gradeTaskNodeInstInfo;
    }
}
