package nckd.jxccl.base.pm.helper;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 人员考评管理帮助类
 * @author W.Y.C
 * @date 2025/9/11 14:21
 * @version 1.0
 */
public class PerformanceManagerHelper {

    /** 人员考评管理实体名称 */
    public static final String PERFMANAGER_ENTITYID = "nckd_perfmanager";
    /** 人员考评管理分录实体名称 */
    public static final String PERFMANAGER_ENTRY_ENTITYID = "nckd_perfmanagerentry";
    /** 分录-考核年份 */
    public static final String NCKD_APPRAISALYEAR = "nckd_appraisalyear";
    /** 分录-考评结果 */
    public static final String NCKD_APPRAISALRESULT = "nckd_appraisalresult";


    /**
     * 获取某个员工某个年度的考评结果
     * @param personId 人员ID
     * @param date 年度
     * @return: DynamicObject（返回考评结果实体，可能为null）
     * @author W.Y.C
     * @date: 2025/09/11 14:25
     */
    public static DynamicObject getPerformanceResult(Long personId, LocalDateTime date) {
        LocalDateTime beginOfYear = DateUtil.beginOfYear(date);
        LocalDateTime endOfYear = DateUtil.endOfDay(date);
        QFilter filter = new QFilter(String.join(".",FormConstant.NCKD_PERSON, FormConstant.ID_KEY), QCP.equals,personId)
                .and(new QFilter(String.join(".",PERFMANAGER_ENTRY_ENTITYID, NCKD_APPRAISALYEAR),QCP.equals,beginOfYear));

        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .addGroup(new String[]{PERFMANAGER_ENTRY_ENTITYID}, NCKD_APPRAISALYEAR,NCKD_APPRAISALRESULT,FormConstant.NCKD_SCORE)
                .addIdNumberNameWithExtras(new String[]{PERFMANAGER_ENTRY_ENTITYID, NCKD_APPRAISALRESULT}, FormConstant.NCKD_SCORE)
                .orderDesc(FormConstant.CREATE_TIME_KEY);
        DynamicObject[] load = BusinessDataServiceHelper.load(PERFMANAGER_ENTITYID, queryFieldBuilder.buildSelect(), new QFilter[]{filter},queryFieldBuilder.buildOrder() );
        if(load != null && load.length > 0){
            DynamicObject perfManager = load[0];
            DynamicObjectCollection perfManagerEntryColl = perfManager.getDynamicObjectCollection(PERFMANAGER_ENTRY_ENTITYID);
            for (DynamicObject perfManagerEntry : perfManagerEntryColl) {
                Date year = perfManagerEntry.getDate(NCKD_APPRAISALYEAR);
                if(DateUtil.isInRange(DateUtil.toLocalDateTime(year),beginOfYear,endOfYear)){
                    //只返回符合的年度考核结果
                    return perfManagerEntry.getDynamicObject(NCKD_APPRAISALRESULT);
                }

            }
        }
        return null;
    }
}