package nckd.jxccl.base.hrpi.helper;

import com.google.common.collect.Lists;
import kd.bos.common.enums.EnableEnum;
import kd.bos.dataentity.entity.DynamicObject;
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.QueryFieldBuilder;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 任职经历Helper类
 * 提供员工任职经历相关信息的查询功能
 *
 * @author W.Y.C
 * @date 2025/11/4 15:33
 * @version 1.0
 */
public class EmpPosOrgRelHelper {

    /**
     * 获取服务年限
     * @param assignmentIds 组织分配ID
     * @return: kd.bos.dataentity.entity.DynamicObject[]
     * @author W.Y.C
     * @date: 2025/12/25 09:57
     */
    public static DynamicObject[] getPerSerLen(Collection<Long> assignmentIds){
        QFilter queryFilter = QFilterCommonHelper.getIsCurrentData()
                .and(String.join(".",FormConstant.ASSIGNMENT,FormConstant.ID_KEY),QCP.in,assignmentIds);
        QueryFieldBuilder queryField = QueryFieldBuilder.create()
                .addIdNumberName(FormConstant.EMPLOYEE_KEY)
                .add(FormConstant.FIRSTJOINCOMDATE_KEY)
                .add(FormConstant.JOINCOMDATE_KEY)
                .add(FormConstant.STARTDATE)
                .add(FormConstant.ENDDATE)
                .add(FormConstant.SOCIALWORKAGE)
                .orderDesc(FormConstant.CREATE_TIME_KEY,FormConstant.MODIFY_TIME_KEY);
        return BusinessDataServiceHelper.load(FormConstant.HRPI_PERSERLEN, queryField.buildSelect(),new QFilter[]{queryFilter});
    }
    /**
     * 查询所有“全职任职”和“在岗”的任职经历
     * @return: kd.bos.dataentity.entity.DynamicObject[]
     * @author W.Y.C
     * @date: 2025/12/25 09:47
     */
    public static DynamicObject[] allEmpPosOrgRel() {
        //查询在职人员任职经历
        QFilter queryFilter = new QFilter(FormConstant.IS_SEQLATESTRECORD, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.IS_DELETED, QCP.equals, EnableEnum.NO.getCode())
                .and(FormConstant.IS_PRIMARY, QCP.equals, EnableEnum.YES.getCode())
                .and(String.join( ".", FormConstant.POSITION_KEY, FormConstant.NCKD_JOBSEQ),QCP.is_notnull,null)
                //全职任职
                .and(String.join(".", FormConstant.POSTYPE,FormConstant.POSTCATEGORY,FormConstant.NUMBER_KEY),QCP.equals,"1010_S")
                //在岗
                .and(String.join( ".", FormConstant.POS_STATUS, FormConstant.POST_STATE_CLS, FormConstant.NUMBER_KEY),QCP.equals,"1010_S");
        String selectProperties = selectProperties().buildSelect();
        String order = selectProperties().buildOrder();
        return BusinessDataServiceHelper.load(FormConstant.HRPI_EMPPOSORGREL, selectProperties, new QFilter[]{queryFilter}, order);
    }

