package nckd.jxccl.base.swc.helper;

import com.google.common.collect.Lists;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.tree.TreeNode;
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.BusinessDataServiceHelper;
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.util.*;
import java.util.stream.Collectors;

/**
 * 描述: 封装SWC常用方法
 * @author turborao
 * @date 2025/11/26 10:05
 */
public class SWCHelper {

    private static final Log log = LogFactory.getLog(SWCHelper.class);
    /**
     * 根据任务ID查询任务信息
     * @param id
     * @return
     */
    public static DynamicObject queryTaskInfoById(Long id) {
        String selPros = "id,number,taskstatus, name, startdate, enddate, ishandleproration,taxitemschemev,country,org,calrulev,paysubjectv,calversionno,tasktype,payrollgroupv.currency.amtprecision,islimitadd,payrollgroupv.currency.name";
        return queryOne(selPros, FormConstant.HSAS_CALPAYROLLTASK, id);
    }

    /**
     * 查询单条数据
     * @param selectProperties
     * @param entityName
     * @param pk
     */
    public static DynamicObject queryOne(String selectProperties,String entityName, Object pk) {
        try {
            return BusinessDataServiceHelper.loadSingle(pk, entityName, selectProperties);
        } catch (RuntimeException var4) {
            log.error("Error occurs when query {}[{}]", entityName, pk);
            return null;
        }
    }

    /**
     * 查询单条数据
     * @param entityName
     * @param pk
     * @return
     */
    public static DynamicObject queryOne(String entityName,Object pk) {
        try {
            return BusinessDataServiceHelper.loadSingle(pk, entityName);
        } catch (RuntimeException var3) {
            log.error("Error occurs when query {}[{}]", entityName, pk);
            return null;
        }
    }

    /**
     * 查询单条数据
     * @param entityName
     * @param selectFields
     * @param fieldName
     * @param filtersValue
     * @return
     */
    public static DynamicObject queryOne(String entityName,String selectFields,String fieldName,Object filtersValue) {
        try {
            QFilter filter1 = new QFilter(fieldName, QCP.equals, filtersValue); // 启用
            return QueryServiceHelper.queryOne(entityName, selectFields,new QFilter[]{filter1});
        } catch (RuntimeException var3) {
            log.error("Error occurs when query {}[{},{}]", entityName, selectFields,fieldName);
            return null;
        }
    }

    /**
     * 批量查询数据 按员工ID
     * @param employeeId
     * @return
     */
    public static Map<Long, DynamicObject> queryCalPersonList(Long employeeId) {

        QFilter filter = new QFilter("employee.id", QCP.equals, employeeId);
        DynamicObjectCollection dyns = QueryServiceHelper.query(FormConstant.HSAS_CALPERSON, "id,name,adminorg.nckd_firstorg.name,adminorg.nckd_secondorg.name,adminorg.nckd_thirdorg.name,adminorg.nckd_fourthorg.name,adminorg.nckd_fifthorg.name,adminorg.nckd_sixthorg.name,empposorgrelsndet.position.name", new QFilter[]{filter});

        Map<Long, DynamicObject> dynsMap = (Map)dyns.stream().collect(Collectors.toMap((obj) -> {
            return obj.getLong("id");
        }, (obj) -> {
            return obj;
        }, (k1, k2) -> {
            return k1;
        }));



        return dynsMap;
    }

    /**
     * 按员工ID查询薪酬数据
     * @param calPersonIds
     * @param startdate
     * @param enddate
     * @return
     */
    public static DynamicObjectCollection querySalaryList(List<Long> calPersonIds, Date startdate, Date enddate, String type) {

        // 获取核算列表信息
        QFilter filter = new QFilter("calpersonid", QCP.in, calPersonIds);
        if(type.equals("10")){
            filter.and("caltask.paydate", QCP.large_equals, startdate);
            filter.and("caltask.paydate", QCP.less_equals, enddate);
        }else{
            filter.and("caltask.payrolldate", QCP.large_equals, startdate);
            filter.and("caltask.payrolldate", QCP.less_equals, enddate);
        }
        //filter.and("caltask.taskstatuse", QCP.equals, "4");   ///任务状态  已审核 7  审批通过 4
        filter.and("hsas_caltableentry.calamountvalue", QCP.large_than, 0);
        String orderStr = "hsas_caltableentry.salaryitem.statisticstag.number";
        String selectFields = "calpersonid,caltask.id,caltask.org.name,caltask.calrule.name,caltask.calcount,hsas_caltableentry.salaryitem.number,hsas_caltableentry.salaryitem.name,hsas_caltableentry.calamountvalue,hsas_caltableentry.salaryitem.statisticstag.number";
        if(type.equals("10")){
            selectFields = selectFields + ",caltask.paydate as bizdate";
            //orderStr = "caltask.paydate";
        }else{
            selectFields = selectFields + ",caltask.payrolldate as bizdate";
            //orderStr = "caltask.payrolldate";
        }
        selectFields = selectFields + ",caltask.paydate,caltask.payrolldate";

        DynamicObjectCollection calTableDyns = QueryServiceHelper.query(FormConstant.HSAS_CALTABLE, selectFields, new QFilter[]{filter}, orderStr);

        return calTableDyns;
    }

