package nckd.jimin.jyyy.fi.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import kd.bos.dataentity.RefObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
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.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.util.CollectionUtils;
import kd.fi.er.business.servicehelper.CoreBaseBillServiceHelper;
import kd.fi.er.business.trip.dao.UserDao;
import kd.fi.er.business.trip.exception.TripSyncLogParam;
import kd.fi.er.business.trip.model.TripSyncDataMappingModel;
import kd.fi.er.business.trip.service.function.AbstractUserInvoke;
import kd.fi.er.business.trip.supplier.Supplier;
import kd.fi.er.business.trip.supplier.didi.systemexternal.DiDiOrgAndUserInvokeUtil;
import kd.fi.er.business.trip.supplier.didi.systemexternal.DiDiServiceUtil;
import kd.fi.er.business.trip.util.SyncUserTypeEnum;
import kd.fi.er.business.trip.util.TripCommonUtil;
import kd.fi.er.business.trip.util.TripSyncConfigUtil;
import kd.fi.er.business.trip.util.TripSyncDataMappingUtil;
import kd.fi.er.business.trip.util.UserHelper;
import kd.fi.er.business.utils.ErCommonUtils;
import kd.fi.er.business.utils.ErCostCenterUtil;
import kd.fi.er.business.utils.TripUserGrantUtils;
import kd.fi.er.common.ExternalConstants;
import kd.hrmp.hrpi.business.infrastructure.utils.QFilterUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * 滴滴人员同步，全复制的7.0.8的标准源码后改造
 * @author wanghaiwu_kd
 * @date 2025/06/05
 */
public class DiDiTripUserCusInvoke extends AbstractUserInvoke<Set<JSONObject>> {
    private static Log logger = LogFactory.getLog(DiDiTripUserCusInvoke.class);

    public DiDiTripUserCusInvoke() {
    }

    protected String supplier() {
        return Supplier.DIDI.name();
    }

    protected Object getInnerData() {
        this.bizInfoObject = BusinessDataServiceHelper.loadSingle("er_biz_info", "lastsyncpeopletamp", new QFilter[]{new QFilter("number", "=", this.supplier())});
        this.lastSyncPeopleTamp = this.bizInfoObject.getString("lastsyncpeopletamp");
        return this.queryChangeInfo(this.lastSyncPeopleTamp, 1, 1000000, (Map)null);
    }

    protected Object getInnerData(String changeTime, Integer pageIndex, Integer pageSize, Map<String, Object> map) {
        return this.queryChangeInfo(changeTime, pageIndex, pageSize, map);
    }

    private Map<String, JSONArray> queryChangeInfo(String changeTime, Integer pageIndex, Integer pageSize, Map<String, Object> map) {
        if (map == null) {
            map = new HashMap();
        }

        this.judgeGrant((Map)map);
        QFilter uFilter = new QFilter("server", "=", this.supplier());
        uFilter.and(new QFilter("datatype", "=", "bos_org"));
        Map<Object, Object> dataOrgMappingMap = TripSyncDataMappingUtil.getDataMappingMapByFilter(uFilter, "innerdataid", "outdataid");
        return this.getChangedUserMap(changeTime, pageIndex, pageSize, dataOrgMappingMap, (Map)map);
    }

    private void judgeGrant(Map<String, Object> map) {
        if (map != null) {
            DynamicObjectCollection servers = TripUserGrantUtils.getServers(this.supplier());
            if (CollectionUtils.isNotEmpty(servers)) {
                Object paramValue = map.getOrDefault("didi", "0");
                if (paramValue != null && "1".equals(paramValue.toString())) {
                    DynamicObjectCollection dynamicObjects = TripUserGrantUtils.queryUserGrantInfosByServer(Collections.singletonList(this.supplier()));
                    Set<Long> grantUserNos = (Set)dynamicObjects.stream().map((dynamicObject) -> {
                        return ErCommonUtils.getPk(dynamicObject.get("grantuser"));
                    }).collect(Collectors.toSet());
                    List userList;
                    if (map.containsKey("userList")) {
                        userList = (List)map.get("userList");
                        grantUserNos.retainAll(userList);
                    }

                    if ((null == grantUserNos || grantUserNos.isEmpty()) && map.containsKey("userList")) {
                        userList = (List)map.get("userList");
                        Map<Object, DynamicObject> bosUsers = BusinessDataServiceHelper.loadFromCache("bos_user", "number", new QFilter[]{new QFilter("id", "in", userList)});
                        if (null != bosUsers && !bosUsers.isEmpty()) {
                            Set<String> number = (Set)bosUsers.values().stream().map((v) -> {
                                return v.getString("number");
                            }).collect(Collectors.toSet());
                            this.tripSyncLogParam.setBillno(StringUtils.join(number, ","));
                        }
                    }

                    map.put("userList", grantUserNos == null ? new ArrayList() : new ArrayList(grantUserNos));
                }
            }

        }
    }

