package nckd.jxccl.swc.stm.business;

import kd.bos.common.enums.EnableEnum;
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 kd.bos.servicehelper.QueryServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.ConvertUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;

/**
* 工资总额帮助类
* @author W.Y.C
* @date 2025/12/9 15:54
* @version 1.0
*/
public class StmService {

    /**
     * 统计组织下法人单位数量（含下级及去重统计）
     * @param org 组织
     * @return: int
     * @author W.Y.C
     * @date: 2025/12/09 18:05
     */
    public static int countCorpNum(DynamicObject org){
        DynamicObjectCollection query = corp(org);
        int count = ConvertUtil.toInt(query.stream()
                .mapToLong(obj -> obj.getLong(String.join(".", "corporateorg", FormConstant.ID_KEY)))
                .filter(id -> id > 0)
                .distinct()
                .count());
        return count;
    }

    public static DynamicObjectCollection corp(DynamicObject org){
        DynamicObject adminOrgHr = BusinessDataServiceHelper.loadSingle(FormConstant.ADMINORG_ENTITYID, FormConstant.STRUCTLONGNUMBER, new QFilter[]{QFilterCommonHelper.getIdEqFilter(org.getLong(FormConstant.ID_KEY))});
        QFilter filter = QFilter.like(FormConstant.STRUCTLONGNUMBER, adminOrgHr.getString(FormConstant.STRUCTLONGNUMBER) + "%")
                .and("corporateorg", QCP.is_notnull,null)
                .and(QFilterCommonHelper.getCurrentVersionFilter())
                .and(QFilterCommonHelper.getEnableFilter())
                .and(QFilterCommonHelper.getStatusFilter())
                .and(String.join(".", "corporateorg", FormConstant.ENABLE),QCP.equals, EnableEnum.YES.getCode())
                //包含自己
                .or(FormConstant.ID_KEY,QCP.equals,org.getLong(FormConstant.ID_KEY));
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .addIdNumberName("corporateorg")
                .add(FormConstant.ID_KEY);
        DynamicObjectCollection query = QueryServiceHelper.query(FormConstant.ADMINORG_ENTITYID, queryFieldBuilder.buildSelect(), new QFilter[]{filter});
        return query;
    }
}