    /**
     * 按薪资业务单元 和 薪酬项目查询薪酬数据
     * @param orgIds
     * @param startdate
     * @param enddate
     * @return
     */
    public static DynamicObjectCollection querySalaryByOrgList(List<Long> orgIds,List<String> itemNumber, Date startdate, Date enddate, String type) {

        // 获取核算列表信息
        QFilter filter = new QFilter("org.id", QCP.in, orgIds);
        if(type.equals("10")){
            filter.and("caltask.paydate", QCP.large_equals, startdate);
            filter.and("caltask.paydate", QCP.less_equals, enddate);
        }else{
            filter.and("caltask.payrolldate", QCP.large_equals, startdate);
            filter.and("caltask.payrolldate", QCP.less_equals, enddate);
        }
        if(itemNumber != null && !itemNumber.isEmpty()){
            filter.and("hsas_caltableentry.salaryitem.number", QCP.in, itemNumber);
        }
        //filter.and("caltask.taskstatuse", QCP.equals, "4");   ///任务状态  已审核 7  审批通过 4
        filter.and("hsas_caltableentry.calamountvalue", QCP.large_than, 0);
        String orderStr = "hsas_caltableentry.salaryitem.statisticstag.number";
        String selectFields = "calpersonid,caltask.id,caltask.org.name,caltask.calrule.name,caltask.calcount,hsas_caltableentry.salaryitem.number,hsas_caltableentry.salaryitem.name,hsas_caltableentry.calamountvalue,hsas_caltableentry.salaryitem.statisticstag.number,org.id";
        if(type.equals("10")){
            selectFields = selectFields + ",caltask.paydate as bizdate";
            //orderStr = "caltask.paydate";
        }else{
            selectFields = selectFields + ",caltask.payrolldate as bizdate";
            //orderStr = "caltask.payrolldate";
        }
        selectFields = selectFields + ",caltask.paydate,caltask.payrolldate";

        DynamicObjectCollection calTableDyns = QueryServiceHelper.query(FormConstant.HSAS_CALTABLE, selectFields, new QFilter[]{filter}, orderStr);

        return calTableDyns;
    }

    /**
     * 根据用户ID查询员工ID
     * @param userId
     * @return
     */
    public static Long queryEmployeeIdByUserId(Long userId) {
        HRBaseServiceHelper SERVICE_HELPER = new HRBaseServiceHelper(FormConstant.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");
    }

    /**
     * 获取 定调薪类型
     */
    public static  DynamicObjectCollection getSalaryTypeDyns() {

        QFilter qFilter11 = new QFilter("number", QCP.in, FormConstant.getsalaryTypeList());
        DynamicObjectCollection salaryTypeDyns = QueryServiceHelper.query(FormConstant.HSBS_SALARYADJUSTRSN,"id,number,name",new QFilter[]{qFilter11},"number");
        return salaryTypeDyns;
    }

    /**
     * 定调薪人员属性配置
     * @param SalaryPersonPropertyName
     * @return
     */
    public static DynamicObject getSalaryPersonProperty(String SalaryPersonPropertyName) {
        QFilter qFilter = new QFilter("name", QCP.equals, SalaryPersonPropertyName);
        DynamicObject salaryPersonPropertDyn = QueryServiceHelper.queryOne(FormConstant.HCDM_CONTRASTPROPCONF,"id,number,name",new QFilter[]{qFilter});
        return salaryPersonPropertDyn;
    }

    /**
     * 获取员工定调薪档案  hcdm_adjfileinfo
     * 员工定调薪档案 会有多条，需要按岗位获取
     * stdscm.entryentity.salarystandard.id  标准表 ID
     * @param employeeID  员工ID
     * @param positionID  岗位ID
     */
    public static DynamicObject getSalaryFileInfo(Long employeeID, Long positionID){

        QFilter qFilter = new QFilter("employee.id", QCP.equals, employeeID);
        QFilter qFilter1 = new QFilter("iscurrentversion", QCP.equals, "1"); // 启用
        QFilter qFilter2 = new QFilter("datastatus", QCP.equals, "1"); // 启用
        QFilter qFilter3 = new QFilter("position.id", QCP.equals, positionID);
        String selectField = "id,boid,number,employee.id,org.id,country.id,salarystructure.id,stdscm.id,empgroup.id,position.nckd_postgrade.id";
        DynamicObject employeesFiles = QueryServiceHelper.queryOne(FormConstant.HCDM_ADJFILEINFO, selectField, new QFilter[]{qFilter,qFilter1,qFilter2,qFilter3});

        return employeesFiles;
    }


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

        String selectFields1 = "employee.id,adminorg.id,adminorg.belongcompany.id,company.id,adminorg.structlongnumber";
        DynamicObject[] empposorgreDyns = BusinessDataServiceHelper.load("hrpi_empposorgrel", selectFields1, filter.toArray());

        return empposorgreDyns;
    }