    private Map<String, JSONArray> getAllUserInfos(Integer pageIndex, Integer pageSize, Map<Object, Object> dataOrgMappingMap, Map<String, Object> map) {
        List<Map<String, Object>> userObjAlls = UserHelper.getAllUserChangeInfos(pageIndex, pageSize, map);
        userObjAlls = (List)userObjAlls.stream().filter((m) -> {
            return !"4".equals(m.get("type"));
        }).collect(Collectors.toList());
        if (userObjAlls != null && userObjAlls.size() >= 1) {
            Map<String, JSONArray> postUserMap = new HashMap();
            Map<String, String> supplierMap = TripCommonUtil.getTripServiceInfo(this.supplier());
            String client_id = (String)supplierMap.get("appkey");
            String company_id = (String)supplierMap.get("orationid");
            String signKey = (String)supplierMap.get("reservedfield1");
            String access_token = DiDiServiceUtil.getCacheToken(new Date());
            if (access_token == null) {
                this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，获取滴滴Token为空，请检查配置。", "DiDiTripUserInvoke_1", "fi-er-business", new Object[0]));
                this.tripSyncLogParam.setStatus("B");
                return null;
            } else {
                JSONArray addUserList = new JSONArray();
                Map<Long, String> reimburseLevelMap = UserDao.getReimburseLevelNumberNew(userObjAlls);
                Iterator var14 = userObjAlls.iterator();

                while(var14.hasNext()) {
                    Map userObjAll = (Map)var14.next();
                    this.buildAddUserList(userObjAll.get("id"), userObjAll.get("phone"), userObjAll.get("name"), userObjAll.get("number"), userObjAll.get("dptId"), client_id, company_id, access_token, signKey, dataOrgMappingMap, addUserList, reimburseLevelMap, userObjAll.get("supernumber"));
                }

                postUserMap.put("add", addUserList);
                return postUserMap;
            }
        } else {
            SyncUserTypeEnum userTypeEnum = UserHelper.getSyncType(map);
            if (pageIndex == 1 && userTypeEnum != SyncUserTypeEnum.SYNC_BY_USER) {
                this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，全量更新，人员为空,请检查人员信息。", "DiDiTripUserInvoke_0", "fi-er-business", new Object[0]));
            }

            return null;
        }
    }

