package nckd.jxccl.opmc.pm.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.url.UrlService;
import kd.bos.workflow.engine.msg.info.MessageInfo;
import nckd.jxccl.opmc.pm.helper.KpiImportUtils;
import org.apache.commons.lang3.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: NoticeKpiUnqualifiedTask
 * @Description: 定时推送绩效导入结果不合格人员
 * @Author: PJJ
 * @Date: 2026/1/14 上午9:39
 * @Version: 1.0
 */
public class NoticeKpiUnqualifiedTask extends AbstractTask {
    private static final Log logger = LogFactory.getLog(NoticeKpiUnqualifiedTask.class);

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //去年年度绩效不合格用户
        List<DynamicObject> yearUnqualifiedUser = KpiImportUtils.yearUnqualifiedUser();
        //查询连续三个月绩效考核 不合格 人员
        List<DynamicObject> monthUnqualifiedUser = KpiImportUtils.monthUnqualifiedUser();
        //查询所有绩效辅导组织负责人
        DynamicObject[] tutor_head = BusinessDataServiceHelper.load("nckd_kpi_tutor_head", "nckd_entryentity.nckd_specialuser,nckd_entryentity.nckd_specialresponsible,nckd_responsibleuser,nckd_org", null);
        //特殊负责人管辖的员工
        Map<Long, DynamicObject> head_specialUsers = Arrays.stream(tutor_head).flatMap(i -> i.getDynamicObjectCollection("nckd_entryentity").stream()).
                collect(Collectors.toMap(i -> i.getLong("nckd_specialuser.id"), i -> i, (existing, replacement) -> existing));
        //特殊员工
        List<Long> specialUsers = Arrays.stream(tutor_head).flatMap(i -> i.getDynamicObjectCollection("nckd_entryentity").stream()).map(i -> i.getLong("nckd_specialuser.id")).collect(Collectors.toList());
        //根据部门汇总人员数据
        HashMap<Long, List<DynamicObject>> org_userMap = new HashMap<>();
        HashMap<Long, List<DynamicObject>> special_userMap = new HashMap<>();
        yearUnqualifiedUser.addAll(monthUnqualifiedUser);
        for (DynamicObject user : yearUnqualifiedUser) {
            //判断特殊员工
            long userId = user.getLong("id");
            if (specialUsers.contains(userId)) {
                //特殊负责人
                Long headId = head_specialUsers.get(userId).getLong("id");
                List<DynamicObject> specialUsersList = special_userMap.get(headId);
                if (ObjectUtils.isEmpty(specialUsersList)) {
                    ArrayList<DynamicObject> list = new ArrayList<>();
                    list.add(user);
                    special_userMap.put(headId, list);
                } else {
                    specialUsersList.add(user);
                }
            } else {
                //正常员工
                //过滤主任职
                DynamicObjectCollection entry = user.getDynamicObjectCollection("entryentity");
                List<DynamicObject> collect = entry.stream().filter(i -> !i.getBoolean("ispartjob")).collect(Collectors.toList());
                Long orgId = collect.get(0).getLong("dpt.id");

                List<DynamicObject> users = org_userMap.get(orgId);
                if (ObjectUtils.isEmpty(users)) {
                    ArrayList<DynamicObject> objects = new ArrayList<>();
                    objects.add(user);
                    org_userMap.put(orgId, objects);
                } else {
                    users.add(user);
                }
            }
        }

        Map<Long, DynamicObject> org_head = Arrays.stream(tutor_head).collect(Collectors.toMap(i -> i.getLong("nckd_org.id"), i -> i));
        //查询组织架构表
        DynamicObjectCollection structure = QueryServiceHelper.query("bos_org_structure", "parent.id,org.id",
                new QFilter[]{new QFilter("view.number", QCP.equals, "01").and("status", QCP.equals, "C").and("enable", QCP.equals, "1")});
        //组织和上级组织map
        Map<Long, Long> orgParent = structure.stream().collect(Collectors.toMap(i -> i.getLong("org.id"), i -> i.getLong("parent.id")));
        //发送消息
        List<MessageInfo> messageInfos = new ArrayList<>();
        //未找到对应负责人的组织
        List<Long> unFindOrg = new ArrayList<>();
        //正常员工
        for (Long curOrgId : org_userMap.keySet()) {
            DynamicObject user = findUser(org_head, orgParent, curOrgId, unFindOrg);
            if (ObjectUtils.isNotEmpty(user)) {
                buildMessage(messageInfos, user, org_userMap.get(curOrgId),tutor_head[0].getLong("id"));
            }
        }
        //特殊员工
        for (Long headId : special_userMap.keySet()) {
            buildMessage(messageInfos, headId, special_userMap.get(headId),tutor_head[0].getLong("id"));
        }

