package com.gtiit.shr.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gtiit.shr.common.Result;
import com.gtiit.shr.entity.enums.TaskNameEnum;
import com.gtiit.shr.entity.enums.TaskStatusEnum;
import com.gtiit.shr.entity.enums.TypeEnum;
import com.gtiit.shr.entity.vo.ExceptionRequestVo;
import com.gtiit.shr.service.ExceptionService;
import com.gtiit.shr.service.NewSynOrgPosPerService;
import com.gtiit.shr.utils.FinalParamUtil;
import com.gtiit.shr.utils.NewOaApiUtil;
import com.kingdee.shr.api.Response;
import com.kingdee.shr.api.SHRClient;
import com.kingdee.shr.api.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author ramon.wang
 * @date Created in 17/07/2025 16:59
 * @description shr同步组织岗位人员到oa系统业务实现类
 */
@Service
@Transactional
public class NewSynOrgPosPerServiceImpl implements NewSynOrgPosPerService {

    @Autowired
    private FinalParamUtil finalParamUtil;

    @Autowired
    private NewOaApiUtil newOaApiUtil;

    @Autowired
    ExceptionService exceptionService;

    Token token = null;

    @Value("${scheduled.org.new.able}")
    private String deptcronStatus;

    @Value("${scheduled.position.new.able}")
    private String positioncronStatus;

    @Value("${scheduled.person.new.able}")
    private String cronStatus;

    private static String shrurl = "https://gtiit.kdeascloud.com/shr";

    private static Map<String, String> statusmap = new HashMap<>();

    static {
//        '{"On Probation":"试用","Employee":"正式","Permanent Employee":"正式","Temporary Worker":"临时",
//        "试用延期":"试用延期","Dismiss":"解聘","Termination":"解聘","Dimission":"离职","Resignation":"离职","Retirement":"退休","无效":"无效"}'
        //key为shr，value为oa
        statusmap.put("On Probation", "1");
        statusmap.put("试用延期", "2");
        statusmap.put("Employee", "3");
        statusmap.put("Permanent Employee", "3");
        statusmap.put("Temporary Worker", "4");
        statusmap.put("Labor Dispatching","4");
        statusmap.put("Practice","5");
        statusmap.put("Dimission", "6");
        statusmap.put("Resignation", "6");
        statusmap.put("Dismiss","6");
        statusmap.put("Termination","6");
        statusmap.put("Retirement with Honors","6");
        statusmap.put("Fired","6");
        statusmap.put("Retirement", "7");
    }