    /**
     * 根据emoloyeeId获取人员证件信息
     * @param employeeId
     * @return
     */
    public static DynamicObject[] queryPercreDyns (List<Long> employeeId) {
        QFilter filter = new QFilter("ismajor", QCP.equals, "1"); // 启用
        filter.and(new QFilter("employee.id", QCP.in, employeeId));

        String selectFields1 = "employee.id,number";
        DynamicObject[] percreDyns = BusinessDataServiceHelper.load("hsbs_percre", selectFields1, filter.toArray());

        return percreDyns;
    }

    /**
     * 判断集合是否为空
     * @param list
     * @return
     */
    public static <T> boolean isEmpty(List<T> list) {
        return null == list || list.size() == 0;
    }


    /**
     * 将嵌套的Map结构转换为List集合
     * @param dataMap 包含嵌套Map结构的数据映射，键为String类型，值为Map<String, Object>类型
     * @return 返回包含Map<String, Object>元素的List集合，如果输入为空则返回空列表
     */
    public static List<Map<String, Object>> mapToList(Map<String, Map<String, Object>> dataMap) {
        // 检查输入参数是否为空或空集合
        if (dataMap == null || dataMap.isEmpty()) {
            return Collections.emptyList();
        }

        // 提取所有非空的value值并收集为List
        return dataMap.values().stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    /**
     * 根据唯一编码集合筛选节点列表中的叶子节点
     *
     * @param nodeList 节点列表，用于遍历查找匹配的节点
     * @param uniqueCodeSet 唯一编码集合，用于匹配叶子节点的ID
     * @return 符合条件的叶子节点列表，如果输入参数为空则返回空列表
     */
    public static List<TreeNode> getCheckTreeNodeList(List<TreeNode> nodeList, Set<String> uniqueCodeSet) {
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(uniqueCodeSet) ||
                org.apache.commons.collections4.CollectionUtils.isEmpty(nodeList)) {
            return Collections.emptyList();
        }

        // 使用队列进行广度优先遍历所有节点
        Queue<TreeNode> nodeQueue = new LinkedList<>(nodeList);
        List<TreeNode> checkNodeList = new ArrayList<>();

        while (!nodeQueue.isEmpty()) {
            TreeNode currentNode = nodeQueue.poll();
            List<TreeNode> children = currentNode.getChildren();

            // 如果当前节点有子节点，则将子节点加入队列继续遍历
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(children)) {
                nodeQueue.addAll(children);
                // 如果当前节点是叶子节点且其ID在唯一编码集合中，则加入结果列表
            } else if (uniqueCodeSet.contains(currentNode.getId())) {
                checkNodeList.add(currentNode);
            }
        }

        return checkNodeList;
    }

    /**
     * 获取所有二级组织
     *
     * @return
     */
    public static DynamicObjectCollection getAllSecondOrg() {
        QFilter filter = QFilterCommonHelper.getCurrentVersionFilter();
        filter.and(QFilterCommonHelper.getEnableFilter(true));
        filter.and(QFilterCommonHelper.getDataStatusFilter());
        filter.and("adminorgtype.number", QCP.equals, "1020_S");
        HRBaseServiceHelper helper = new HRBaseServiceHelper("haos_adminorghrf7");
        return helper.queryOriginalCollection("id,name,number", filter.toArray());
    }

    public static DynamicObject getOrgByName (String name) {
        QFilter filter = QFilterCommonHelper.getCurrentVersionFilter();
        filter.and(QFilterCommonHelper.getEnableFilter(true));
        filter.and(QFilterCommonHelper.getDataStatusFilter());
        filter.and("name", QCP.equals,  name);
        HRBaseServiceHelper helper = new HRBaseServiceHelper("haos_adminorghrf7");
        return helper.loadOne(filter.toArray());
    }


}
