package com.kingdee.eas.custom.recuritment.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitFactory;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.IAdminOrgUnit;
import com.kingdee.eas.basedata.person.IPerson;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.beisen.utils.BeisenApiClient;
import com.kingdee.eas.custom.beisen.utils.BeisenParam;
import com.kingdee.eas.custom.recuritment.bizEnum.ExecuteResultEnum;
import com.kingdee.eas.hr.base.HRBillStateEnum;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.recuritment.*;
import com.kingdee.shr.recuritment.app.util.db.RecDBUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 招聘需求推送服务（谷医堂sHR招聘需求）
 */
public class RecruitmentDemandService {

    private static final Logger logger = Logger.getLogger(RecruitmentDemandService.class);

    /**
     * 是否为生产环境
     */
    private static boolean isProductionEnv = true ;
    // 常量定义
    private static final int REQUIREMENT_STATUS_IN_PROGRESS = 40;
    private static final int SHARE_TYPE_SUBORDINATE = 2;
    private static final int REQUIREMENT_TYPE_NEW = 1;
    private static final int REQUIREMENT_TYPE_SUPPLY  = 4;
    // 值映射关系
    private static final Map<String, Integer> REQUIREMENT_TYPE_MAP = createRequirementTypeMap();
    private static final Map<String, Integer> CATEGORY_MAP = createCategoryMap();
    private static final Map<String, Integer> KIND_MAP = createKindMap();
    private static final Map<String, String> HEADCOUNT_TYPE_MAP = createHeadcountTypeMap();
    private static final Map<String, String> YES_NO_MAP = createYesNoMap();
    private static final Map<String, String> TRAIN_PERIOD_MAP = createTrainPeriodMap();
    private static final Map<String, String> FORMAL_CUSTOM_FIELDS = createFormalCustomFields();
    private static final Map<String, String> TEST_CUSTOM_FIELDS = createTestCustomFields();
    //招聘类型
    private static final Map<String, Integer> RECRUITMENTTYPE_MAP = createRecruitmentType();
    
//    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    // 缓存工号到用户ID的映射（避免重复查询）
    private static final Map<String, Integer> jobNumberToUserIdCache = new ConcurrentHashMap<>();

    private static final Map<String, Integer> STATUS_MAPPING = new HashMap<>();
    static {
        // 初始化映射关系 (billState/DliState, flowState) -> 需求状态值
        STATUS_MAPPING.put(key(3, 0), 40);  // 进行中
        STATUS_MAPPING.put(key(3, 1), 60);  // 已完成
        STATUS_MAPPING.put(key(3, 2), 50);  // 已关闭
        STATUS_MAPPING.put(key(0, 3), 10);  // 未提交
        STATUS_MAPPING.put(key(1, 0), 20);  // 审批中
        STATUS_MAPPING.put(key(2, 0), 20);  // 审批中
    }

    // 辅助方法：生成组合键
    private static String key(int state1, int state2) {
        return state1 + "|" + state2;
    }

    /**
     * 映射 shr 的 billState 和 flowState 到需求状态
     * @param billState billState值
     * @param flowState flowState值
     * @return 需求状态值，未匹配时返回null
     */
    public static Integer mapShrToStatus(int billState, int flowState) {
        return STATUS_MAPPING.get(key(billState, flowState));
    }


    public RecruitmentDemandService(  boolean isProductionEnv) {
        this.isProductionEnv = isProductionEnv;
    }

    // 初始化映射关系的方法
    private static Map<String, Integer> createRequirementTypeMap() {
        Map<String, Integer> map = new HashMap<>();
        map.put("002", REQUIREMENT_TYPE_SUPPLY);  // 新增编制 ->  缺编补充
        map.put("001", REQUIREMENT_TYPE_NEW);  // 缺编补充 -> 新增
        return Collections.unmodifiableMap(map);
    }

    private static Map<String, Integer> createCategoryMap() {
        Map<String, Integer> map = new HashMap<>();
        map.put("001", 1);  // 社会招聘
        map.put("002", 2);  // 校园招聘
        map.put("006", 3);  // 实习生招聘
        return Collections.unmodifiableMap(map);
    }