    @Scheduled(
            cron = "${scheduled.org.cron}"
    )
    @Transactional
    public void SynOrg() throws Exception {
        //TODO 这里记得要删除旧接口的定时同步任务，把旧定时任务设置为禁用
        if (TaskStatusEnum.ABLE.getValue().equals(this.deptcronStatus)) {
            String var1 = FinalParamUtil.getBeforeOneDay(new Date());
            this.synOrgToType(var1, FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    @Override
    public Result SynOrg(String startTime, String endTime) throws Exception {
        return this.synOrgToType(startTime, endTime, TypeEnum.MANUAL.getValue());
    }

    private Result synOrgToType(String startTime, String endTime, String type) throws Exception {
        SHRClient sHRClient = new SHRClient();
        //TODO 这里先把shr生产环境数据同步到oa测试环境。为了不影响同步程序生产环境的日志等配置，这里不能在application.yml中spring.profiles.active:uat改为prod。所以先写死生产shr的url
        this.token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
//        this.token = sHRClient.loginShrByUser(shrurl);
        Result result = new Result();
        result.setCode(1);
        JSONArray jsonAdmArr = null;
        Map<String, String> param = new HashMap();
        param.put("startDate", startTime);
        param.put("endDate", endTime);

        try {
            jsonAdmArr = JSONObject.parseArray(this.getOSFData(this.finalParamUtil.getInteOAGetAdminOrgDataService(), param).getData().toString());
        } catch (Exception var31) {
            return new Result(false, 0, "SHR系统请求报错，报错信息为--new：" + var31.getMessage());
        }

        Map<String, Object> mapBody = new HashMap();
        ArrayList<Map<String, String>> dataList = new ArrayList();
        Map<String, Object> paramMap = new HashMap();
        //shr返回的组织数据不为空
        if (jsonAdmArr != null && jsonAdmArr.size() > 0) {
            for (int i = 0; i < jsonAdmArr.size(); ++i) {
                JSONObject jsonObject = JSONObject.parseObject(jsonAdmArr.get(i).toString());
                String shortname = jsonObject.getString("simpleName");
                if (StrUtil.isEmpty(shortname)) {
                    shortname = jsonObject.getString("name");
                }

                HashMap mpBody = new HashMap();
                mpBody.put("name", shortname);
                mpBody.put("code", jsonObject.getString("fnumber"));
//            mpBody.put("fullname", jsonObject.getString("name"));
                //其中 7 表示中文，8 表示英文
                JSONObject fullname = new JSONObject();
                fullname.put("7", jsonObject.getString("name"));
                fullname.put("8", jsonObject.getString("name_L1"));
                JSONObject multiObj = new JSONObject();
                multiObj.put("fullname", fullname);
                mpBody.put("multiObj", multiObj);

                mpBody.put("parent", jsonObject.getString("supFnumber"));
                mpBody.put("description", jsonObject.getString("name_L1"));

                //组装自定义的部门负责人和部门分管领导
                JSONObject result1 = new JSONObject();
                result1.put("bmfzr", jsonObject.getString("pnumber") == null ? "" : jsonObject.getString("pnumber"));
                result1.put("bmfgld", jsonObject.getString("pvc_number") == null ? "" : jsonObject.getString("pvc_number"));
                mpBody.put("departmentExtend", result1);

                dataList.add(mpBody);
                paramMap.put(jsonObject.getString("fnumber"), mpBody);
            }

            if (dataList.size() == 0) {
                return new Result(false, 0, "当前时间范围内未找到组织的变动记录--new");
            } else {
                mapBody.put("data", dataList);
                Map<String, String> dataRuleMap = new HashMap();
                dataRuleMap.put("department", "code");
                dataRuleMap.put("employee", "job_num");
                mapBody.put("dataRule", dataRuleMap);
                String sendAPIByAddAdmin = "";

                try {
                    sendAPIByAddAdmin = this.newOaApiUtil.restful("/papi/openapi/api/hrm/restful/syncDepartment", mapBody, "sendAPIByAddAdmin");
                } catch (Exception var30) {
                    return new Result(false, 0, "OA系统请求报错，报错信息为--new：" + var30.getMessage());
                }

                System.out.println("日志打印--admin--new：" + sendAPIByAddAdmin);
                Integer sucessCount = 0;
                Integer failCount = 0;
                JSONObject jsonObject = JSONObject.parseObject(sendAPIByAddAdmin);
                //同步失败
                if (StrUtil.isNotEmpty(jsonObject.getString("errcode"))) {
                    String errmsg = "";
                    if (StrUtil.isNotEmpty(jsonObject.getString("errmsg"))) {
                        errmsg = jsonObject.getString("errmsg");
                    }
                    return new Result(false, 0, "OA系统请求报错，报错信息为--new：" + errmsg);
                } else {
                    List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();
                    JSONArray dataResult = jsonObject.getJSONArray("data");
                    int batchSize = 100;
                    int totalSize = dataResult.size();
                    int batchCount = (totalSize + batchSize - 1) / batchSize;

                    for (int i = 0; i < batchCount; ++i) {
                        int startIndex = i * batchSize;
                        int endIndex = Math.min(startIndex + batchSize, totalSize);
                        List<Object> subObjects = dataResult.subList(startIndex, endIndex);
                        for (Object object : subObjects) {
                            JSONObject jsonObject1 = (JSONObject) object;
//                        JSONObject jsonObject1 = dataResult.getJSONObject(i);
                            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                            exceptionRequestVo.setTaskName("OA部门同步-new-" + jsonObject1.getString("keyValue") + "-" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
                            exceptionRequestVo.setTaskType(TaskNameEnum.OADEPT.getValue());
                            exceptionRequestVo.setType(type);
                            exceptionRequestVo.setExcuteDate(new Date());
                            exceptionRequestVo.setErrorReason(jsonObject1.getString("errcode"));
                            exceptionRequestVo.setIsSucess("否");
                            if ("SUCCESS".equals(jsonObject1.getString("status"))) {
                                exceptionRequestVo.setIsSucess("是");
                                sucessCount = sucessCount + 1;
                            } else {
                                failCount++;
                            }

                            exceptionRequestVo.setRequestParam(JSON.toJSONString(paramMap.get(jsonObject1.getString("keyValue"))));
                            exceptionRequestVo.setResponeParam(jsonObject1.toString());
                            exceptionRequestVoList.add(exceptionRequestVo);
                        }
                        if (exceptionRequestVoList != null && exceptionRequestVoList.size() > 0) {
                            int resultConut = this.exceptionService.insertBatchException(exceptionRequestVoList);
                            if (resultConut > 0) {
                                exceptionRequestVoList.clear();
                            }
                        }
                    }

                    result.setMessage("操作成功--new,同步成功" + sucessCount + "，失败" + failCount + "条");
                    return result;
                }
            }
        } else {
            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
            exceptionRequestVo.setTaskName("OA部门同步-new");
            exceptionRequestVo.setTaskType(TaskNameEnum.OADEPT.getValue());
            exceptionRequestVo.setType(type);
            exceptionRequestVo.setExcuteDate(new Date());
            exceptionRequestVo.setErrorReason("当前时间范围内未找到组织的变动记录");
            exceptionRequestVo.setIsSucess("否");
            exceptionRequestVo.setResponeParam(jsonAdmArr.toJSONString());
            this.exceptionService.insertException(exceptionRequestVo);
            return new Result(false, 0, "当前时间范围内未找到组织的变动记录--new");
        }
    }

    @Scheduled(
            cron = "${scheduled.position.cron}"
    )
    @Transactional
    public void SynPosition() throws Exception {
        if (TaskStatusEnum.ABLE.getValue().equals(this.positioncronStatus)) {
            this.synPositionToType(FinalParamUtil.parse(FinalParamUtil.getBeforeOneDay(new Date())), new Date(), TypeEnum.AUTO.getValue());
        }

    }

    public Result SynPosition(Date startTime, Date endTime) throws Exception {
        return this.synPositionToType(startTime, endTime, TypeEnum.MANUAL.getValue());
    }

    private Result synPositionToType(Date startTime, Date endTime, String type) throws Exception {
        SHRClient sHRClient = new SHRClient();
        //TODO
        this.token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
//        this.token = sHRClient.loginShrByUser(shrurl);
        Result result = new Result();
        result.setCode(1);
        JSONArray jsonAdmArr = null;

        try {
            jsonAdmArr = JSONObject.parseArray(this.getOSFData(this.finalParamUtil.getInteOAGetPositionDataService(), (Map) null).getData().toString());
        } catch (Exception var29) {
            return new Result(false, 0, "SHR系统请求报错，报错信息为--new：" + var29.getMessage());
        }

        Map<String, Object> mapBody = new HashMap();
        ArrayList<Map<String, String>> listBody = new ArrayList();
        Map<String, Object> paramMap = new HashMap();
        //shr返回的岗位数据不为空
        if (jsonAdmArr != null && jsonAdmArr.size() > 0) {
            for (int i = 0; i < jsonAdmArr.size(); ++i) {
                JSONObject jsonObject = JSONObject.parseObject(jsonAdmArr.get(i).toString());
                String fLastUpdateTime = jsonObject.getString("fLastUpdateTime");
                Boolean flag = FinalParamUtil.getLastDateTime(fLastUpdateTime);
                if (startTime != null && endTime != null) {
                    flag = false;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (startTime.getTime() <= sdf.parse(fLastUpdateTime).getTime() && sdf.parse(fLastUpdateTime).getTime() <= endTime.getTime()) {
                        flag = true;
                    }
                }

                if (flag) {
                    String longNamel1 = jsonObject.getString("longNamel1");
                    String longNamel2 = jsonObject.getString("longNamel2");
                    String name = jsonObject.getString("Name");
                    String namel1 = jsonObject.getString("Namel1");
                    String orgName = jsonObject.getString("orgName");
                    String posName_CN = "";
                    String posName_EN = "";
                    if (!StrUtil.isEmpty(orgName) && "true".equals(this.finalParamUtil.getIsJobTitlePrefixed())) {
                        posName_CN = orgName + "-" + name;
                        posName_EN = orgName + "-" + namel1;
                    } else {
                        posName_CN = name;
                        posName_EN = namel1;
                    }

                    String parent = jsonObject.getString("supFnumber");
                    HashMap mpBody = new HashMap();
                    mpBody.put("code", jsonObject.getString("fnumber"));
                    mpBody.put("name", posName_EN);
                    mpBody.put("parent", parent);
                    mpBody.put("department", jsonObject.getString("fOrgNumber"));
                    JSONObject multiname = new JSONObject();
                    multiname.put("7", posName_CN);
                    multiname.put("8", posName_EN);
                    JSONObject multiObj = new JSONObject();
                    multiObj.put("name", multiname);
                    mpBody.put("multiObj", multiObj);

                    listBody.add(mpBody);
                    paramMap.put(jsonObject.getString("fnumber"), mpBody);
                }
            }

            if (listBody.size() == 0) {
                return new Result(false, 0, "当前时间范围内未找到岗位的变动记录--new");
            } else {
                mapBody.put("data", listBody);
                Map<String, String> dataRuleMap = new HashMap();
                dataRuleMap.put("position", "code");
                dataRuleMap.put("department", "code");
                mapBody.put("dataRule", dataRuleMap);
                String sendAPIByAddPosition = "";

                try {
                    sendAPIByAddPosition = this.newOaApiUtil.restful("/papi/openapi/api/hrm/restful/syncPosition", mapBody, "sendAPIByAddPosition");
                } catch (Exception var28) {
                    return new Result(false, 0, "OA系统请求报错，报错信息为--new：" + var28.getMessage());
                }

                System.out.println("日志打印--position--new：" + sendAPIByAddPosition);
                Integer sucessCount = 0;
                Integer failCount = 0;
                JSONObject jsonObject = JSONObject.parseObject(sendAPIByAddPosition);
                //同步失败
                if (StrUtil.isNotEmpty(jsonObject.getString("errcode"))) {
                    String errmsg = "";
                    if (StrUtil.isNotEmpty(jsonObject.getString("errmsg"))) {
                        errmsg = jsonObject.getString("errmsg");
                    }
                    return new Result(false, 0, "OA系统请求报错，报错信息为--new：" + errmsg);
                } else {
                    List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();
                    JSONArray dataResult = jsonObject.getJSONArray("data");
                    int batchSize = 100;
                    int totalSize = dataResult.size();
                    int batchCount = (totalSize + batchSize - 1) / batchSize;

                    for (int i = 0; i < batchCount; ++i) {
                        int startIndex = i * batchSize;
                        int endIndex = Math.min(startIndex + batchSize, totalSize);
                        List<Object> subObjects = dataResult.subList(startIndex, endIndex);
                        for (Object object : subObjects) {
                            JSONObject jsonObject1 = (JSONObject) object;
//                        JSONObject jsonObject1 = dataResult.getJSONObject(i);
                            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                            exceptionRequestVo.setTaskName("OA岗位同步-new-" + jsonObject1.getString("keyValue") + "-" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
                            exceptionRequestVo.setTaskType(TaskNameEnum.OAPOST.getValue());
                            exceptionRequestVo.setType(type);
                            exceptionRequestVo.setExcuteDate(new Date());
                            exceptionRequestVo.setErrorReason(jsonObject1.getString("errcode"));
                            exceptionRequestVo.setIsSucess("否");
                            if ("SUCCESS".equals(jsonObject1.getString("status"))) {
                                exceptionRequestVo.setIsSucess("是");
                                sucessCount = sucessCount + 1;
                            } else {
                                failCount++;
                            }

                            exceptionRequestVo.setRequestParam(JSON.toJSONString(paramMap.get(jsonObject1.getString("keyValue"))));
                            exceptionRequestVo.setResponeParam(jsonObject1.toString());
                            exceptionRequestVoList.add(exceptionRequestVo);
                        }
                        if (exceptionRequestVoList != null && exceptionRequestVoList.size() > 0) {
                            int resultConut = this.exceptionService.insertBatchException(exceptionRequestVoList);
                            if (resultConut > 0) {
                                exceptionRequestVoList.clear();
                            }
                        }
                    }

                    result.setMessage("操作成功--new,同步成功" + sucessCount + "，失败" + failCount + "条");
                    return result;
                }
            }
        } else {
            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
            exceptionRequestVo.setTaskName("OA岗位同步-new");
            exceptionRequestVo.setTaskType(TaskNameEnum.OAPOST.getValue());
            exceptionRequestVo.setType(type);
            exceptionRequestVo.setExcuteDate(new Date());
            exceptionRequestVo.setErrorReason("当前时间范围内未找到岗位的变动记录");
            exceptionRequestVo.setIsSucess("否");
            exceptionRequestVo.setResponeParam(jsonAdmArr.toJSONString());
            this.exceptionService.insertException(exceptionRequestVo);
            return new Result(false, 0, "当前时间范围内未找到岗位的变动记录--new");
        }
    }

    @Scheduled(
            cron = "${scheduled.person.cron}"
    )
    @Transactional
    public void scheduledSynPerson() throws IOException {
        if (TaskStatusEnum.ABLE.getValue().equals(this.cronStatus)) {
            Map<String, String> param = new HashMap();
            param.put("startDate", FinalParamUtil.getBeforeOneDay(new Date()));
            param.put("endDate", FinalParamUtil.formatDate(new Date()));
            param.put("personNumber", "");
            SHRClient sHRClient = new SHRClient();
            //TODO
            this.token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
//            this.token = sHRClient.loginShrByUser(shrurl);
            String resultString = this.getOSFData(this.finalParamUtil.getSynPersonService(), param).getData().toString();
            JSONObject shrResultJson = JSONObject.parseObject(resultString);
            if (!org.springframework.util.StringUtils.isEmpty(shrResultJson) && "error".equals(shrResultJson.getString("result"))) {
                ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                exceptionRequestVo.setTaskName("OA员工同步-new");
                exceptionRequestVo.setTaskType(TaskNameEnum.OASTAFF.getValue());
                exceptionRequestVo.setType(TypeEnum.AUTO.getValue());
                exceptionRequestVo.setExcuteDate(new Date());
                exceptionRequestVo.setErrorReason(shrResultJson.getString("summary"));
                exceptionRequestVo.setIsSucess("否");
                exceptionRequestVo.setResponeParam(resultString);
                this.exceptionService.insertException(exceptionRequestVo);
            } else if (shrResultJson.getString("code").equals("1") && shrResultJson.getJSONArray("data").size() > 0) {
                this.synPersonToType(shrResultJson, TypeEnum.AUTO.getValue());
            } else {
                ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                exceptionRequestVo.setTaskName("OA员工同步-new");
                exceptionRequestVo.setTaskType(TaskNameEnum.OASTAFF.getValue());
                exceptionRequestVo.setType(TypeEnum.AUTO.getValue());
                exceptionRequestVo.setExcuteDate(new Date());
                exceptionRequestVo.setErrorReason("当前时间范围内暂无变更的人员信息");
                exceptionRequestVo.setIsSucess("否");
                exceptionRequestVo.setResponeParam(resultString);
                this.exceptionService.insertException(exceptionRequestVo);
            }
        }
    }

    public Result synPerson(String startDate, String endDate, String personNumber) throws Exception {
        SHRClient sHRClient = new SHRClient();
        this.token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
        Map<String, String> param = new HashMap();
        param.put("startDate", startDate);
        param.put("endDate", endDate);
        param.put("personNumber", personNumber);
        String resultString = "";

        try {
            resultString = this.getOSFData(this.finalParamUtil.getSynPersonService(), param).getData().toString();
        } catch (Exception var8) {
            return new Result(false, 0, "SHR系统请求报错，报错信息为--new：" + var8.getMessage());
        }

        JSONObject shrResultJson = JSONObject.parseObject(resultString);
        if (!org.springframework.util.StringUtils.isEmpty(shrResultJson) && "error".equals(shrResultJson.getString("result"))) {
            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
            exceptionRequestVo.setTaskName("OA员工同步-new");
            exceptionRequestVo.setTaskType(TaskNameEnum.OASTAFF.getValue());
            exceptionRequestVo.setType(TypeEnum.MANUAL.getValue());
            exceptionRequestVo.setExcuteDate(new Date());
            exceptionRequestVo.setErrorReason(shrResultJson.getString("summary"));
            exceptionRequestVo.setIsSucess("否");
            exceptionRequestVo.setResponeParam(resultString);
            this.exceptionService.insertException(exceptionRequestVo);
            return new Result(false, 0, shrResultJson.getString("summary"));
        } else if (shrResultJson.getString("code").equals("1") && shrResultJson.getJSONArray("data").size() > 0) {
            return this.synPersonToType(shrResultJson, TypeEnum.MANUAL.getValue());
        } else {
            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
            exceptionRequestVo.setTaskName("OA员工同步-new");
            exceptionRequestVo.setTaskType(TaskNameEnum.OASTAFF.getValue());
            exceptionRequestVo.setType(TypeEnum.MANUAL.getValue());
            exceptionRequestVo.setExcuteDate(new Date());
            exceptionRequestVo.setErrorReason("当前时间范围内暂无变更的人员信息");
            exceptionRequestVo.setIsSucess("否");
            exceptionRequestVo.setResponeParam(resultString);
            this.exceptionService.insertException(exceptionRequestVo);
            Result result = new Result();
            result.setMessage("shr端暂无变更的人员信息！--new");
            return result;
        }
    }

    private Result synPersonToType(JSONObject shrResultJson, String type) {
        JSONArray dataJsonArray = (JSONArray) shrResultJson.get("data");
        Map<String, Object> mapBody = new HashMap();
        ArrayList<Map<String, String>> listBody = new ArrayList();
        Map<String, Object> paramMap = new HashMap();

        //组装e10需要的参数格式
//        JSONArray newJsonArray = new JSONArray();
        for (int i = 0; i < dataJsonArray.size(); i++) {
            HashMap mpBody = new HashMap();
//            JSONObject newObj = new JSONObject();
            JSONObject requestJson = dataJsonArray.getJSONObject(i);
            mpBody.put("loginid", requestJson.getString("loginid"));
            mpBody.put("job_num", requestJson.getString("workcode"));
            //处理岗位
            String jobtitle = requestJson.getString("jobtitle");
            String validJson = jobtitle.replaceFirst("^\\{JSON\\}", "");
            JSONObject jsonObj = JSONObject.parseObject(validJson);
            mpBody.put("position", jsonObj.getString("jobtitlecode"));

            mpBody.put("hiredate", requestJson.getString("companystartdate"));
            //判断性别
            String sex = null;
            if (StrUtil.isNotEmpty(requestJson.getString("sex"))) {
                if ("男".equals(requestJson.getString("sex"))) {
                    sex = "male";
                } else if ("女".equals(requestJson.getString("sex"))) {
                    sex = "female";
                } else {
                    sex = "";
                }
            }
            mpBody.put("sex", sex);
            mpBody.put("mobile", requestJson.getString("mobile"));
            mpBody.put("telephone", requestJson.getString("telephone"));
            mpBody.put("grade", requestJson.getString("joblevel"));
            mpBody.put("superior", requestJson.getString("managerid"));
            mpBody.put("username", requestJson.getString("lastname"));
            mpBody.put("password", requestJson.getString("password"));
            //处理部门
            String department = requestJson.getString("department");
            validJson = department.replaceFirst("^\\{JSON\\}", "");
            jsonObj = JSONObject.parseObject(validJson);
            mpBody.put("department", jsonObj.getString("departmentcode"));

            mpBody.put("sec_level", requestJson.getString("seclevel"));
            mpBody.put("email", requestJson.getString("email"));
            mpBody.put("personnel_status", StrUtil.isEmpty(statusmap.get(requestJson.getString("status")))?"":statusmap.get(requestJson.getString("status")));
            mpBody.put("resp_desc",requestJson.getString("jobactivitydesc"));

            listBody.add(mpBody);
//            newJsonArray.add(newObj);
            paramMap.put(requestJson.getString("workcode"), mpBody);
        }

//        mapBody.put("data", listBody);
        Map<String, String> dataRuleMap = new HashMap();
        dataRuleMap.put("employee", "job_num");
        dataRuleMap.put("department", "code");
        dataRuleMap.put("position", "code");
        dataRuleMap.put("grade", "name");
        mapBody.put("dataRule", dataRuleMap);

//        JSONArray dataArray = shrResultJson.getJSONArray("data");
        int arraySize = listBody.size();
        int arrayNum = arraySize % 100 == 0 ? arraySize / 100 : arraySize / 100 + 1;

        int errorSize = 0;
        int successSize = 0;
        TaskNameEnum oaStaff = TaskNameEnum.OASTAFF;
        List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();

        for (int i = 1; i <= arrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 100, arraySize);
            int jSONArrayStart = (i - 1) * 100;
            List<Map<String, String>> objects = listBody.subList(jSONArrayStart, jSONArrayEnd);
            mapBody.put("data", objects);
            String sendAPIByAddPerson = "";

            try {
                sendAPIByAddPerson = this.newOaApiUtil.restful("/papi/openapi/api/hrm/restful/syncEmployee", mapBody, "sendAPIByAddPerson");
            } catch (Exception var27) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + var27.getMessage());
            }

            JSONObject oaResultJson = JSON.parseObject(sendAPIByAddPerson);
            if (StrUtil.isNotEmpty(oaResultJson.getString("errcode"))) {
                String errmsg = "";
                if (StrUtil.isNotEmpty(oaResultJson.getString("errmsg"))) {
                    errmsg = oaResultJson.getString("errmsg");
                }
                return new Result(false, 0, "OA系统请求报错，报错信息为--new：" + errmsg);
            } else {
                JSONArray dataResult = oaResultJson.getJSONArray("data");
                if (dataResult != null && dataResult.size() > 0) {
                    for (int index = 0; index < dataResult.size(); ++index) {
                        JSONObject jsonObject1 = dataResult.getJSONObject(index);
                        ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                        exceptionRequestVo.setTaskName("OA员工同步-new-" + jsonObject1.getString("keyValue") + "-" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
                        exceptionRequestVo.setTaskType(oaStaff.getValue());
                        exceptionRequestVo.setType(type);
                        exceptionRequestVo.setExcuteDate(new Date());
                        exceptionRequestVo.setErrorReason(jsonObject1.getString("errcode"));
                        exceptionRequestVo.setIsSucess("否");
                        if ("SUCCESS".equals(jsonObject1.getString("status"))) {
                            exceptionRequestVo.setIsSucess("是");
                            successSize = successSize + 1;
                        } else {
                            errorSize++;
                        }

                        exceptionRequestVo.setRequestParam(JSON.toJSONString(paramMap.get(jsonObject1.getString("keyValue"))));
                        exceptionRequestVo.setResponeParam(jsonObject1.toString());
                        exceptionRequestVoList.add(exceptionRequestVo);
                    }
                    if (exceptionRequestVoList != null && exceptionRequestVoList.size() > 0) {
                        int resultConut = this.exceptionService.insertBatchException(exceptionRequestVoList);
                        if (resultConut > 0) {
                            exceptionRequestVoList.clear();
                        }
                    }
                }
            }

        }

        return new Result(true, successSize - errorSize > 0 ? 1 : 0, "同步成功:" + successSize + ";同步失败:" + errorSize);
    }

    public Response getOSFData(String OsfName, Map map) throws IOException {
        SHRClient client = new SHRClient();
        //TODO 这里先把shr生产环境数据同步到oa测试环境，为了不影响生产环境同步程序的日志等配置。这里不能在application.yml中spring.profiles.active:uat改为prod。所以先写死生产shr的url
        return client.executeOSFService(this.finalParamUtil.getShrUrl(), this.token, OsfName, map);
//        return client.executeOSFService(shrurl, this.token, OsfName, map);
    }
}