    //根据id查询任职经历
    public static DynamicObject[] queryEmpPosOrgRelById(Collection<Long> ids) {
        // 构建基础查询条件
        QFilter queryFilter = new QFilter(FormConstant.ID_KEY, QCP.in, ids);

        // 构建查询字段和排序规则
        QueryFieldBuilder queryFieldBuilder = selectProperties();
        queryFieldBuilder.addIdNumberName(FormConstant.POSITION_KEY,FormConstant.NCKD_WORKNATURE);
        queryFieldBuilder.addIdNumberName(FormConstant.ADMINORG,FormConstant.NCKD_FIRSTORG);
        queryFieldBuilder.addIdNumberName(FormConstant.ADMINORG,FormConstant.NCKD_SECONDORG);
        queryFieldBuilder.addIdNumberName(FormConstant.ADMINORG,FormConstant.NCKD_THIRDORG);
        queryFieldBuilder.addIdNumberName(FormConstant.ADMINORG,FormConstant.NCKD_FOURTHORG);
        queryFieldBuilder.addIdNumberName(FormConstant.ADMINORG,FormConstant.NCKD_FIFTHORG);
        queryFieldBuilder.addIdNumberName(FormConstant.ADMINORG,FormConstant.NCKD_SIXTHORG);
        String selectProperties = queryFieldBuilder.buildSelect();
        String order = selectProperties().buildOrder();

        // 执行查询并返回结果
        return BusinessDataServiceHelper.load(FormConstant.HRPI_EMPPOSORGREL, selectProperties, new QFilter[]{queryFilter}, order);
    }
    /**
     * 根据员工ID查询最新的任职经历信息
     *
     * @param employeeId 员工ID
     * @return 员工的任职经历信息，如果不存在则返回null
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static DynamicObject queryEmpPosOrgRelByEmployees(Long employeeId) {
        DynamicObject[] dynamicObjects = queryEmpPosOrgRelByEmployees(Lists.newArrayList(employeeId), null);
        return dynamicObjects.length > 0 ? dynamicObjects[0] : null;
    }

    /**
     * 根据多个员工ID查询最新的任职经历信息（含不在岗）
     *
     * @param employeeIds 员工ID集合
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static Map<Long, DynamicObject> queryEmpPosOrgRelWithOutPostByEmployeesMap(Collection<Long> employeeIds) {
        DynamicObject[] dynamicObjects = queryEmpPosOrgRelByEmployeesWithOutPost(employeeIds, null);
        // 按员工ID分组，并取每个员工的最新记录（按开始日期）
        Map<Long, List<DynamicObject>> grouped = new HashMap<>();
        for (DynamicObject obj : dynamicObjects) {
            Long empId = obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY));
            grouped.computeIfAbsent(empId, k -> new ArrayList<>()).add(obj);
        }

        // 从每组中选取开始日期最新的记录
        Map<Long, DynamicObject> result = new HashMap<>();
        for (Map.Entry<Long, List<DynamicObject>> entry : grouped.entrySet()) {
            List<DynamicObject> records = entry.getValue();
            DynamicObject latestRecord = records.stream()
                    .max((o1, o2) -> {
                        Date date1 = o1.getDate(FormConstant.STARTDATE);
                        Date date2 = o2.getDate(FormConstant.STARTDATE);
                        return date1.compareTo(date2);
                    })
                    .orElse(null);
            result.put(entry.getKey(), latestRecord);
        }

        return result;

    }

    /**
     * 根据多个员工ID查询最新的任职经历信息（含不在岗）
     *
     * @param employeeIds 员工ID集合
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static Map<Long, DynamicObject> queryEmpPosOrgRelByEmployeesMap(Collection<Long> employeeIds) {
        DynamicObject[] dynamicObjects = queryEmpPosOrgRelByEmployees(employeeIds, null);
        // 按员工ID分组，并取每个员工的最新记录（按开始日期）
        Map<Long, List<DynamicObject>> grouped = new HashMap<>();
        for (DynamicObject obj : dynamicObjects) {
            Long empId = obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY));
            grouped.computeIfAbsent(empId, k -> new ArrayList<>()).add(obj);
        }

        // 从每组中选取开始日期最新的记录
        Map<Long, DynamicObject> result = new HashMap<>();
        for (Map.Entry<Long, List<DynamicObject>> entry : grouped.entrySet()) {
            List<DynamicObject> records = entry.getValue();
            DynamicObject latestRecord = records.stream()
                    .max((o1, o2) -> {
                        Date date1 = o1.getDate(FormConstant.STARTDATE);
                        Date date2 = o2.getDate(FormConstant.STARTDATE);
                        return date1.compareTo(date2);
                    })
                    .orElse(null);
            result.put(entry.getKey(), latestRecord);
        }

        return result;

    }

    /**
     * 根据多个员工ID查询最新的任职经历信息（含历史）
     *
     * @param employeeIds 员工ID集合
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static Map<Long, DynamicObject> queryEmpPosOrgRelHisByEmployeesMap(Collection<Long> employeeIds) {
        DynamicObject[] dynamicObjects = queryEmpPosOrgRelHisByEmployees(employeeIds, null);
        // 按员工ID分组，并取每个员工的最新记录（按开始日期）
        Map<Long, List<DynamicObject>> grouped = new HashMap<>();
        for (DynamicObject obj : dynamicObjects) {
            Long empId = obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY));
            grouped.computeIfAbsent(empId, k -> new ArrayList<>()).add(obj);
        }

        // 从每组中选取开始日期最新的记录
        Map<Long, DynamicObject> result = new HashMap<>();
        for (Map.Entry<Long, List<DynamicObject>> entry : grouped.entrySet()) {
            List<DynamicObject> records = entry.getValue();
            DynamicObject latestRecord = records.stream()
                    .max((o1, o2) -> {
                        Date date1 = o1.getDate(FormConstant.STARTDATE);
                        Date date2 = o2.getDate(FormConstant.STARTDATE);
                        return date1.compareTo(date2);
                    })
                    .orElse(null);
            result.put(entry.getKey(), latestRecord);
        }

        return result;

    }

    /**
     * 根据多个员工ID查询最新的任职经历信息
     *
     * @param employeeIds 员工ID集合
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static DynamicObject[] queryEmpPosOrgRelByEmployees(Collection<Long> employeeIds) {
        return queryEmpPosOrgRelByEmployees(employeeIds, null);
    }

    /**
     * 获取员工最新有效任职经历
     * 查询条件包括：
     * 1. 员工ID在指定范围内
     * 2. 是最新记录（IS_SEQLATESTRECORD=YES）
     * 3. 未删除（IS_DELETED=NO）
     * 4. 是主任职（IS_PRIMARY=YES）
     *
     * @param employeeIds 员工ID集合
     * @param otherFilter 其他查询条件（可选）
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static DynamicObject[] queryEmpPosOrgRelByEmployees(Collection<Long> employeeIds, QFilter otherFilter) {
        // 构建基础查询条件

        QFilter queryFilter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.in, employeeIds)
                .and(FormConstant.IS_SEQLATESTRECORD, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.IS_DELETED, QCP.equals, EnableEnum.NO.getCode())
                .and(FormConstant.IS_PRIMARY, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.STARTDATE, QCP.less_equals, new Date())
                .and(FormConstant.ENDDATE, QCP.large_equals, new Date())
                .and(FormConstant.ISCURRENTDATA, QCP.equals, EnableEnum.YES.getCode())
                //在岗
                .and(String.join( ".", FormConstant.POS_STATUS, FormConstant.POST_STATE_CLS, FormConstant.NUMBER_KEY),QCP.equals,"1010_S");

        // 添加额外查询条件（如果有）
        if (otherFilter != null) {
            queryFilter.and(otherFilter);
        }

        // 构建查询字段和排序规则
        String selectProperties = selectProperties().buildSelect();
        String order = selectProperties().buildOrder();

        // 执行查询并返回结果
        return BusinessDataServiceHelper.load(FormConstant.HRPI_EMPPOSORGREL, selectProperties, new QFilter[]{queryFilter}, order);
    }

    /**
     * 获取员工最新有效任职经历（含不在岗）
     * 查询条件包括：
     * 1. 员工ID在指定范围内
     * 2. 是最新记录（IS_SEQLATESTRECORD=YES）
     * 3. 未删除（IS_DELETED=NO）
     * 4. 是主任职（IS_PRIMARY=YES）
     *
     * @param employeeIds 员工ID集合
     * @param otherFilter 其他查询条件（可选）
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static DynamicObject[] queryEmpPosOrgRelByEmployeesWithOutPost(Collection<Long> employeeIds, QFilter otherFilter) {
        // 构建基础查询条件

        QFilter queryFilter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.in, employeeIds)
                .and(FormConstant.IS_SEQLATESTRECORD, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.IS_DELETED, QCP.equals, EnableEnum.NO.getCode())
                .and(FormConstant.IS_PRIMARY, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.STARTDATE, QCP.less_equals, new Date())
                .and(FormConstant.ENDDATE, QCP.large_equals, new Date())
                .and(FormConstant.ISCURRENTDATA, QCP.equals, EnableEnum.YES.getCode());

        // 添加额外查询条件（如果有）
        if (otherFilter != null) {
            queryFilter.and(otherFilter);
        }

        // 构建查询字段和排序规则
        String selectProperties = selectProperties().buildSelect();
        String order = selectProperties().buildOrder();

        // 执行查询并返回结果
        return BusinessDataServiceHelper.load(FormConstant.HRPI_EMPPOSORGREL, selectProperties, new QFilter[]{queryFilter}, order);
    }

    /**
     * 获取员工有效任职经历（含历史）
     * 查询条件包括：
     * 1. 员工ID在指定范围内
     * 2. 是最新记录（IS_SEQLATESTRECORD=YES）
     * 3. 未删除（IS_DELETED=NO）
     * 4. 是主任职（IS_PRIMARY=YES）
     *
     * @param employeeIds 员工ID集合
     * @param otherFilter 其他查询条件（可选）
     * @return 员工的任职经历信息数组
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static DynamicObject[] queryEmpPosOrgRelHisByEmployees(Collection<Long> employeeIds, QFilter otherFilter) {
        // 构建基础查询条件

        QFilter queryFilter = new QFilter(FormConstant.EMPLOYEE_KEY, QCP.in, employeeIds)
                .and(FormConstant.IS_SEQLATESTRECORD, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.IS_DELETED, QCP.equals, EnableEnum.NO.getCode())
                .and(FormConstant.IS_PRIMARY, QCP.equals, EnableEnum.YES.getCode())
                .and(FormConstant.STARTDATE, QCP.less_equals, new Date())
                .and(FormConstant.ENDDATE, QCP.large_equals, new Date())
                //在岗
                .and(String.join( ".", FormConstant.POS_STATUS, FormConstant.POST_STATE_CLS, FormConstant.NUMBER_KEY),QCP.equals,"1010_S");

        // 添加额外查询条件（如果有）
        if (otherFilter != null) {
            queryFilter.and(otherFilter);
        }

        // 构建查询字段和排序规则
        String selectProperties = selectProperties().buildSelect();
        String order = selectProperties().buildOrder();

        // 执行查询并返回结果
        return BusinessDataServiceHelper.load(FormConstant.HRPI_EMPPOSORGREL, selectProperties, new QFilter[]{queryFilter}, order);
    }

    /**
     * 构建查询字段和排序规则
     * 包含员工基本信息、岗位类型、组织架构等相关字段
     *
     * @return QueryFieldBuilder 查询字段构建器
     * @author W.Y.C
     * @date: 2025/11/04 16:02
     */
    public static QueryFieldBuilder selectProperties() {
        return QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.IS_PRIMARY)
                .add(FormConstant.STARTDATE)
                .addIdNumberName(FormConstant.EMPLOYEE_KEY)
                .addIdNumberName(FormConstant.CHGACTION)
                .addIdNumberName(FormConstant.POSTYPE)
                .addIdNumberName(FormConstant.POS_STATUS)
                // 所属公司
                .addIdNumberName(FormConstant.COMPANY_KEY)
                // 行政组织（部门）
                .add(FormConstant.ADMINORG)
                .addIdNumberName(FormConstant.ADMINORG)
                // 岗位
                .addIdNumberName(FormConstant.POSITION_KEY)
                .addIdNumberName(FormConstant.POSITION_KEY,FormConstant.NCKD_JOBSEQ)
                .addIdNumberName(FormConstant.ASSIGNMENT)
                .orderDesc(FormConstant.STARTDATE)
                .orderDesc(FormConstant.ENDDATE);
    }
}