    private static Map<String, Integer> createKindMap() {
        Map<String, Integer> map = new HashMap<>();
        map.put("1", 1);  // 全职
        map.put("2", 2);  // 兼职
        map.put("0", 4);  // 不限 -> 其他
        return Collections.unmodifiableMap(map);
    }

    private static Map<String, String> createHeadcountTypeMap() {
        Map<String, String> map = new HashMap<>();
        map.put("0", "0");  // 薪酬包预算内招聘申请
        map.put("1", "1");  // 编制外招聘申请
        map.put("2", "2");  // 薪酬包预算外招聘申请
        return Collections.unmodifiableMap(map);
    }

    private static Map<String, String> createYesNoMap() {
        Map<String, String> map = new HashMap<>();
        map.put("是", "是");
        map.put("否", "否");
        return Collections.unmodifiableMap(map);
    }

    private static Map<String, String> createTrainPeriodMap() {
        Map<String, String> map = new HashMap<>();
        map.put("three", "3月");
        map.put("six", "6月");
        map.put("twelve", "12月");
        return Collections.unmodifiableMap(map);
    }
    
    //招聘类型
    private static Map<String, Integer> createRecruitmentType() {
          Map<String, Integer> map = new HashMap<>();
             // 初始化映射关系
          map.put("001", 1); // 社会招聘
          map.put("002", 2); // 校园招聘
          map.put("006", 3); // 实习生招聘
          map.put("003", 4); // 内部推荐
          map.put("004", 5); // 内部竞聘
          map.put("005", 6); // 猎头招聘
          map.put("007", 7); // 外包(派遣)
          map.put("008", 8); // 管培生
          return Collections.unmodifiableMap(map);
      }

    
    private static Map<String, String> createFormalCustomFields() {
        Map<String, String> map = new HashMap<>();
        map.put("招聘职位", "extzhaopinzhiwei_614492_675953134");
        map.put("招聘业务组织", "extzhaopinyewuzuzhi_614492_625299195");
        map.put("招聘申请类型", "extzhaopinshenqingleixing_614492_1996095690");
        map.put("组织层级", "extzhaopinbumencengji_614492_28373535");
        map.put("是否营销类", "extshifouyingxiaolei_614492_686667835");
        map.put("工资待遇", "extgongzidaiyu_614492_1581268897");
        map.put("福利待遇", "extfulidaiyu_614492_1723263995");
        map.put("备注", "extbeizhu_614492_449117520");
        map.put("培养周期", "extpeiyangzhouqi_614492_13124793");
        map.put("是否需轮岗", "extshifouxulungang_614492_1020570825");
        map.put("轮岗岗位", "extlunganggangwei_614492_1371281235");
        map.put("定岗岗位", "extdingganggangwei_614492_1002839243");
        map.put("转正考核标准", "extzhuanzhengkaohebiaozhun_614492_1527148155");
        map.put("办公地点", "extbangongdidian_614492_920550595");
        map.put("招聘类型", "extzhaopinqudao_614492_409009478");
        
        return Collections.unmodifiableMap(map);
    }

    private static Map<String, String> createTestCustomFields() {
        Map<String, String> map = new HashMap<>();
        map.put("招聘职位", "extzhaopinzhiwei_433899_675953134");
        map.put("招聘业务组织", "extzhaopinyewuzuzhi_433899_625299195");
        map.put("招聘申请类型", "extzhaopinshenqingleixing_433899_1996095690");
        map.put("组织层级", "extzhaopinbumencengji_433899_28373535");
        map.put("是否营销类", "extshifouyingxiaolei_433899_686667835");
        map.put("工资待遇", "extgongzidaiyu_433899_1581268897");
        map.put("福利待遇", "extfulidaiyu_433899_1723263995");
        map.put("备注", "extbeizhu_433899_449117520");
        map.put("培养周期", "extpeiyangzhouqi_433899_13124793");
        map.put("是否需轮岗", "extshifouxulungang_433899_1020570825");
        map.put("轮岗岗位", "extlunganggangwei_433899_1371281235");
        map.put("定岗岗位", "extdingganggangwei_433899_1002839243");
        map.put("转正考核标准", "extzhuanzhengkaohebiaozhun_433899_1527148155");
        map.put("办公地点", "extbangongdidian_433899_920550595");
        map.put("招聘类型", "extzhaopinqudao_433899_409009478");
        
        return Collections.unmodifiableMap(map);
    }



   