    private void buildAddUserList(Object userId, Object phone, Object name, Object number, Object dptId, String client_id, String company_id, String access_token, String signKey, Map<Object, Object> dataMappingMap, JSONArray addUserList, Map<Long, String> reimburseLevelMap, Object superNumber) {
        HashMap<String, Object> signMap = new HashMap();
        signMap.put("client_id", client_id);
        signMap.put("company_id", company_id);
        signMap.put("access_token", access_token);
        signMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000L));
        JSONObject userDataJsonObject = new JSONObject();
        userDataJsonObject.put("phone", phone);
        userDataJsonObject.put("realname", name);
        userDataJsonObject.put("employee_number", number);

        //二开逻辑，增加base地
        String baseCity = getBaseCity(number.toString());
        userDataJsonObject.put("residentsname", baseCity);

        int intValue = TripSyncConfigUtil.getIntValue("trip_Superior", 0, Arrays.asList(0, 1));
        if (intValue == 1) {
            userDataJsonObject.put("immediate_superior_employee_number", superNumber == null ? "" : superNumber);
        }

        userDataJsonObject.put("is_remark", 2);
        dataMappingMap.get(dptId);
        this.setBudgetCenterId(dataMappingMap, dptId, userDataJsonObject, userId);
        this.setUserReimburseLevel(userId, reimburseLevelMap, userDataJsonObject, dptId);
        userDataJsonObject.put("use_company_money", this.getUseCompanyMoney());
        setInvoceInfo(dptId, userDataJsonObject);
        signMap.put("data", userDataJsonObject.toString());
        String addUserSign = DiDiServiceUtil.genSign(signMap, signKey);
        JSONObject addUserObj = new JSONObject(signMap);
        addUserObj.put("sign", addUserSign);
        addUserList.add(addUserObj);
    }

    private static void setInvoceInfo(Object dptId, JSONObject userDataJsonObject) {
        Long deptid = Long.parseLong(dptId.toString());
        Long costCompanyId = CoreBaseBillServiceHelper.getAccountOrgId(deptid, true);
        DynamicObject std_costcenter = ErCostCenterUtil.getCostCenterByCostDept(deptid);
        Long companyId = CoreBaseBillServiceHelper.initCompanyByDept(deptid);
        Long stdCostcenterId = 0L;
        if (std_costcenter != null) {
            stdCostcenterId = std_costcenter.getLong("id");
        }

        JSONObject extJson = new JSONObject();
        extJson.put("deptId", dptId);

        //二开逻辑，增加参数【客户部门CODE】
        extJson.put("out_budget_id", dptId);

        if (null != companyId) {
            extJson.put("companyId", companyId);
        }

        extJson.put("costCompanyId", costCompanyId);
        extJson.put("stdCostcenterId", stdCostcenterId);
        extJson.put("taxpayer_subject", costCompanyId);
        userDataJsonObject.put("invoice_info", extJson.toJSONString());
    }

    private void setUserReimburseLevel(Object userId, Map<Long, String> reimburseLevelMap, JSONObject userDataJsonObject, Object dptId) {
        String dtrip_personnel_rank = TripSyncConfigUtil.getTripsyncSettingByKey("dtrip_personnel_rank");
        if (!StringUtils.isEmpty(dtrip_personnel_rank)) {
            String reimbursenumber = (String)reimburseLevelMap.get(Long.parseLong(userId.toString()));
            if (!"0".equals(dtrip_personnel_rank)) {
                Long companyId = CoreBaseBillServiceHelper.initCompanyByDept(Long.parseLong(dptId.toString()));
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingleFromCache("bos_org", "id,name,number", new QFilter[]{new QFilter("id", "in", companyId)});
                switch (dtrip_personnel_rank) {
                    case "1":
                        if (StringUtils.isNotEmpty(reimbursenumber) && dynamicObject != null) {
                            userDataJsonObject.put("out_rank_id", dynamicObject.getString("number") + "-" + reimbursenumber.trim());
                        }
                        break;
                    case "2":
                        if (StringUtils.isNotEmpty(reimbursenumber)) {
                            userDataJsonObject.put("out_rank_id", reimbursenumber.trim());
                        }
                        break;
                    case "3":
                        if (StringUtils.isNotEmpty(reimbursenumber) && dynamicObject != null) {
                            userDataJsonObject.put("out_rank_id", dynamicObject.getString("number") + "-" + reimbursenumber.trim());
                        } else if (dynamicObject != null) {
                            userDataJsonObject.put("out_rank_id", dynamicObject.getString("number") + "-General-01");
                        }
                        break;
                    case "4":
                        if (StringUtils.isNotEmpty(reimbursenumber)) {
                            userDataJsonObject.put("out_rank_id", reimbursenumber.trim());
                        } else {
                            userDataJsonObject.put("out_rank_id", "General-01");
                        }
                        break;
                    case "5":
                        if (StringUtils.isNotEmpty(reimbursenumber) && dynamicObject != null) {
                            userDataJsonObject.put("out_rank_id", dynamicObject.getString("number") + "-" + reimbursenumber.trim());
                        } else {
                            userDataJsonObject.put("out_rank_id", "General-01");
                        }
                }

            }
        }
    }

    private void buildEditUserList(Object userId, Object phone, Object name, Object number, Object dptId, String client_id, String company_id, String access_token, String signKey, Map<Object, Object> dataOrgMappingMap, Map<Object, Object> dataUserMappingMap, JSONArray editUserList, Map<Long, String> reimburseLevelMap, Object superNumber) {
        Object externalNumber = dataUserMappingMap.get(number);
        if (dataUserMappingMap != null && dataUserMappingMap.size() > 0 && externalNumber != null) {
            HashMap<String, Object> signMap = new HashMap();
            signMap.put("client_id", client_id);
            signMap.put("company_id", company_id);
            signMap.put("access_token", access_token);
            signMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000L));
            signMap.put("member_id", dataUserMappingMap.get(number));
            JSONObject userDataJsonObject = new JSONObject();
            userDataJsonObject.put("phone", phone);
            userDataJsonObject.put("is_remark", 2);
            userDataJsonObject.put("realname", name);
            userDataJsonObject.put("employee_number", number);

            //二开逻辑，增加base地
            String baseCity = getBaseCity(number.toString());
            userDataJsonObject.put("residentsname", baseCity);

            int intValue = TripSyncConfigUtil.getIntValue("trip_Superior", 0, Arrays.asList(0, 1));
            if (intValue == 1) {
                userDataJsonObject.put("immediate_superior_employee_number", superNumber == null ? "" : superNumber);
            }

            dataOrgMappingMap.get(dptId);
            this.setBudgetCenterId(dataOrgMappingMap, dptId, userDataJsonObject, userId);
            this.setUserReimburseLevel(userId, reimburseLevelMap, userDataJsonObject, dptId);
            setInvoceInfo(dptId, userDataJsonObject);
            userDataJsonObject.put("use_company_money", this.getUseCompanyMoney());
            signMap.put("data", userDataJsonObject.toString());
            String editUserSign = DiDiServiceUtil.genSign(signMap, signKey);
            JSONObject editUserObj = new JSONObject(signMap);
            editUserObj.put("sign", editUserSign);
            editUserList.add(editUserObj);
        }

    }

    private void buildDelUserList(String client_id, String company_id, String access_token, String signKey, String userIdDelGroup, JSONArray delUserList) {
        HashMap<String, Object> signMap = new HashMap();
        signMap.put("client_id", client_id);
        signMap.put("company_id", company_id);
        signMap.put("access_token", access_token);
        signMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000L));
        signMap.put("member_id", userIdDelGroup);
        String delUserSign = DiDiServiceUtil.genSign(signMap, signKey);
        JSONObject delUserObj = new JSONObject(signMap);
        delUserObj.put("sign", delUserSign);
        delUserList.add(delUserObj);
    }

    private Map<String, JSONArray> getChangedUserMap(String changeTime, Integer pageIndex, Integer pageSize, Map<Object, Object> dataOrgMappingMap, Map<String, Object> map) {
        Date changeDate = TripCommonUtil.convertToDate(changeTime);
        List<Map<String, Object>> userChangeInfos = UserHelper.getUserInfosByTimeNew(pageIndex, pageSize, changeDate, map);
        if (userChangeInfos != null && userChangeInfos.size() >= 1) {
            Map<String, JSONArray> postUserMap = new HashMap();
            Map<String, String> supplierMap = TripCommonUtil.getTripServiceInfo(this.supplier());
            String client_id = (String)supplierMap.get("appkey");
            String company_id = (String)supplierMap.get("orationid");
            String signKey = (String)supplierMap.get("reservedfield1");
            String access_token = "";
            QFilter uFilter = new QFilter("server", "=", this.supplier());
            uFilter.and(new QFilter("datatype", "=", "bos_user"));
            Map<Object, Object> dataUserMappingMap = TripSyncDataMappingUtil.getDataMappingMapByFilter(uFilter, "number", "outdataid");
            JSONArray addUserList = new JSONArray();
            List<Map<String, Object>> tmpUserChangeInfo = (List)userChangeInfos.stream().filter((userChangeObjMap) -> {
                return !dataUserMappingMap.containsKey(userChangeObjMap.get("number"));
            }).collect(Collectors.toList());
            Map<Long, String> reimburseLevelMap = UserDao.getReimburseLevelNumberNew(userChangeInfos);
            tmpUserChangeInfo.stream().filter((userChangeObjMap) -> {
                return (null == userChangeObjMap.get("enable") || !"0".equals(userChangeObjMap.get("enable").toString())) && (null == userChangeObjMap.get("isforbidden") || !"true".equals(userChangeObjMap.get("isforbidden").toString()));
            }).forEach((userChangeObjMap) -> {
                this.buildAddUserList(userChangeObjMap.get("id"), userChangeObjMap.get("phone"), userChangeObjMap.get("name"), userChangeObjMap.get("number"), userChangeObjMap.get("dptId"), client_id, company_id, access_token, signKey, dataOrgMappingMap, addUserList, reimburseLevelMap, userChangeObjMap.get("supernumber"));
            });
            if (CollectionUtils.isNotEmpty(addUserList)) {
                postUserMap.put("add", addUserList);
            }

            List<Map<String, Object>> maxTimeUserChangeInfos = new ArrayList();

            userChangeInfos.stream().collect(Collectors.groupingBy(v -> v.get("id").toString())).forEach((key, valueList) -> {
                maxTimeUserChangeInfos.add(valueList.stream().filter(v -> v.get("modifytime") != null).max(
                        Comparator.comparing(v -> (Date) v.get("modifytime"))).get());
            });

            this.sortList(maxTimeUserChangeInfos);

            JSONArray editUserList = new JSONArray();
            maxTimeUserChangeInfos.stream().filter(userChangeObjMap -> userChangeObjMap.get("number") != null && dataUserMappingMap.containsKey(userChangeObjMap.get("number"))
                    && !((null != userChangeObjMap.get("enable") && "0".equals(userChangeObjMap.get("enable").toString()))
                    || (null != userChangeObjMap.get("isforbidden") && "true".equals(userChangeObjMap.get("isforbidden").toString())))).collect(Collectors.toList()).forEach(userChangeObjMap -> {
                buildEditUserList(userChangeObjMap.get("id"), userChangeObjMap.get("phone"), userChangeObjMap.get("name"), userChangeObjMap.get("number"), userChangeObjMap.get("dptId"),
                        client_id, company_id, access_token, signKey, dataOrgMappingMap, dataUserMappingMap, editUserList, reimburseLevelMap, userChangeObjMap.get("supernumber"));
            });

            if (CollectionUtils.isNotEmpty(editUserList)) {
                postUserMap.put("edit", editUserList);
            }

            DynamicObjectCollection servers = TripUserGrantUtils.getServers(this.supplier());
            if (CollectionUtils.isNotEmpty(servers)) {
                Object paramValue = map == null ? 0 : map.getOrDefault("didi", "0");
                if (paramValue == null || "0".equals(paramValue.toString())) {
                    postUserMap.clear();
                }
            }

            new ArrayList();
            JSONArray delUserList = new JSONArray();
            List<Map<String, Object>> delUserChangeInfos = (List)maxTimeUserChangeInfos.stream().filter((userChangeDO) -> {
                return userChangeDO.get("number") != null && (null != userChangeDO.get("enable") && "0".equals(userChangeDO.get("enable").toString()) || null != userChangeDO.get("isforbidden") && "true".equals(userChangeDO.get("isforbidden").toString()));
            }).collect(Collectors.toList());
            if (delUserChangeInfos.size() > 0) {
                int size = delUserChangeInfos.size() / 100 + 1;
                Map<Integer, List> userMapGroup = new HashMap(size);

                int i;
                for(i = 0; i < size; ++i) {
                    userMapGroup.put(i, new ArrayList(100));
                }

                for(i = 0; i < delUserChangeInfos.size(); ++i) {
                    int index = i / 100;
                    Object number = ((Map)delUserChangeInfos.get(i)).get("number");
                    ((List)userMapGroup.get(index)).add(number);
                }

                for(i = 0; i < userMapGroup.size(); ++i) {
                    List userMapGroupList = (List)userMapGroup.get(i);
                    StringBuilder userIdSb = new StringBuilder();

                    for(int j = 0; j < userMapGroupList.size(); ++j) {
                        String innerNumber = (String)userMapGroupList.get(j);
                        Long outerUserId = (Long)dataUserMappingMap.get(innerNumber);
                        if (outerUserId != null && outerUserId != 0L) {
                            if ("".equals(userIdSb.toString())) {
                                userIdSb = userIdSb.append(outerUserId);
                            } else {
                                userIdSb = userIdSb.append("_").append(outerUserId);
                            }
                        }
                    }

                    if (StringUtils.isNotEmpty(userIdSb.toString())) {
                        this.buildDelUserList(client_id, company_id, access_token, signKey, userIdSb.toString(), delUserList);
                    }
                }

                if (CollectionUtils.isNotEmpty(delUserList)) {
                    postUserMap.put("del", delUserList);
                }
            }

            return postUserMap;
        } else {
            if (pageIndex == 1) {
                this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，差量更新，差量人员为空。", "DiDiTripUserInvoke_2", "fi-er-business", new Object[0]));
            }

            return null;
        }
    }

    protected Object convert(Object info) {
        return info;
    }

    protected String batPushProcess(Object data) {
        Map<String, JSONArray> postUserJSONArrayMap = (Map)data;
        if (postUserJSONArrayMap != null && postUserJSONArrayMap.size() > 0) {
            AtomicReference<Boolean> successflag = new AtomicReference(true);
            List<JSONArray> waitDelData = Lists.newArrayListWithCapacity(1);
            postUserJSONArrayMap.forEach((syncKey, postUserJSONArray) -> {
                String url = "";
                switch (syncKey) {
                    case "add":
                        url = (String)ExternalConstants.DIDIURLMAP.get("memberSingleKey");
                        break;
                    case "edit":
                        url = (String)ExternalConstants.DIDIURLMAP.get("memberEditKey");
                        break;
                    case "del":
                        url = (String)ExternalConstants.DIDIURLMAP.get("memberDelKey");
                }

                if (StringUtils.isNotBlank(url)) {
                    Map<String, String> supplierMap = TripCommonUtil.getTripServiceInfo(this.supplier());
                    String signKey = (String)supplierMap.get("reservedfield1");
                    RefObject<List<TripSyncLogParam>> refObject = new RefObject(new ArrayList(10));
                    List<TripSyncDataMappingModel> dataMappingList = DiDiOrgAndUserInvokeUtil.postChangeData(successflag, syncKey, "bos_user", postUserJSONArray, url, this.supplier(), this.tripSyncLogParam, this.tripSyncLogParamList, signKey, refObject);
                    TripSyncDataMappingUtil.saveTripSyncDataMapping(dataMappingList);
                    if (StringUtils.equals(syncKey, "del")) {
                        waitDelData.add(postUserJSONArray);
                    }

                    ((List)refObject.getValue()).stream().forEach((e) -> {
                        this.addTripSyncLogParam((TripSyncLogParam)e);
                    });
                }

            });
            this.dealWaitDelData(waitDelData);
            String code = "300";
            if ((Boolean)successflag.get()) {
                code = "200";
            }

            return code;
        } else {
            String code = "200";
            if (this.tripSyncLogParam.getStatus().equals("B")) {
                code = "300";
            }

            this.tripSyncLogParam.setMessage(ResManager.loadKDString("商旅集成，差量更新，差量人员为空。", "DiDiTripUserInvoke_2", "fi-er-business", new Object[0]));
            return code;
        }
    }

    protected boolean syncUserByPage() {
        return true;
    }

    private void setBudgetCenterId(Map<Object, Object> dataOrgMappingMap, Object dptId, JSONObject userDataJsonObject, Object userId) {
        if (!dataOrgMappingMap.isEmpty()) {
            int paramValue = TripSyncConfigUtil.getIntValue("budget_center_id", 1);
            Object budgetCenterId = null;
            switch (paramValue) {
                case 0:
                case 2:
                    budgetCenterId = dataOrgMappingMap.get(Long.parseLong(dptId.toString()));
                    break;
                case 1:
                    budgetCenterId = defaultDeal(dataOrgMappingMap, userId, budgetCenterId);
                    break;
                case 3:
                    Long accountOrgId = CoreBaseBillServiceHelper.getAccountOrgId(Long.parseLong(dptId.toString()));
                    if (accountOrgId == null) {
                        defaultDeal(dataOrgMappingMap, userId, budgetCenterId);
                    } else {
                        budgetCenterId = dataOrgMappingMap.get(accountOrgId);
                    }
            }

            userDataJsonObject.put("budget_center_id", budgetCenterId);
        }
    }

    private static Object defaultDeal(Map<Object, Object> dataOrgMappingMap, Object userId, Object budgetCenterId) {
        DynamicObject userInfo = BusinessDataServiceHelper.loadSingle("bos_user", "id,number,entryentity.dpt,entryentity.ispartjob,entryentity.id", new QFilter[]{new QFilter("id", "=", Long.parseLong(userId.toString()))});
        if (userInfo == null) {
            return budgetCenterId;
        } else {
            DynamicObjectCollection entryEntity = userInfo.getDynamicObjectCollection("entryentity");
            int size = entryEntity.size();

            for(int i = 0; i < size; ++i) {
                DynamicObject dynamicObject = (DynamicObject)entryEntity.get(i);
                boolean ispartjob = dynamicObject.getBoolean("ispartjob");
                if (!ispartjob) {
                    Long id = ErCommonUtils.getPk(dynamicObject.get("dpt"));
                    Long companyId = CoreBaseBillServiceHelper.initCompanyByDept(id);
                    budgetCenterId = dataOrgMappingMap.get(companyId);
                }
            }

            return budgetCenterId;
        }
    }

    private Integer getUseCompanyMoney() {
        return TripSyncConfigUtil.getBoolean("dtrip_use_company_money") ? 1 : 0;
    }

    private void sortList(List<Map<String, Object>> maxTimeUserChangeInfos) {
        maxTimeUserChangeInfos.sort(Comparator.comparing((t) -> {
            return String.valueOf(t.get("modifytime"));
        }));
    }

    private void dealWaitDelData(List<JSONArray> waitDelData) {
        if (!CollectionUtils.isEmpty(waitDelData)) {
            JSONArray delJsonArray = (JSONArray)waitDelData.get(0);
            List<String> outIdLists = Lists.newArrayListWithCapacity(16);
            Iterator var4 = delJsonArray.iterator();

            while(var4.hasNext()) {
                Object o = var4.next();
                JSONObject jsonObject = (JSONObject)o;
                String member_id = jsonObject.getString("member_id");
                if (!StringUtils.isEmpty(member_id)) {
                    String[] outIDs = member_id.split("_");
                    outIdLists.addAll((Collection)Arrays.stream(outIDs).collect(Collectors.toList()));
                }
            }

            logger.info("外部数据ID", outIdLists.size());
            QFilter tmpFilter = new QFilter("server", "=", this.supplier());
            tmpFilter.and(new QFilter("datatype", "=", "bos_user"));
            List<Object> numbers = Lists.newArrayListWithCapacity(16);
            Map<Object, Object> dataUserMappingMap = TripSyncDataMappingUtil.getDataMappingMapByFilter(tmpFilter, "outdataid", "number");
            Iterator var15 = outIdLists.iterator();

            while(var15.hasNext()) {
                String outId = (String)var15.next();
                long outIdLong = Long.parseLong(outId);
                if (dataUserMappingMap.containsKey(outIdLong)) {
                    Object number = dataUserMappingMap.get(outIdLong);
                    if (number != null && !StringUtils.isEmpty(number.toString())) {
                        numbers.add(number);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(numbers)) {
                DeleteServiceHelper.delete("er_tripsync_datamapping", new QFilter[]{new QFilter("server", "=", this.supplier()), new QFilter("number", "in", numbers)});
            }
        }
    }

    /**
     * 获取base地，二开方法
     * @param employeeNumber
     * @return
     */
    private String getBaseCity(Object employeeNumber){
        String baseCity = "";

        if (employeeNumber != null) {
            QFilter statusFilter = QFilterUtil.getCurrentQf();
            statusFilter.and(QFilterUtil.getDataStatusFilter());

            QFilter qFilter = new QFilter("number", "=", employeeNumber);
            qFilter.and(statusFilter);

            DynamicObject hrPerson = BusinessDataServiceHelper.loadSingleFromCache("hrpi_person", "id", qFilter.toArray());
            if (hrPerson == null) {
                logger.info("根据员工number未获取到HR人员基本信息{}", employeeNumber);
                return "";
            }
            if(hrPerson != null){
                DynamicObject baseLocation = QueryServiceHelper.queryOne("hrpi_baselocation", "location.city.id", new QFilter[]{
                        new QFilter("person", QCP.equals, hrPerson.getLong("id")),
                        new QFilter("iscurrentversion", QCP.equals, Boolean.TRUE)
                });

                if(baseLocation != null){
                    Long cityId = baseLocation.getLong("location.city.id");
                    DynamicObject admind = QueryServiceHelper.queryOne("bd_admindivision", "name",
                            new QFilter("id", QCP.equals, cityId).toArray());
                    // 查询行政区划名称
                    if(admind != null) {
                        baseCity = admind.getString("name");
                    }
                }
            }
        } else {
            logger.info("未获取到员工{}", employeeNumber);
        }
        return baseCity;
    }
}

