package nckd.jxccl.hr.ijp.plugin.form.recgen;

import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.QueryEntityType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.hr.hbp.business.servicehelper.HRQueryEntityHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;
import nckd.jxccl.hr.ijp.common.IntJobPostConstant;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
* 三类人员记录生成
* 实体标识：nckd_intjobpost
* @author W.Y.C
* @date 2026/1/7 11:41
* @version 1.0
*/
public class IntJobPostFormPlugin extends AbstractFormPlugin implements Plugin {

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs evt) {
        if(evt.getOperationResult() != null && evt.getOperationResult().isSuccess()){
            String operateKey = evt.getOperateKey();
            if(IntJobPostConstant.FETCHEMP_OP.equalsIgnoreCase(operateKey)){
                String talentType = ConvertUtil.toStr(this.getModel().getValue(IntJobPostConstant.NCKD_TALENTTYPE));
                DynamicObject org = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(IntJobPostConstant.NCKD_ORG));
                if(StringUtils.isBlank(talentType)){
                    this.getView().showTipNotification("请先选择人员类别！");
                }else if(org == null){
                    this.getView().showTipNotification("请先选择二级单位！");
                }else{
                    if("A".equalsIgnoreCase(talentType)){
                        getExcellentEmp();
                    }else if("B".equalsIgnoreCase(talentType)){

                    }else{

                    }
                }
            }
        }
    }

    //获取优秀生员工
    //本单位工作（工作信息-进本单位时间）满5年，距法定退休年龄（工作信息-新法定退休日期）超过5年且上年度员工绩效考核为优秀的所有员工
    private void getExcellentEmp(){
        DynamicObject org = ConvertUtil.toDynamicObjectOrNull(this.getModel().getValue(IntJobPostConstant.NCKD_ORG));
        //前5年
        LocalDateTime firstFiveYears = DateUtil.minusYears(DateUtil.now(), 5);
        //后5年
        LocalDateTime fiveYearsLater = DateUtil.addYears(DateUtil.now(), 5);

        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.STARTDATE)
                .addIdNumberName(FormConstant.ADMINORG)
                .addIdNumberName(FormConstant.POSITION_KEY)
                .addGroup(new String[]{FormConstant.EMPLOYEE_KEY}, FormConstant.ID_KEY, FormConstant.NAME_KEY, FormConstant.EMP_NUMBER_KEY)
                .orderDesc(FormConstant.STARTDATE);

        QFilter qFilter = new QFilter(String.join(".", FormConstant.ADMINORG, FormConstant.NCKD_SECONDORG), QCP.equals, org.getLong(FormConstant.ID_KEY))
                .and(QFilterCommonHelper.getValidDateFilter(FormConstant.STARTDATE, FormConstant.ENDDATE))
                //任职类型：上挂/全职任职
                .and(String.join( ".", FormConstant.POSTYPE, FormConstant.NUMBER_KEY), QCP.in,new String[]{"JTCC_1002", "1010_S"})
                //在职人员
                .and(String.join(".", FormConstant.HRPI_EMPENTREL, FormConstant.LABOR_REL_STATUS, FormConstant.IS_HIRED), QCP.equals, EnableEnum.YES.getCode())
                //进本单位满5年
                .and(String.join(".", FormConstant.HRPI_EMPENTREL, FormConstant.STARTDATE), QCP.less_equals, DateUtil.toDate(firstFiveYears));
                //新法定退休日期超过5年条件，或退休日期为空
        QFilter lanRetDtFilter = new QFilter(String.join(".", FormConstant.HRPI_PERSERLEN, FormConstant.NCKD_NEWPLANRETDT), QCP.is_null,null)
                .or(String.join(".", FormConstant.HRPI_PERSERLEN, FormConstant.NCKD_NEWPLANRETDT), QCP.large_equals, DateUtil.toDate(fiveYearsLater));
        qFilter.and(lanRetDtFilter);
        QueryEntityType queryEntityType = (QueryEntityType) EntityMetadataCache.getDataEntityType("personfilequery");
        DynamicObjectCollection personList = HRQueryEntityHelper.getInstance().getQueryDyoColl(queryEntityType, queryFieldBuilder.buildSelect(), new QFilter[]{qFilter}, queryFieldBuilder.buildOrder());
        Map<Long, DynamicObject> personMap = personList.stream()
                .collect(Collectors.groupingBy(
                        obj -> obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY))
                ))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().get(0) // 由于已按日期降序排列，取第一条即为最新
                ));

        //获取上年和上上年考核结果
        QueryFieldBuilder perfManagerQueryFieldBuilder = QueryFieldBuilder.create()
                .addIdNumberName("nckd_appraisalresult")
                .add("nckd_appraisalyear");

        Date beginDate = DateUtil.beginOfYear(DateUtil.minusYears(DateUtil.nowDate(), 2));
        Date endDate = DateUtil.endOfYear(DateUtil.minusYears(DateUtil.nowDate(), 1));
        QFilter perfManagerFilter = new QFilter("nckd_appraisalyear",QCP.large_equals,beginDate)
                .and("nckd_appraisalyear",QCP.less_equals,endDate)
                .and(String.join(".", "nckd_perfmanager", FormConstant.NCKD_PERSON), QCP.in, personMap.keySet());
        DynamicObjectCollection query = QueryServiceHelper.query("nckd_perfmanagerentry", perfManagerQueryFieldBuilder.buildSelect(), new QFilter[]{perfManagerFilter});
        for (DynamicObject dynamicObject : query) {
            
        }

    }
}