    /**
     * 构建需求数据公共部分
     * @throws BOSException 
     * @throws EASBizException 
     */
    private JSONObject buildRequirementData(Context ctx, RecuritmentDemandInfo demandInfo) throws BOSException, EASBizException {
        JSONObject params = new JSONObject();
 
        // 需求类型映射
        RecPersonType recPersonType = demandInfo.getRecPersonType();
        if (recPersonType != null && StringUtils.isNotBlank(recPersonType.getValue())) {
            Integer mappedType = REQUIREMENT_TYPE_MAP.get(recPersonType.getValue());
            params.put("requirementType", mappedType != null ? mappedType : REQUIREMENT_TYPE_NEW);
//            //test  
//            params.put("requirementType", 1);
        }

        // 基本字段映射
        params.put("name", demandInfo.getPositionName());
        params.put("requirementCount", demandInfo.getRecuritNumber());
        params.put("jobDescription", demandInfo.getResponsibilities());
        params.put("qualification", demandInfo.getQualification());
        
        AdminOrgUnitInfo department = demandInfo.getDepartment();
        if(null!= department) {
        	IAdminOrgUnit orgIns = AdminOrgUnitFactory.getLocalInstance(ctx);
        	department = orgIns.getAdminOrgUnitInfo(new ObjectUuidPK(department.getId().toString()));
        	params.put("orgCode", department.getNumber());
//            params.put("orgName", department.getName());
//            //test
//            params.put("departmentId", 0);
        }
        
        // 日期字段
        Date applyDate = demandInfo.getApplyDate();
        if (applyDate != null) {
            SimpleDateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            params.put("createDate", dfmt.format(applyDate));
        }
        
        Date arrivalDate = demandInfo.getArrivalDate();
        if (arrivalDate != null) {
            SimpleDateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            params.put("arivalTime", dfmt.format(arrivalDate));
        }

        // 值映射字段
        mapValueIfPresent(CATEGORY_MAP, demandInfo.getRecuritmentType(), "category", params);
        mapEnumValue(KIND_MAP, demandInfo.getJobNature(), "kind", params);

        // 申请人转换
        PersonInfo proposer = demandInfo.getProposer();
        if (proposer != null ) {
            IPerson pIns = PersonFactory.getLocalInstance(ctx);
            proposer = pIns.getPersonInfo(new ObjectUuidPK(proposer.getId().toString()));
            Integer beisenUserId = convertToBeisenUserId(proposer.getNumber());
            //test 1038350
//            Integer beisenUserId = convertToBeisenUserId("1038350");
            if (beisenUserId != null) {
                params.put("createBy", beisenUserId);
                params.put("dutyUser", beisenUserId);
            }
        }

        HRBillStateEnum billState = demandInfo.getBillState();
        FlowStateEnum flowState = demandInfo.getFlowState();
        Integer rStatus = mapShrToStatus(billState.getValue(), flowState.getValue());
        params.put("requirementStatus", rStatus);
        // 处理自定义字段
        addCustomFields(  ctx, params, demandInfo);
        
        return params;
    }

