package zlkj.hr.opmc.pmd.business.ext.impl;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.api.JobInfo;
import kd.bos.schedule.api.JobType;
import kd.bos.schedule.form.JobFormInfo;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.opmc.epa.business.task.ActivityAddActObjTask;
import kd.opmc.pmd.business.application.service.PerffileChangeApplicationService;
import kd.opmc.pmd.business.domain.perffile.entity.ChgInfoBo;
import kd.opmc.pmd.business.domain.perffile.entityservice.PerffileChangeEntityService;
import kd.opmc.pmd.business.domain.perffile.entityservice.PerffileEntityService;
import kd.opmc.pmd.business.domain.perffile.enums.PersonnelChangeTypeEnum;
import kd.opmc.pmd.business.ext.IPerffileChangeService;
import kd.opmc.pmd.common.constants.PerffileChangeConstants;
import zlkj.hr.opmc.pmd.business.ext.constants.PerffileActivityConstants;

import java.util.*;
import java.util.stream.Collectors;

import static kd.hr.hbp.common.constants.HRBaseConstants.*;

/**
 * description: PerffileChangeServiceImplExt <br>
 * date: 2026/4/22 18:26 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class PerffileChangeServiceImplExt  implements IPerffileChangeService {
    //管理岗编码
    private static final String positiontype_number="1010_S";


    //@Override
    public List<Long> beforeConsumePersonnelChange(ChgInfoBo chgInfoBo) {
        //new ArrayList<>(HRBaseConstants.INITCAPACITY_ARRAYLIST);
        return Collections.emptyList();
    }

    @Override
    public void afterConsumePersonnelChange(ChgInfoBo chgInfoBo) {
        if(chgInfoBo == null) {
            return;
        }
        //如果变动类型是跨公司调动，则自动处理档案
        //如果要加其他变动类型的调用自动处理，需要增加变动类型判断
        PersonnelChangeTypeEnum changeTypeEnum = PersonnelChangeTypeEnum.getChangeType(chgInfoBo.getChgCategoryId());
        if(changeTypeEnum == PersonnelChangeTypeEnum.CROSS_TRANS) {
            //获取变动任务信息
            PerffileChangeEntityService perffileChangeEntityService = new PerffileChangeEntityService();
            PerffileChangeApplicationService perffileChangeApplicationService = new PerffileChangeApplicationService();
            DynamicObject[] perfFileChangeArr = perffileChangeEntityService.queryByChgRecordId(chgInfoBo.getRecordId());
            //判断变动是否是否被处理
            List<Long> changeIds = new ArrayList<>(2);
            for (DynamicObject perfFileChange : perfFileChangeArr) {
                if (STR_ONE.equals(perfFileChange.getString("processstatus"))) {
                    changeIds.add(perfFileChange.getLong(ID));
                }
            }
            PerffileEntityService perffileEntityService = new PerffileEntityService();
            if(!changeIds.isEmpty()) {
                //获取档案变动详情
                DynamicObjectType entityType = EntityMetadataCache.getDataEntityType("pmd_perffilechange");
                DynamicObject[] perfFileChangeInfoArr = BusinessDataServiceHelper.load(changeIds.toArray(), entityType);

                for (DynamicObject dynamicObject : perfFileChangeInfoArr) {
                    if (PerffileChangeConstants.CHGMODE_ADD.equals(dynamicObject.getString(PerffileChangeConstants.CHGMODE))) {
                        //新增档案时，绩效组织可编辑
                        dynamicObject.set(PerffileChangeConstants.PERFORG, dynamicObject.get(PerffileChangeConstants.PERFORGA));
                    }
                    //设置为任务已处理
                    dynamicObject.set(PerffileChangeConstants.PROCESS_STATUS, STR_TWO);
                    //调用档案变动处理服务
                    perffileChangeApplicationService.processPerffileChange(dynamicObject);
                    //处理考核活动
                    if (PerffileChangeConstants.CHGMODE_ADD.equals(dynamicObject.getString(PerffileChangeConstants.CHGMODE))) {
                        this.addPersonToActivityByPerffileChange(dynamicObject, perffileEntityService);
                    }
                }
            }
        }

    }

    /**
     * 添加员工到考核活动中
     * @param dynamicObject
     * @param perffileEntityService
     */
    private void addPersonToActivityByPerffileChange(DynamicObject dynamicObject, PerffileEntityService perffileEntityService) {
        DynamicObject depempa = dynamicObject.getDynamicObject("depempa");
        DynamicObject[] perffile = perffileEntityService.query("id,name",new QFilter[]{new QFilter("depemp.id","=",depempa.getLong(ID))});
        if(perffile.length>0) {
            //新增档案时，根据岗位（hbpm_positionhr）加入考核活动逻辑：入职单中如果是包括项目经理岗的（模糊查询，包括项目经理四个字），均自动添加到项目经理考核活动中；

            DynamicObject pos = dynamicObject.getDynamicObject(PerffileChangeConstants.POSITION);
            DynamicObjectType positionhrEntityType = EntityMetadataCache.getDataEntityType("hbpm_positionhr");
            pos = BusinessDataServiceHelper.loadSingle(pos.getLong(ID), positionhrEntityType);
            //岗位类型(hbpm_positiontype)
            String posName = pos.getString(NAME);

            DynamicObjectCollection successList = new DynamicObjectCollection();
            successList.add(perffile[perffile.length - 1]);
            //包含项目经理
            if (posName.contains(PerffileActivityConstants.PROJECT_MANAGER)) {
                //取启动中的考核活动
                DynamicObject[] epa_activitys = BusinessDataServiceHelper.load("epa_activity", "id,name",
                        new QFilter[]{
                                new QFilter("name", "like", "%" + PerffileActivityConstants.PROJECT_MANAGER + "%"),
                                new QFilter("activitystatus", "=", "30")
                        });
                //遍历考核活动添加人员
                for (DynamicObject activity : epa_activitys) {
                    dynamicObject.get(PerffileChangeConstants.PERSON);
                    Map<String, Object> params = new HashMap(16);
                    params.put("activity_id", activity.getLong(ID));
                    params.put("success_list", successList.stream().map((data) -> data.getLong("id")).collect(Collectors.toList()));
                    this.dispatch(params);
                }
            }
            else {
                //如果是非项目经理岗，且岗位类型为非管理岗的，均添加到员工考核活动中。同时添加的时候，要添加到启动中的考核活动中。
                DynamicObject positiontype = pos.getDynamicObject("positiontype");
                DynamicObjectType positiontypeEntityType = EntityMetadataCache.getDataEntityType("hbpm_positiontype");
                positiontype = BusinessDataServiceHelper.loadSingle(positiontype.getLong(ID), positiontypeEntityType);
                //为非管理岗
                if(!positiontype_number.equals(positiontype.getString(NUMBER))){
                    //取启动中的考核活动
                    DynamicObject[] epa_activitys = BusinessDataServiceHelper.load("epa_activity", "id,name",
                            new QFilter[]{
                                    new QFilter("name", "like", "%" + PerffileActivityConstants.PROJECT_ORDINARY + "%"),
                                    new QFilter("activitystatus", "=", "30")
                            });
                    //遍历考核活动添加人员
                    for (DynamicObject activity : epa_activitys) {
                        dynamicObject.get(PerffileChangeConstants.PERSON);
                        Map<String, Object> params = new HashMap(16);
                        params.put("activity_id", activity.getLong(ID));
                        params.put("success_list", successList.stream().map((data) -> data.getLong("id")).collect(Collectors.toList()));
                        this.dispatch(params);
                    }
                }
            }
        }
    }

    public void dispatch(Map<String, Object> params) {
        JobInfo jobInfo = new JobInfo();
        jobInfo.setAppId("epa");
        jobInfo.setJobType(JobType.REALTIME);
        jobInfo.setRunByUserId(RequestContext.get().getCurrUserId());
        jobInfo.setId(UUID.randomUUID().toString());
        jobInfo.setParams(params);
        jobInfo.setTaskClassname(ActivityAddActObjTask.class.getName());
        JobFormInfo jobFormInfo = new JobFormInfo(jobInfo);
        jobFormInfo.setCaption(ResManager.loadKDString(ResManager.loadKDString("添加评估对象", "EvalObjectJoinedList_7", "opmc-epa-formplugin", new Object[0]), "DispatchUtil_1", "opmc-epa-common", new Object[0]));
        //jobFormInfo.setCloseCallBack(closeCallBack);
        jobFormInfo.setCanBackground(false);
        jobFormInfo.setCanStop(false);
    }
}
