package nckd.jimin.jyyy.hr.tsrsc.plugin.util;

import kd.bos.algo.DataSet;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.db.DBRoute;
import kd.bos.entity.plugin.support.util.StringUtils;
import kd.bos.orm.ORM;
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.common.util.HRDBUtil;
import org.apache.commons.lang3.ObjectUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class RecUtils {
    private static String appFile_entity = "tspr_appfile";  //应聘档案/候选人
    private static String arfrsm_entity = "tstpm_srscarfmrsm";   //应聘登记表
    private static String casApply_entity = "nckd_casrecrapply";    //临时招聘申请
    private static String yearApply_entity = "nckd_yearapply";    //年度招聘申请
    private static String applyEntry_entity = "entryentity";    //招聘申请分录标识
    /**
     * 获取组织对应人员编制总数（包含下级）
     * @param orgId 组织ID
     * @return 编制数
     */
    public static int getStaffCount(Object orgId){

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(date);

        // 拼接 SQL 查询 haos_stafforgempcount
        StringBuilder sql2 = new StringBuilder("SELECT DISTINCT T.fstructlongnumber,ST.fcount as count "
                + "FROM T_HAOS_ADMINORG A "
                + "LEFT JOIN T_HAOS_ADMINSTRUCT T ON a.fboid = T.fadminorgid "
                + "left join T_HAOS_STAFFORGEMPCOUNT ST on A.fboid = ST.fuseorgboid "
                + "WHERE A.fiscurrentversion = '0' AND A.fdatastatus = '1' AND A.finitstatus = '2' "
                + "AND T.fiscurrentversion = '0' AND T.fdatastatus = '1' AND T.fstructprojectid = 1010 "
                + "AND T.finitstatus = '2' AND T.fbsed <= '" + dateStr + "' "
                + "AND T.fbsled >= '" + dateStr + "' AND T.fenable = '1' "
                + "AND A.fbsed <= '" + dateStr + "' AND A.fbsled >= '" + dateStr + "' "
                + "AND A.fenable = '1' "
                + "AND ( T.fstructlongnumber LIKE ( select top 1 concat(F.fstructlongnumber,'%')  from  T_HAOS_ADMINSTRUCT F where  F.fadminorgid = ? "
                + "AND F.fiscurrentversion = '0' AND F.fdatastatus = '1' AND F.fstructprojectid = 1010 "
                + "AND F.finitstatus = '2' AND F.fbsed <= '" + dateStr + "' "
                + "AND F.fbsled >= '" + dateStr + "' AND F.fenable = '1' "
                +") " +") "
        );

        Object[] param = new Object[]{(Long) orgId};
//        DataSet dataSet = HRDBUtil.queryDataSet("haos_adminOrgHisSearch", new DBRoute("hr"), sql.toString(), param);
        DataSet dataSet = HRDBUtil.queryDataSet("haos_adminOrgHisSearch", new DBRoute("hr"), sql2.toString(), param);

        ORM orm = ORM.create();
        DynamicObjectCollection retDynCol = orm.toPlainDynamicObjectCollection(dataSet);
        // 获取实际人数
        AtomicInteger nckdRellownum2 = new AtomicInteger(0);
        retDynCol.forEach(dynObj -> {
            if(ObjectUtils.isNotEmpty(dynObj.getInt("count"))){
                nckdRellownum2.addAndGet(dynObj.getInt("count"));
            }
        });
        return nckdRellownum2.get();
    }

    /**
     * 根据候选人管理ID 获取 临时/年度招聘申请分录的招聘部门、岗位和招聘需求负责人
     * @param appFileId
     * @return
     */
    public static DynamicObject getCasApplyEntryDyn (Long appFileId) {
        //先查询候选人档案
        DynamicObject appFile = BusinessDataServiceHelper.loadSingle(appFileId, appFile_entity);
        //获取应聘登记表ID
        Long arfRsmId = appFile.getLong("arfrsm.id");
        arfrsm_entity = "tstpm_srscarfmrsm";
        DynamicObject arfRsm = BusinessDataServiceHelper.loadSingle(arfRsmId, arfrsm_entity);
        String applyEntryId = arfRsm.getString("nckd_mokahcnum");
        if(StringUtils.isEmpty(applyEntryId))
            return null;
        QFilter filter = new QFilter(applyEntry_entity + ".id", QCP.equals, Long.valueOf(applyEntryId));
        String selectFields = "nckd_person.id,entryentity.nckd_recruitorg.id,entryentity.nckd_recruitpost.id";
        QFilter[] filters = new QFilter[]{filter};
        if(QueryServiceHelper.exists(casApply_entity, filters)) {
            return QueryServiceHelper.queryOne(casApply_entity, selectFields, filters);
        }
        else if(QueryServiceHelper.exists(yearApply_entity, filters)) {
            return QueryServiceHelper.queryOne(yearApply_entity, selectFields, filters);
        }
        else {
            return null;
        }
    }



}