    /**
     * 添加自定义字段
     * @throws BOSException 
     * @throws EASBizException 
     */
    private void addCustomFields(Context ctx, JSONObject params, RecuritmentDemandInfo demandInfo) throws BOSException, EASBizException {
        // 招聘职位
        addCustomField(params, "招聘职位", demandInfo.getRecuritPosition().getName());
        
        // 招聘业务组织
        addCustomField(params, "招聘业务组织", demandInfo.getHrOrgUnit().getName());
        
        // 其他自定义字段
     // 招聘申请类型 (headcountType -> 自定义字段)
        String headcountType = Optional.ofNullable(demandInfo.get("headcountType"))
                .map(Object::toString) // 任何类型安全转String
                .orElse("");
        addCustomField(params, "招聘申请类型", mapHeadcountType(headcountType));
        addCustomField(params, "组织层级", String.valueOf(demandInfo.getDepartment().getLevel()));
        addCustomField(params, "是否营销类", mapYesNo(getPropertyValue(demandInfo, "isMarketing")));
        SalaryEnum salary = demandInfo.getSalary();
        if(null!= salary) {
        	String alias = salary.getAlias();
        	addCustomField(params, "工资待遇", alias);
        }
        addCustomField(params, "福利待遇", getBenefits(demandInfo));
        addCustomField(params, "备注", demandInfo.getRecRema());
        
        // 培养周期特殊处理
        String trainPeriod = Optional.ofNullable(getPropertyValue(demandInfo, "trainPeriod"))
                .map(Object::toString)
                .map(key -> TRAIN_PERIOD_MAP.getOrDefault(key, ""))
                .orElse("");
        addCustomField(params, "培养周期", trainPeriod);
        
        // 其他字段
        addCustomField(params, "是否需轮岗", mapYesNo(getPropertyValue(demandInfo, "needJobRotation")));
        addCustomField(params, "轮岗岗位", getPropertyAsString(demandInfo, "rotationPosition"));
        addCustomField(params, "定岗岗位", getPropertyAsString(demandInfo, "fixedPosition"));
        addCustomField(params, "转正考核标准", getPropertyAsString(demandInfo, "regularizationStandard"));
        addCustomField(params, "办公地点", getPropertyAsString(demandInfo, "workPlace"));
        
        //
//        if( null != demandInfo.get("demandCompType")) {
//        	   DemandCompTypeInfo demandCompType = (DemandCompTypeInfo) demandInfo.get("demandCompType");
//               addCustomField(params, "招聘类型", demandCompType.getRecTypeName() );
//        }
        DemandCompTypeCollection demandCompType = demandInfo.getDemandCompType();
        if(null != demandCompType && demandCompType.size() > 0) {
        	DemandCompTypeInfo demandCompTypeInfo = demandCompType.get(0);
        	RecType4BaseItemInfo recType = demandCompTypeInfo.getRecType();
        	if( null != recType ) {
        		IRecType4BaseItem retTypeIns = RecType4BaseItemFactory.getLocalInstance(ctx);
        		recType = retTypeIns.getRecType4BaseItemInfo( new ObjectUuidPK(recType.getId().toString()));
        		String number = recType.getNumber();
        		Integer  val = RECRUITMENTTYPE_MAP.get(number);
        		addCustomField(params, "招聘类型", val );
        	}
        }
    }

    /**
     * 创建招聘需求
     * @throws BOSException
     * @throws EASBizException
     */
    public String createRequirement(Context ctx, RecuritmentDemandInfo demandInfo,JSONObject requirementData) throws IOException, EASBizException, BOSException {
        JSONObject response = new JSONObject();
        try {
            response = BeisenApiClient.getInstance().callApi(BeisenParam.CREATE_REQUIREMENT_URL, requirementData);
            handleApiResponse(ctx,response,demandInfo , "");
        }catch (Exception e) {
            handleApiResponse(ctx,response,demandInfo , "");
            logger.error("创建招聘需求时发生错误", e);
        }

        return response.getString("data");
    }

    /**
     * 推送招聘需求到北森系统
     * @param demandInfo sHR系统的招聘需求数据
     * @return 北森系统返回的需求ID
     */
    public String createRecruitmentDemand(Context ctx, RecuritmentDemandInfo demandInfo) throws Exception {
        JSONObject params = buildRequirementData(  ctx, demandInfo);
          // 需求状态固定为40(进行中)
        params.put("shareType", SHARE_TYPE_SUBORDINATE);          // 共享方式固定为2(共享给下级)
        return createRequirement( ctx, demandInfo,params);
    }
    
    
    public void updateRequirement(Context ctx, String requirementId, RecuritmentDemandInfo demandInfo) throws BOSException, EASBizException {
        JSONObject params = buildRequirementData(  ctx, demandInfo);
        params.put("requirementId", requirementId);
//        params.put("requirementStatus", REQUIREMENT_STATUS_IN_PROGRESS); // 进行中
        JSONObject response = new JSONObject();
        try {
            BeisenApiClient apiClient = BeisenApiClient.getInstance();
            response = apiClient.callPutApi(BeisenParam.UPDATE_REQUIREMENT_URL, params);
            handleApiResponse(ctx,response,demandInfo , requirementId);
        } catch (Exception e) {
            handleApiResponse(ctx,response,demandInfo , requirementId);
            logger.error("更新招聘需求时发生错误", e);
        }
    }

