package nckd.jxccl.base.wtc.helper;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.ObjectUtils;
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.servicehelper.QueryServiceHelper;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;

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

/**
 * Tyx 2025-11-28
 * 考勤帮助类
 */
public class WTCHelper {

    private static final Log logger = LogFactory.getLog(WTCHelper.class);
    public static final HRBaseServiceHelper HOLIDAYFOROT_HELPER = new HRBaseServiceHelper("nckd_holidayforot");
    public static final HRBaseServiceHelper OTBILL_HELPER = new HRBaseServiceHelper("wtom_overtimeapplybill");
    public static final HRBaseServiceHelper OTTYPE_HELPER = new HRBaseServiceHelper("wtbd_ottype");
    /* 工作流角色 */
    public static final HRBaseServiceHelper WFROLE_HELPER = new HRBaseServiceHelper("wf_role");
    public static final HRBaseServiceHelper VAAPPLY_HELPER = new HRBaseServiceHelper("wtabm_vaapply");
    public static final HRBaseServiceHelper PARTYPOSH_HELPER = new HRBaseServiceHelper("nckd_hrpi_partyposh");

    /**
     * 根据考勤档案ID获取二级单位编码
     * @param attFileId
     */
    public static String getSecondOrgNumberByAttFileId (Long attFileId) {
        QFilter filter = new QFilter ("id", QCP.equals, attFileId);
        String selectFields = "adminorg.nckd_secondorg.number";
        return null;
    }

    /**
     * 根据加班归属日期获取假期
     *
     * @return
     */
    public static DynamicObject getHolidayByOtDutyDate (Date otDutyDate) {
        QFilter filter = new QFilter("nckd_startdate", QCP.less_equals, otDutyDate);
        filter.and("nckd_enddate", QCP.large_equals, otDutyDate);
        DynamicObject dyn = HOLIDAYFOROT_HELPER.queryOriginalOne("name, nckd_startdate, nckd_enddate, nckd_holidays", filter.toArray());
        return dyn;
    }

    /**
     * 根据起止日期+考勤档案+排除ID获取加班日期的天数
     * 如果加班单为yyyy-MM-dd 18:00:00 至 yyyy-MM-dd 19:00:00，不管实际加班小时，计作一天
     *
     * @param startDate
     * @param endDate
     * @param attfileId
     * @param billId
     * @return
     */
    public static int getOTDays(Date startDate, Date endDate, Long attfileId, Long billId) {
        QFilter filter = new QFilter("attfile.id", QCP.equals, attfileId);
        filter.and("id", QCP.not_equals, billId);
        filter.and("sdentry.otdutydate", QCP.large_equals, startDate);
        filter.and("sdentry.otdutydate", QCP.less_equals, endDate);
        DynamicObjectCollection cols = OTBILL_HELPER.queryOriginalCollection("id,sdentry.otdutydate", filter.toArray());
        Set<Date> dateSet = cols.stream().map(dyn -> dyn.getDate("sdentry.otdutydate")).collect(Collectors.toSet());
        return dateSet.size();
    }

    /**
     * 获取加班类型
     * @param number 加班类型编码
     * @return
     */
    public static DynamicObject getSdOtType (String number) {
        QFilter filter = new QFilter("number", QCP.equals, number);
        return OTTYPE_HELPER.loadOne(filter.toArray());
    }

    /**
     * 根据角色编码+用户ID获取工作流角色信息
     *
     * @param roleNumber
     * @param userId
     * @return
     */
    public static DynamicObject getWFRoleByUserId (String roleNumber, long userId) {
        QFilter filter = new QFilter("number", QCP.equals, roleNumber);
        filter.and("roleentry.user.id", QCP.equals, userId);
        return WFROLE_HELPER.queryOriginalOne("roleentry.org.id, roleentry.includadminsub", filter.toArray());
    }


    /**
     * 根据组织ID列表获取关键岗位信息
     * @param orgIds 组织ID列表
     * @return
     */
    public static List<Long> getKeyPositionByOrg (List<Long> orgIds) {
        QFilter filter = new QFilter("nckd_iskeypos", QCP.equals, "1");
        filter.and(QFilterCommonHelper.getCurrentVersionFilter());
        filter.and("adminorg.id", QCP.in, orgIds);
        HRBaseServiceHelper helper = new HRBaseServiceHelper(FormConstant.HBPM_POSITIONHR);
        DynamicObjectCollection positions = helper.queryOriginalCollection("id", filter.toArray());
        return positions.stream().map(position -> position.getLong("id")).collect(Collectors.toList());
    }