        Map<String, Object> stringObjectMap = MessageCenterServiceHelper.batchSendMessages(messageInfos);
        if( ObjectUtils.isNotEmpty(unFindOrg) ){
            sendSettingMsg(tutor_head[0].getLong("id"));
        }
        logger.info("员工绩效不合格消息提醒发送结果" + stringObjectMap.get("success") + "返回结果" + stringObjectMap.get("description"));

    }

    private void sendSettingMsg(Long id) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setMessageTitle(new LocaleString("未配置消息"));
        messageInfo.setMessageContent(new LocaleString("未配置消息"));
        messageInfo.setType(MessageInfo.TYPE_ALARM);
        messageInfo.setEntityNumber("nckd_kpi_tutor_head");
        messageInfo.setBizDataId(id);
        messageInfo.setTag("员工绩效");
        messageInfo.setUserIds(Collections.singletonList(UserServiceHelper.getCurrentUserId()));
        messageInfo.setSenderId(UserServiceHelper.getCurrentUserId());
        Map<String, Object> stringObjectMap = MessageCenterServiceHelper.batchSendMessages(Collections.singletonList(messageInfo));
        logger.info("未配置消息" + stringObjectMap.get("success") + "返回结果" + stringObjectMap.get("description"));
    }

    private DynamicObject findUser(Map<Long, DynamicObject> org_head, Map<Long, Long> orgParent, Long curOrgId, List<Long> unFindOrg) {
        //员工对应组织先找负责人
        DynamicObject userHead = org_head.get(curOrgId);
        if (ObjectUtils.isEmpty(userHead)) {
            Long org_parent = orgParent.get(curOrgId);
            if (org_parent == null) {
                unFindOrg.add(curOrgId);
                return null;
            } else {
                DynamicObject user = findUser(org_head, orgParent, org_parent, unFindOrg);
                return user;
            }
        } else {
            return userHead;
        }
    }

    private void buildMessage(List<MessageInfo> messageInfos, DynamicObject user, List<DynamicObject> dynamicObjects,Long id) {
        // 构建 消息
        MessageInfo messageInfo = new MessageInfo();
        // 设置 消息标题
        messageInfo.setMessageTitle(new LocaleString("员工绩效评估不合格提醒"));
        // 设置 文本消息内容
        Set<String> collect = dynamicObjects.stream().map(i -> i.getLocaleString("name").getLocaleValue_zh_CN() + ":" + i.getString("number")).collect(Collectors.toSet());
        // 设置 文本消息内容
        messageInfo.setMessageContent(new LocaleString(collect.toString()));
        // 设置 消息类型
        messageInfo.setType(MessageInfo.TYPE_TASK);
        // 设置 实体编码
        messageInfo.setEntityNumber("nckd_kpi_tutor_head");
        // 设置 业务单据ID
        messageInfo.setBizDataId(id);
        // 设置 标签
        messageInfo.setTag("员工绩效");
//        long managerBoId = entryDyo.getDynamicObject(SanDingConstant.NCKD_MANAGER_KEY).getLong(SanDingConstant.BOID_KEY);
        // 设置 消息接收人
        messageInfo.setUserIds(Collections.singletonList(user.getLong("id")));
        // 设置 消息Web端url
//        messageInfo.setContentUrl(UrlService.getDomainContextUrl() + "/index.html?formId=" + SanDingConstant.NCKD_SANDINGTASK_ENTITY + "&pkId=" + SANDING_TASK_MAP.get(entryDyo.getLong(SanDingConstant.ID_KEY)));
        // 设置发送人
        messageInfo.setSenderId(UserServiceHelper.getCurrentUserId());
        messageInfos.add(messageInfo);
    }

    private void buildMessage(List<MessageInfo> messageInfos, Long headId, List<DynamicObject> dynamicObjects,Long id) {
        // 构建 消息
        MessageInfo messageInfo = new MessageInfo();
        // 设置 消息标题
        messageInfo.setMessageTitle(new LocaleString("员工绩效评估不合格提醒"));
        // 设置 文本消息内容
        Set<String> collect = dynamicObjects.stream().map(i -> i.getLocaleString("name").getLocaleValue_zh_CN() + ":" + i.getString("number")).collect(Collectors.toSet());
//        String.format("",collect);
        messageInfo.setMessageContent(new LocaleString(collect.toString()));
        // 设置 消息类型
        messageInfo.setType(MessageInfo.TYPE_TASK);
        messageInfo.setEntityNumber("nckd_kpi_tutor_head");
        messageInfo.setBizDataId(id);

        // 设置 标签
        messageInfo.setTag("员工绩效");
        // 设置 消息接收人
        messageInfo.setUserIds(Collections.singletonList(headId));
        // 设置发送人
        messageInfo.setSenderId(UserServiceHelper.getCurrentUserId());
        messageInfos.add(messageInfo);
    }

}