    /**
     * 处理API响应
     * @throws BOSException 
     * @throws EASBizException 
     */
    private void handleApiResponse(Context ctx, JSONObject response, RecuritmentDemandInfo demandInfo ,String requirementId) throws BOSException, EASBizException {
        //如果不包含code字段，则认为是错误的响应
        int code = 500;
        if (response.containsKey("code")) {
            code = response.getIntValue("code");
        }
        String message =  "发生调用错误,请查看后台日志!";
       if (response.containsKey("message")) {
           message = response.getString("message");
       }
        SelectorItemCollection selectorCol = new SelectorItemCollection();
        selectorCol.add(new  SelectorItemInfo("requirementId"));
        selectorCol.add(new  SelectorItemInfo("syncBeisenResult"));
        selectorCol.add(new  SelectorItemInfo("syncStatus"));
        if (code == 200) {
        	if(!StringUtils.isEmpty(requirementId)) {
        		demandInfo.put("requirementId", requirementId);
        	}else {
        		demandInfo.put("requirementId", response.getString("data"));
        	}
        	demandInfo.put("syncStatus", ExecuteResultEnum.SUCCESS_VALUE);
        	demandInfo.put("syncBeisenResult", "成功: " + message);
            logger.info( "成功: " + message);
        } else {
        	logger.error("失败: " + message + " (code: " + code + ")");
        	demandInfo.put("syncStatus", ExecuteResultEnum.ERROR_VALUE);
        	demandInfo.put("syncBeisenResult", "失败: " + message + " (code: " + code + ")");
        }
        IRecuritmentDemand demandIns = RecuritmentDemandFactory.getLocalInstance(ctx);
    	demandIns.updatePartial(demandInfo, selectorCol);
    }

    /**
     * 获取属性值
     */
    private Object getPropertyValue(RecuritmentDemandInfo demandInfo, String property) {
        return demandInfo.get(property);
    }
    
    /**
     * 获取属性字符串值
     */
    private String getPropertyAsString(RecuritmentDemandInfo demandInfo, String property) {
        return Optional.ofNullable(getPropertyValue(demandInfo, property))
                .map(Object::toString)
                .orElse("");
    }

    /**
     * 映射值如果存在
     */
    private void mapValueIfPresent(Map<String, Integer> valueMap, String sourceValue, String targetKey, JSONObject params) {
        if (StringUtils.isNotBlank(sourceValue)) {
            Integer mappedValue = valueMap.get(sourceValue);
            if (mappedValue != null) {
                params.put(targetKey, mappedValue);
            }
        }
    }

    /**
     * 映射枚举值
     */
    private void mapEnumValue(Map<String, Integer> valueMap, JobNatureEnum sourceEnum, String targetKey, JSONObject params) {
        if (sourceEnum != null) {
            Integer mappedValue = valueMap.get(sourceEnum.getValue());
            if (mappedValue != null) {
                params.put(targetKey, mappedValue);
            }
        }
    }