    /**
     * 获取休假单信息
     *
     * @param positionIds
     * @param startDate
     * @param endDate
     * @param billId
     * @return
     */
    public static DynamicObjectCollection getVaApplyInfo (List<Long> positionIds, Date startDate, Date endDate, Long billId) {
        QFilter filter = getVaApplyFilter(positionIds, startDate, endDate, billId);
        String selectFields = getVaApplySelectFields();
        DynamicObjectCollection cols = VAAPPLY_HELPER.queryOriginalCollection(selectFields, filter.toArray());
        return cols;
    }


    /**
     * 获取休假单过滤条件
     *
     * @param positionIds
     * @param startDate
     * @param endDate
     * @param billId
     * @return
     */
    public static QFilter getVaApplyFilter (List<Long> positionIds, Date startDate, Date endDate, Long billId) {
        QFilter filter = new QFilter("attfile.position.id", QCP.in, positionIds);
        filter.and("applytime", QCP.large_than, BigDecimal.ZERO);
        filter.and("billstatus", QCP.in,  new HashSet<>(Arrays.asList("B", "C", "D")));
        filter.and("id", QCP.not_equals, billId);

        String startField = "startdate";
        String endField = "enddate";
        QFilter startFilter = new QFilter(startField, QCP.less_equals, startDate);
        startFilter.and(new QFilter(endField, QCP.large_equals, startDate));

        QFilter endFilter = new QFilter(startField, QCP.less_equals, endDate);
        endFilter.and(new QFilter(endField, QCP.large_equals, endDate));

        QFilter startFilter1 = new QFilter( startField, QCP.large_equals, startDate);
        startFilter1.and(new QFilter(startField, QCP.less_than, endDate));

        QFilter endFilter1 = new QFilter(endField, QCP.large_equals, startDate);
        endFilter1.and(new QFilter( endField, QCP.less_than, endDate));

        filter.and(startFilter.or(endFilter).or(startFilter1).or(endFilter1));

        return filter;
    }

    /**
     * 获取休假单查询字段
     * @return
     */
    public static String getVaApplySelectFields() {
        String selectFields = "billno, attfile.empnumber, attfile.employee.name, attfile.adminorg.name, attfile.position.name, startdate, enddate";
        return selectFields;
    }


    /**
     * 根据用户ID查询员工ID
     * @param userId
     * @return
     */
    public static Long queryEmployeeIdByUserId(Long userId) {
        HRBaseServiceHelper SERVICE_HELPER = new HRBaseServiceHelper("hrpi_personuserrel");
        DynamicObject personuserrel = SERVICE_HELPER.queryOne("employee,user,createtime", new QFilter[]{new QFilter("user", "=", userId), new QFilter("enable", "=", "1")}, "createtime desc");
        return personuserrel == null ? 0L : personuserrel.getLong("employee_id");
    }

    /**
     * 根据employeeId查询任职经历
     * @param employeeId
     * @return
     */
    public static DynamicObjectCollection queryEmpPosOrgRelDyns (List<Long> employeeId) {
        QFilter filter = new QFilter("iscurrentdata", QCP.equals, "1"); // 启用
        filter.and(new QFilter("employee.id", QCP.in, employeeId));

        String selectFields1 = "adminorg.id, position.id";
        DynamicObjectCollection empposorgreDyns = QueryServiceHelper.query("hrpi_empposorgrel", selectFields1, filter.toArray());

        return empposorgreDyns;
    }

    /**
     * 获取岗位直接下级的关键岗位
     * @param positionIds
     * @return
     */
    public static List<Long> getSubKeyPositions(List<Long> positionIds) {
        QFilter filter = new QFilter ("parent.id", QCP.in, positionIds);
        filter.and("nckd_iskeypos", QCP.equals, "1");
        DynamicObjectCollection subPositionDyns = QueryServiceHelper.query("hbpm_positionhr", "id", filter.toArray());
        return subPositionDyns.stream().map(dyn -> dyn.getLong("id")).collect(Collectors.toList());
    }

    /**
     * 根据员工ID获取职务层级
     * 员工档案-党政职务变更履历-职务层级
     * @param employeeId
     * @return
     */
    public static String getZwcjByEmployeeId(Long employeeId) {
        QFilter filter = new QFilter("employee.id", QCP.equals, employeeId);
        filter.and("startdate", QCP.less_equals, new Date());
        filter.and("enddate", QCP.large_equals, new Date());
        String selectFields = "nckd_posgrade.name";
        DynamicObject dyn = PARTYPOSH_HELPER.queryOriginalOne(selectFields, filter.toArray());
        return ObjectUtils.isEmpty(dyn)? null : dyn.getString("nckd_posgrade.name");
    }
}