    /**
     * 推送福利待遇
     */
    public String getBenefits(RecuritmentDemandInfo demandInfo) {
        String sql = "SELECT BENEFITS.FName FROM T_REC_Benefits BENEFITS " +
                     "JOIN T_REC_RecDemandLinkBenefits LINK01 ON (BENEFITS.FID = LINK01.FBenefitsID) " +
                     "WHERE BENEFITS.FState = 1 AND LINK01.FDemandID = ?";
        
        StringBuilder value = new StringBuilder();
        try {
            List<Object[]> datas = RecDBUtils.getQueryData(SHRContext.getInstance().getContext(), sql, 
                    new Object[]{demandInfo.getId().toString()});
            
            if (CollectionUtils.isNotEmpty(datas)) {
                for (Object[] objects : datas) {
                    if (objects.length > 0) {
                        value.append(String.valueOf(objects[0]));
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取福利待遇异常", e);
        }
        return value.toString();
    }

    /**
     * 添加自定义字段
     */
    private void addCustomField(JSONObject params, String fieldName, String value) {
        if (StringUtils.isNotBlank(value)) {
            String fieldCode = getCustomFieldCode(fieldName);
            if (fieldCode != null) {
                params.put(fieldCode, value);
            }
        }
    }
    
    /**
     * 添加自定义字段_integer
     */
    private void addCustomField(JSONObject params, String fieldName, Integer value) {
        if (null != value) {
            String fieldCode = getCustomFieldCode(fieldName);
            if (fieldCode != null) {
                params.put(fieldCode, value);
            }
        }
    }

    /**
     * 获取自定义字段编码
     */
    private String getCustomFieldCode(String fieldName) {
        Map<String, String> fieldMap = isProductionEnv ? FORMAL_CUSTOM_FIELDS : TEST_CUSTOM_FIELDS;
        return fieldMap.get(fieldName);
    }

    /**
     * 映射招聘申请类型
     */
    private String mapHeadcountType(String headcountType) {
        return StringUtils.isNotBlank(headcountType) ? 
                HEADCOUNT_TYPE_MAP.getOrDefault(headcountType, headcountType) : 
                null;
    }

    /**
     * 映射是否类型
     */
    private String mapYesNo(Object value) {
        if (ObjectUtils.isNotEmpty(value)) {
            String strValue = value.toString();
            return YES_NO_MAP.getOrDefault(strValue, strValue);
        }
        return YES_NO_MAP.get("否");
    }

//    /**
//     * 将sHR用户标识转换为北森用户ID
//     */
//    private Integer convertToBeisenUserId(String shrUserIdentifier) {
//        // 实际实现应根据业务逻辑查询映射关系
//        return 407802551; // 示例ID
//    }



    /**
     * 批量获取北森用户ID
     * @param jobNumbers 员工工号集合
     * @return 工号到用户ID的映射
     * @throws IOException
     */
    public Map<String, Integer> getUserIdsByJobNumbers(Set<String> jobNumbers) throws IOException {
        // 检查输入
        if (jobNumbers == null || jobNumbers.isEmpty()) {
            return Collections.emptyMap();
        }

        // 分离已缓存和未缓存的工号
        Map<String, Integer> result = new HashMap<>();
        List<String> needQuery = new ArrayList<>();

        for (String jobNumber : jobNumbers) {
            if (jobNumberToUserIdCache.containsKey(jobNumber)) {
                result.put(jobNumber, jobNumberToUserIdCache.get(jobNumber));
            } else {
                needQuery.add(jobNumber);
            }
        }

        // 分批查询（每次最多30个）
        int batchSize = 30;
        for (int i = 0; i < needQuery.size(); i += batchSize) {
            int end = Math.min(i + batchSize, needQuery.size());
            List<String> batch = needQuery.subList(i, end);
            JSONObject requestData = new JSONObject();
            requestData.put("jobNumbers", batch);
            JSONObject response = BeisenApiClient.getInstance().callApi(
                    BeisenParam.GET_USERID_BY_JOBNUMBER_URL, requestData);

            // 处理响应
            if ("200".equals(response.getString("code"))) {
                JSONArray data = response.getJSONArray("data");
                if (data != null) {
                    for (int j = 0; j < data.size(); j++) {
                        JSONObject item = data.getJSONObject(j);
                        String jobNum = item.getString("jobNumber");
                        Integer userId = item.getInteger("userId");

                        // 只缓存有效结果
                        if (jobNum != null && userId != null && userId > 0) {
                            jobNumberToUserIdCache.put(jobNum, userId);
                            result.put(jobNum, userId);
                        }
                    }
                }
            } else {
                logger.error("批量获取用户ID失败: " + response.getString("message"));
            }
        }

        return result;
    }

    /**
     * 将sHR用户标识转换为北森用户ID
     */
    private Integer convertToBeisenUserId(String jobNumber) {
        if (StringUtils.isBlank(jobNumber)) {
            return null;
        }

        // 先尝试从缓存获取
        if (jobNumberToUserIdCache.containsKey(jobNumber)) {
            return jobNumberToUserIdCache.get(jobNumber);
        }

        // 批量查询（即使只有一个也走批量接口）
        try {
            Set<String> jobNumbers = Collections.singleton(jobNumber);
            Map<String, Integer> mapping = getUserIdsByJobNumbers(jobNumbers);
            return mapping.get(jobNumber);
        } catch (IOException e) {
            logger.error("转换工号到北森用户ID时发生错误，工号: " + jobNumber, e);
            return null;
        }
    }

}