package com.gtiit.shr.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gtiit.shr.common.Result;
import com.gtiit.shr.entity.enums.OperationEnum;
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.CountVo;
import com.gtiit.shr.entity.vo.DeptInfoVo;
import com.gtiit.shr.entity.vo.ExceptionRequestVo;
import com.gtiit.shr.entity.vo.JobInfoVo;
import com.gtiit.shr.entity.vo.PersonInfoVo;
import com.gtiit.shr.entity.vo.PersonOfficeVo;
import com.gtiit.shr.entity.vo.PositionVo;
import com.gtiit.shr.service.DeptService;
import com.gtiit.shr.service.ExceptionService;
import com.gtiit.shr.service.JobService;
import com.gtiit.shr.service.LocalCopyService;
import com.gtiit.shr.service.PersonOfficeService;
import com.gtiit.shr.service.PersonService;
import com.gtiit.shr.service.PositionService;
import com.gtiit.shr.utils.FinalParamUtil;
import com.gtiit.shr.utils.ShrClientUtil;
import com.kingdee.shr.api.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
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.util.StringUtils;

@Service
public class LocalCopyServiceImpl implements LocalCopyService {
    @Autowired
    private ShrClientUtil shrClientUtil;
    @Autowired
    private FinalParamUtil finalParamUtil;
    @Autowired
    private PersonService personService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private PersonOfficeService personOfficeService;
    @Autowired
    private ExceptionService exceptionService;
    @Autowired
    private JobService jobService;
    @Value("${scheduled.local.person.able}")
    private String personStatus;
    @Value("${scheduled.local.dept.able}")
    private String deptStatus;
    @Value("${scheduled.local.position.able}")
    private String positionStatus;
    @Value("${scheduled.local.personOffice.able}")
    private String personOfficeStatus;
    @Value("${scheduled.local.job.able}")
    private String jobStatus;


    @Scheduled(
            cron = "${scheduled.local.person.cron}"
    )
    public void scheduledSynLocalPerson() {
        if (TaskStatusEnum.ABLE.getValue().equals(this.personStatus)) {
            FinalParamUtil var10001 = this.finalParamUtil;
            String var1 = FinalParamUtil.getBeforeOneDay(new Date());
            FinalParamUtil var10002 = this.finalParamUtil;
            this.savePersonToType(var1, FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    @Scheduled(
            cron = "${scheduled.local.dept.cron}"
    )
    public void scheduledSynLocalDept() {
        if (TaskStatusEnum.ABLE.getValue().equals(this.deptStatus)) {
            this.saveDeptToType(FinalParamUtil.getBeforeOneDay(new Date()), FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    @Scheduled(
            cron = "${scheduled.local.position.cron}"
    )
    public void scheduledSynLocalPosition() {
        if (TaskStatusEnum.ABLE.getValue().equals(this.positionStatus)) {
            this.savePositionToType(FinalParamUtil.getBeforeOneDay(new Date()), FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    @Scheduled(
            cron = "${scheduled.local.personOffice.cron}"
    )
    public void scheduledSynLocalPersonOffice() {
        if (TaskStatusEnum.ABLE.getValue().equals(this.personOfficeStatus)) {
            this.savePersonOfficeToType(FinalParamUtil.getBeforeOneDay(new Date()), FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    @Scheduled(
            cron = "${scheduled.local.job.cron}"
    )
    public void scheduledSynLocalJob() {
        if (TaskStatusEnum.ABLE.getValue().equals(this.jobStatus)) {
            this.savePersonToType(FinalParamUtil.getBeforeOneDay(new Date()), FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    public Result savePerson(String bigDat, String endDat) {
        return this.savePersonToType(bigDat, endDat, TypeEnum.MANUAL.getValue());
    }

    public Result saveDept(String bigDat, String endDat) {
        return this.saveDeptToType(bigDat, endDat, TypeEnum.MANUAL.getValue());
    }

    public Result savePosition(String bigDat, String endDat) {
        return this.savePositionToType(bigDat, endDat, TypeEnum.MANUAL.getValue());
    }

    public Result savePersonOffice(String bigDat, String endDat) {
        return this.savePersonOfficeToType(bigDat, endDat, TypeEnum.MANUAL.getValue());
    }

    public Result saveJob(String bigDat, String endDat) {
        return this.saveJobToType(bigDat, endDat, TypeEnum.MANUAL.getValue());
    }

    private Result savePersonToType(String bigDat, String endDat, String type) {
        Result result = new Result();
        CountVo addCountVo = new CountVo();
        CountVo updateCountVo = new CountVo();

        try {
            Map<String, String> map = new HashMap();
            map.put("startDate", bigDat);
            map.put("endDate", endDat);
            Response response = this.shrClientUtil.sendShr(this.finalParamUtil.getGtiitLocalPersonOsfService(), map);
            JSONArray dataArray = JSONArray.parseArray(response.getData().toString());
            if (dataArray.isEmpty()) {
                result.setFlag(false);
                result.setCode(0);
                result.setMessage("当前时间范围内暂无变更的员工基本信息数据！");
                return result;
            }

            List<String> shrIds = (List)dataArray.stream().map((obj) -> {
                return ((JSONObject)obj).getString("SHRID");
            }).collect(Collectors.toList());
            List<PersonInfoVo> queryLists = this.queryList(shrIds);
            Map<String, PersonInfoVo> personInfoVoMap = new HashMap();
            if (queryLists != null && queryLists.size() > 0) {
                personInfoVoMap = (Map)queryLists.stream().collect(Collectors.toMap(PersonInfoVo::getId, Function.identity(), (v1, v2) -> {
                    return v1;
                }));
            }

            List<PersonInfoVo> addPersonInfoVos = new ArrayList();
            List<PersonInfoVo> updatePersonInfoVos = new ArrayList();
            Iterator var15 = dataArray.iterator();

            while(var15.hasNext()) {
                Object data = var15.next();
                JSONObject dataJson = (JSONObject)data;
                PersonInfoVo personInfoVo = new PersonInfoVo();
                String shrid = dataJson.getString("SHRID");
                if (((Map)personInfoVoMap).get(shrid) != null) {
                    personInfoVo = (PersonInfoVo)((Map)personInfoVoMap).get(shrid);
                    updatePersonInfoVos.add(this.processPerson(personInfoVo, dataJson));
                } else {
                    addPersonInfoVos.add(this.processPerson(personInfoVo, dataJson));
                }
            }

            if (addPersonInfoVos != null && addPersonInfoVos.size() > 0) {
                addCountVo = this.processTurnSaveAndUpdate(addPersonInfoVos, OperationEnum.ADD.getValue(), type, addCountVo);
            }

            if (updatePersonInfoVos != null && updatePersonInfoVos.size() > 0) {
                updateCountVo = this.processTurnSaveAndUpdate(updatePersonInfoVos, OperationEnum.UPDATE.getValue(), type, updateCountVo);
            }
        } catch (Exception var20) {
            return new Result(false, 0, "系统报错,报错信息为：" + var20.getMessage());
        }

        result.setFlag(true);
        result.setCode(1);
        result.setMessage("操作成功，总条数为：" + (addCountVo.getTotalCount() + updateCountVo.getTotalCount()) + "，新增了" + addCountVo.getSuccessTotal() + "条，更新了" + updateCountVo.getSuccessTotal() + "条");
        return result;
    }

    private Result saveDeptToType(String bigDat, String endDat, String type) {
        Result result = new Result();
        CountVo addCountVo = new CountVo();
        CountVo updateCountVo = new CountVo();

        try {
            Map<String, String> map = new HashMap();
            map.put("startDate", this.formatDate(bigDat, true));
            map.put("endDate", this.formatDate(endDat, false));
            Response response = this.shrClientUtil.sendShr(this.finalParamUtil.getGtiitOrgAdminService(), map);
            JSONArray dataArray = JSONArray.parseArray(response.getData().toString());
            if (dataArray.isEmpty()) {
                result.setFlag(false);
                result.setCode(0);
                result.setMessage("当前时间范围内暂无变更的部门数据！");
                return result;
            }

            List<String> shrIds = (List)dataArray.stream().map((obj) -> {
                return ((JSONObject)obj).getString("ID");
            }).collect(Collectors.toList());
            List<DeptInfoVo> queryLists = this.queryListDept(shrIds);
            Map<String, DeptInfoVo> infoVoMap = new HashMap();
            if (queryLists.size() > 0) {
                infoVoMap = (Map)queryLists.stream().collect(Collectors.toMap(DeptInfoVo::getId, Function.identity(), (v1, v2) -> {
                    return v1;
                }));
            }

            List<DeptInfoVo> addInfoVos = new ArrayList();
            List<DeptInfoVo> updateInfoVos = new ArrayList();
            Iterator var15 = dataArray.iterator();

            while(var15.hasNext()) {
                Object data = var15.next();
                JSONObject dataJson = (JSONObject)data;
                DeptInfoVo infoVo = new DeptInfoVo();
                String shrid = dataJson.getString("ID");
                if (((Map)infoVoMap).get(shrid) != null) {
                    infoVo = (DeptInfoVo)((Map)infoVoMap).get(shrid);
                    updateInfoVos.add(this.processDept(infoVo, dataJson));
                } else {
                    addInfoVos.add(this.processDept(infoVo, dataJson));
                }
            }

            if (addInfoVos.size() > 0) {
                addCountVo = this.processTurnSaveAndUpdateDept(addInfoVos, OperationEnum.ADD.getValue(), type, addCountVo);
            }

            if (updateInfoVos.size() > 0) {
                updateCountVo = this.processTurnSaveAndUpdateDept(updateInfoVos, OperationEnum.UPDATE.getValue(), type, updateCountVo);
            }
        } catch (Exception var20) {
            return new Result(false, 0, "系统报错,报错信息为：" + var20.getMessage());
        }

        result.setFlag(true);
        result.setCode(1);
        result.setMessage("操作成功，总条数为：" + (addCountVo.getTotalCount() + updateCountVo.getTotalCount()) + "，新增了" + addCountVo.getSuccessTotal() + "条，更新了" + updateCountVo.getSuccessTotal() + "条");
        return result;
    }

    private Result savePositionToType(String bigDat, String endDat, String type) {
        Result result = new Result();
        CountVo addCountVo = new CountVo();
        CountVo updateCountVo = new CountVo();

        try {
            Map<String, String> map = new HashMap();
            map.put("startDate", this.formatDate(bigDat, true));
            map.put("endDate", this.formatDate(endDat, false));
            Response response = this.shrClientUtil.sendShr(this.finalParamUtil.getGtiitOrgPositionService(), map);
            JSONArray dataArray = JSONArray.parseArray(response.getData().toString());
            if (dataArray.isEmpty()) {
                result.setFlag(false);
                result.setCode(0);
                result.setMessage("当前时间范围内暂无变更的职位数据！");
                return result;
            }

            List<String> shrIds = (List)dataArray.stream().map((obj) -> {
                return ((JSONObject)obj).getString("ID");
            }).collect(Collectors.toList());
            List<PositionVo> queryLists = this.queryListPosition(shrIds);
            Map<String, PositionVo> infoVoMap = new HashMap();
            if (queryLists.size() > 0) {
                infoVoMap = (Map)queryLists.stream().collect(Collectors.toMap(PositionVo::getId, Function.identity(), (v1, v2) -> {
                    return v1;
                }));
            }

            List<PositionVo> addInfoVos = new ArrayList();
            List<PositionVo> updateInfoVos = new ArrayList();
            Iterator var15 = dataArray.iterator();

            while(var15.hasNext()) {
                Object data = var15.next();
                JSONObject dataJson = (JSONObject)data;
                PositionVo infoVo = new PositionVo();
                String shrid = dataJson.getString("ID");
                if (((Map)infoVoMap).get(shrid) != null) {
                    infoVo = (PositionVo)((Map)infoVoMap).get(shrid);
                    updateInfoVos.add(this.processPosition(infoVo, dataJson));
                } else {
                    addInfoVos.add(this.processPosition(infoVo, dataJson));
                }
            }

            if (addInfoVos.size() > 0) {
                addCountVo = this.processTurnSaveAndUpdatePosition(addInfoVos, OperationEnum.ADD.getValue(), type, addCountVo);
            }

            if (updateInfoVos.size() > 0) {
                updateCountVo = this.processTurnSaveAndUpdatePosition(updateInfoVos, OperationEnum.UPDATE.getValue(), type, updateCountVo);
            }
        } catch (Exception var20) {
            return new Result(false, 0, "系统报错,报错信息为：" + var20.getMessage());
        }

        result.setFlag(true);
        result.setCode(1);
        result.setMessage("操作成功，总条数为：" + (addCountVo.getTotalCount() + updateCountVo.getTotalCount()) + "，新增了" + addCountVo.getSuccessTotal() + "条，更新了" + updateCountVo.getSuccessTotal() + "条");
        return result;
    }

    private Result savePersonOfficeToType(String bigDat, String endDat, String type) {
        Result result = new Result();
        CountVo addCountVo = new CountVo();
        CountVo updateCountVo = new CountVo();

        try {
            Map<String, String> map = new HashMap();
            map.put("startDate", this.formatDate(bigDat, true));
            map.put("endDate", this.formatDate(endDat, false));
            Response response = this.shrClientUtil.sendShr(this.finalParamUtil.getGtiitEmpOrgRelationService(), map);
            JSONArray dataArray = JSONArray.parseArray(response.getData().toString());
            if (dataArray.isEmpty()) {
                result.setFlag(false);
                result.setCode(0);
                result.setMessage("当前时间范围内暂无变更的员工任职历史数据！");
                return result;
            }

            List<String> shrIds = (List)dataArray.stream().map((obj) -> {
                return ((JSONObject)obj).getString("ID");
            }).collect(Collectors.toList());
            List<PersonOfficeVo> queryLists = this.queryListPersonOffice(shrIds);
            Map<String, PersonOfficeVo> infoVoMap = new HashMap();
            if (queryLists.size() > 0) {
                infoVoMap = (Map)queryLists.stream().collect(Collectors.toMap(PersonOfficeVo::getId, Function.identity(), (v1, v2) -> {
                    return v1;
                }));
            }

            List<PersonOfficeVo> addInfoVos = new ArrayList();
            List<PersonOfficeVo> updateInfoVos = new ArrayList();
            Iterator var15 = dataArray.iterator();

            while(var15.hasNext()) {
                Object data = var15.next();
                JSONObject dataJson = (JSONObject)data;
                PersonOfficeVo infoVo = new PersonOfficeVo();
                String shrid = dataJson.getString("ID");
                if (((Map)infoVoMap).get(shrid) != null) {
                    infoVo = (PersonOfficeVo)((Map)infoVoMap).get(shrid);
                    updateInfoVos.add(this.processPersonOffice(infoVo, dataJson));
                } else {
                    addInfoVos.add(this.processPersonOffice(infoVo, dataJson));
                }
            }

            if (addInfoVos.size() > 0) {
                addCountVo = this.processTurnSaveAndUpdatePersonOffice(addInfoVos, OperationEnum.ADD.getValue(), type, addCountVo);
            }

            if (updateInfoVos.size() > 0) {
                updateCountVo = this.processTurnSaveAndUpdatePersonOffice(updateInfoVos, OperationEnum.UPDATE.getValue(), type, updateCountVo);
            }
        } catch (Exception var20) {
            return new Result(false, 0, "系统报错,报错信息为：" + var20.getMessage());
        }

        result.setFlag(true);
        result.setCode(1);
        result.setMessage("操作成功，总条数为：" + (addCountVo.getTotalCount() + updateCountVo.getTotalCount()) + "，新增了" + addCountVo.getSuccessTotal() + "条，更新了" + updateCountVo.getSuccessTotal() + "条");
        return result;
    }

    private List<PersonInfoVo> queryList(List<String> shrIds) {
        List<PersonInfoVo> personInfoVos = new ArrayList();
        int jSONArraySize = shrIds.size();
        int jSONArrayNum = jSONArraySize % 1000 == 0 ? jSONArraySize / 1000 : jSONArraySize / 1000 + 1;

        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 1000, jSONArraySize);
            int jSONArrayStart = (i - 1) * 1000;
            List<String> ids = shrIds.subList(jSONArrayStart, jSONArrayEnd);
            Result page = this.personService.findPage(ids);
            if (page.getData() != null) {
                personInfoVos.addAll((List)page.getData());
            }
        }

        return personInfoVos;
    }

    private List<DeptInfoVo> queryListDept(List<String> shrIds) {
        List<DeptInfoVo> infoVos = new ArrayList();
        int jSONArraySize = shrIds.size();
        int jSONArrayNum = jSONArraySize % 1000 == 0 ? jSONArraySize / 1000 : jSONArraySize / 1000 + 1;


        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 1000, jSONArraySize);
            int jSONArrayStart = (i - 1) * 1000;
            List<String> ids = shrIds.subList(jSONArrayStart, jSONArrayEnd);
            Result page = this.deptService.findPage(ids);
            if (page.getData() != null) {
                infoVos.addAll((List)page.getData());
            }
        }

        return infoVos;
    }

    private List<PositionVo> queryListPosition(List<String> shrIds) {
        List<PositionVo> infoVos = new ArrayList();
        int jSONArraySize = shrIds.size();
        int jSONArrayNum = jSONArraySize % 1000 == 0 ? jSONArraySize / 1000 : jSONArraySize / 1000 + 1;


        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 1000, jSONArraySize);
            int jSONArrayStart = (i - 1) * 1000;
            List<String> ids = shrIds.subList(jSONArrayStart, jSONArrayEnd);
            Result page = this.positionService.findPage(ids);
            if (page.getData() != null) {
                infoVos.addAll((List)page.getData());
            }
        }

        return infoVos;
    }

    private List<PersonOfficeVo> queryListPersonOffice(List<String> shrIds) {
        List<PersonOfficeVo> infoVos = new ArrayList();
        int jSONArraySize = shrIds.size();
        int jSONArrayNum = jSONArraySize % 1000 == 0 ? jSONArraySize / 1000 : jSONArraySize / 1000 + 1;


        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 1000, jSONArraySize);
            int jSONArrayStart = (i - 1) * 1000;
            List<String> ids = shrIds.subList(jSONArrayStart, jSONArrayEnd);
            Result page = this.personOfficeService.findPage(ids);
            if (page.getData() != null) {
                infoVos.addAll((List)page.getData());
            }
        }

        return infoVos;
    }

    private PersonInfoVo processPerson(PersonInfoVo personInfoVo, JSONObject dataJson) {
        personInfoVo.setId(dataJson.getString("SHRID"));
        personInfoVo.setPersonNumber(dataJson.getString("PERSON_NUMBER"));
        personInfoVo.setLastName(dataJson.getString("LAST_NAME"));
        personInfoVo.setMiddleNames(dataJson.getString("MIDDLE_NAMES"));
        personInfoVo.setFirstName(dataJson.getString("FIRST_NAME"));
        personInfoVo.setLocalName(dataJson.getString("LOCAL_NAME"));
        personInfoVo.setDisplayName(dataJson.getString("DISPLAY_NAME"));
        personInfoVo.setUserPersonType(dataJson.getString("USER_PERSON_TYPE"));
        personInfoVo.setFullPartTime(dataJson.getString("FULL_PART_TIME"));
        personInfoVo.setHireDate(dataJson.getString("HIRE_DATE"));
        personInfoVo.setProbationPeriod(dataJson.getString("PROBATION_PERIOD"));
        personInfoVo.setProbationUnit(dataJson.getString("PROBATION_UNIT"));
        personInfoVo.setDateProbationEnd(dataJson.getString("DATE_PROBATION_END"));
        personInfoVo.setWorkPhone(dataJson.getString("WORK_PHONE"));
        personInfoVo.setCellPhone(dataJson.getString("CELL_PHONE"));
        personInfoVo.setEmailAddress(dataJson.getString("EMAIL_ADDRESS"));
        personInfoVo.setSEmailAddress(dataJson.getString("S_EMAIL_ADDRESS"));
        personInfoVo.setCitizenShip(dataJson.getString("CITIZENSHIP"));
        personInfoVo.setGender(dataJson.getString("GENDER"));
        personInfoVo.setDateOfBirth(dataJson.getString("DATE_OF_BIRTH"));
        personInfoVo.setEthnicity(dataJson.getString("ETHNICITY"));
        personInfoVo.setHukouType(dataJson.getString("HUKOU_TYPE"));
        personInfoVo.setPoliticalStatus(dataJson.getString("POLITICAL_STATUS"));
        personInfoVo.setTerDate(dataJson.getString("TER_DATE"));
        personInfoVo.setReason(dataJson.getString("REASON"));
        personInfoVo.setProfessionalTitle(dataJson.getString("PROFESSIONAL_TITLE"));
        personInfoVo.setJobLevel(dataJson.getString("JOB_LEVEL"));
        personInfoVo.setUserName(dataJson.getString("USER_NAME"));
        personInfoVo.setContractStartDate(dataJson.getString("CONTRACT_START_DATE"));
        personInfoVo.setContractEndDate(dataJson.getString("CONTRACT_END_DATE"));
        personInfoVo.setErpCreationDate(dataJson.getString("ERP_CREATION_DATE"));
        personInfoVo.setErpLastUpdateDate(dataJson.getString("ERP_LAST_UPDATE_DATE"));
        return personInfoVo;
    }

    private DeptInfoVo processDept(DeptInfoVo infoVo, JSONObject dataJson) {
        infoVo.setId(dataJson.getString("ID"));
        infoVo.setOrganizationCode(dataJson.getString("ORGANIZATION_CODE"));
        infoVo.setOrganizationNameEn(dataJson.getString("ORGANIZATION_NAME_EN"));
        infoVo.setOrganizationNameCn(dataJson.getString("ORGANIZATION_NAME_CN"));
        infoVo.setOrganizationShortName(dataJson.getString("ORGANIZATION_SHORT_NAME"));
        infoVo.setDepartmentHeadPersonNumber(dataJson.getString("DEPARTMENT_HEAD_PERSON_NUMBER"));
        infoVo.setDepartmentHeadName(dataJson.getString("DEPARTMENT_HEAD_NAME"));
        infoVo.setPvcPersonNumber(dataJson.getString("PVC_PERSON_NUMBER"));
        infoVo.setPvcName(dataJson.getString("PVC_NAME"));
        infoVo.setErpCreationDate(dataJson.getString("ERP_CREATION_DATE"));
        infoVo.setErpLastUpdateDate(dataJson.getString("ERP_LAST_UPDATE_DATE"));
        return infoVo;
    }

    private PositionVo processPosition(PositionVo infoVo, JSONObject dataJson) {
        infoVo.setId(dataJson.getString("ID"));
        infoVo.setPositionCode(dataJson.getString("POSITION_CODE"));
        infoVo.setPositionNameEn(dataJson.getString("POSITION_NAME_EN"));
        infoVo.setPositionNameCn(dataJson.getString("POSITION_NAME_CN"));
        infoVo.setEffectiveStartDate(dataJson.getString("EFFECTIVE_START_DATE"));
        infoVo.setEffectiveEndDate(dataJson.getString("EFFECTIVE_END_DATE"));
        infoVo.setOrganizationCode(dataJson.getString("ORGANIZATION_CODE"));
        infoVo.setJobCode(dataJson.getString("JOB_CODE"));
        infoVo.setJobNameEn(dataJson.getString("JOB_NAME_EN"));
        infoVo.setActiveStatus(dataJson.getString("ACTIVE_STATUS"));
        infoVo.setDepartmentHead(dataJson.getString("DEPARTMENT_HEAD"));
        infoVo.setErpCreationDate(dataJson.getString("ERP_CREATION_DATE"));
        infoVo.setErpLastUpdateDate(dataJson.getString("ERP_LAST_UPDATE_DATE"));
        return infoVo;
    }

    private PersonOfficeVo processPersonOffice(PersonOfficeVo infoVo, JSONObject dataJson) {
        infoVo.setShrId(dataJson.getString("ID"));
        infoVo.setPersonNumber(dataJson.getString("PERSON_NUMBER"));
        infoVo.setLastName(dataJson.getString("LAST_NAME"));
        infoVo.setMiddleNames(dataJson.getString("MIDDLE_NAMES"));
        infoVo.setFirstName(dataJson.getString("FIRST_NAME"));
        infoVo.setLocalName(dataJson.getString("LOCAL_NAME"));
        infoVo.setDisplayName(dataJson.getString("DISPLAY_NAME"));
        infoVo.setEffectiveStartDate(dataJson.getString("EFFECTIVE_START_DATE"));
        infoVo.setEffectiveEndDate(dataJson.getString("EFFECTIVE_END_DATE"));
        infoVo.setDepartmentCode(dataJson.getString("DEPARTMENT_CODE"));
        infoVo.setDepartmentName(dataJson.getString("DEPARTMENT_NAME"));
        infoVo.setDepartmentShortName(dataJson.getString("DEPARTMENT_SHORT_NAME"));
        infoVo.setJobName(dataJson.getString("JOB_NAME"));
        infoVo.setPosition(dataJson.getString("POSITION"));
        infoVo.setPositionCode(dataJson.getString("POSITION_CODE"));
        infoVo.setWorkCate(dataJson.getString("WORK_CATE"));
        infoVo.setFullPartTime(dataJson.getString("FULL_PART_TIME"));
        infoVo.setManagerPersonNumber(dataJson.getString("MANAGER_PERSON_NUMBER"));
        infoVo.setManagerName(dataJson.getString("MANAGER_NAME"));
        infoVo.setAdminTitle(dataJson.getString("ADMIN_TITLE"));
        infoVo.setAcademicTitle(dataJson.getString("ACADEMIC_TITLE"));
        infoVo.setJob2(dataJson.getString("JOB2"));
        infoVo.setJobLevel(dataJson.getString("JOB_LEVEL"));
        infoVo.setPrimaryFlag(dataJson.getString("PRIMARY_FLAG"));
        infoVo.setAssignmentStatusType(dataJson.getString("ASSIGNMENT_STATUS_TYPE"));
        infoVo.setErpCreationDate(dataJson.getString("ERP_CREATION_DATE"));
        infoVo.setErpLastUpdateDate(dataJson.getString("ERP_LAST_UPDATE_DATE"));
        return infoVo;
    }

    private CountVo processTurnSaveAndUpdate(List<PersonInfoVo> personInfoVos, String operationType, String type, CountVo countVo) {
        int jSONArraySize = personInfoVos.size();
        int jSONArrayNum = jSONArraySize % 60 == 0 ? jSONArraySize / 60 : jSONArraySize / 60 + 1;

        int totalCount = 0;
        int sucessCount = 0;
        List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();

        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 60, jSONArraySize);
            int jSONArrayStart = (i - 1) * 60;
            List<PersonInfoVo> persons = personInfoVos.subList(jSONArrayStart, jSONArrayEnd);
            totalCount += persons.size();
            int result = 0;

            if (operationType.equals(OperationEnum.ADD.getValue())) {
                result = this.personService.insertBatchPerson(persons);
            } else {
                result = this.personService.updateBatchPerson(persons);
            }

            sucessCount += persons.size();
            ExceptionRequestVo exception = new ExceptionRequestVo();
            String personNumbers = (String)persons.stream().filter((a) -> {
                return !StringUtils.isEmpty(a.getPersonNumber());
            }).map((a) -> {
                return a.getPersonNumber();
            }).collect(Collectors.joining(","));
            exception.setTaskType(TaskNameEnum.ATTENDANCE.getValue());
            exception.setType(type);
            exception.setErrorReason("");
            exception.setIsSucess(result > 0 ? "是" : "否");
            StringBuilder var10001 = (new StringBuilder()).append(TaskNameEnum.LPERSON.getName()).append("-");
            FinalParamUtil var10002 = this.finalParamUtil;
            exception.setTaskName(var10001.append(FinalParamUtil.formatDate(new Date())).toString());
            exception.setRequestParam(personNumbers);
            exception.setResponeParam(TaskNameEnum.LPERSON.getName() + OperationEnum.fromVal(operationType).getName() + (result > 0 ? "成功" : "失败"));
            exception.setExcuteDate(new Date());
            exceptionRequestVoList.add(exception);
        }

        countVo.setTotalCount(totalCount);
        countVo.setSuccessTotal(sucessCount);
        if (exceptionRequestVoList != null && exceptionRequestVoList.size() > 0) {
            this.exceptionService.insertBatchException(exceptionRequestVoList);
        }

        return countVo;
    }

    private CountVo processTurnSaveAndUpdateDept(List<DeptInfoVo> infoVos, String operationType, String type, CountVo countVo) {
        int jSONArraySize = infoVos.size();
        int jSONArrayNum = jSONArraySize % 60 == 0 ? jSONArraySize / 60 : jSONArraySize / 60 + 1;

        int totalCount = 0;
        int sucessCount = 0;
        List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();

        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 60, jSONArraySize);
            int jSONArrayStart = (i - 1) * 60;
            List<DeptInfoVo> vos = infoVos.subList(jSONArrayStart, jSONArrayEnd);
            totalCount += vos.size();
            int result = 0;

            if (operationType.equals(OperationEnum.ADD.getValue())) {
                result = this.deptService.insertBatchPerson(vos);
            } else {
                result = this.deptService.updateBatchPerson(vos);
            }

            sucessCount += vos.size();
            ExceptionRequestVo exception = new ExceptionRequestVo();
            String personNumbers = (String)vos.stream().filter((a) -> {
                return !StringUtils.isEmpty(a.getOrganizationCode());
            }).map(DeptInfoVo::getOrganizationCode).collect(Collectors.joining(","));
            exception.setTaskType(TaskNameEnum.LDEPT.getValue());
            exception.setType(type);
            exception.setErrorReason("");
            exception.setIsSucess(result > 0 ? "是" : "否");
            exception.setTaskName(TaskNameEnum.LDEPT.getName() + "-" + FinalParamUtil.formatDate(new Date()));
            exception.setRequestParam(personNumbers);
            exception.setResponeParam(TaskNameEnum.LDEPT.getName() + OperationEnum.fromVal(operationType).getName() + (result > 0 ? "成功" : "失败"));
            exception.setExcuteDate(new Date());
            exceptionRequestVoList.add(exception);
        }

        countVo.setTotalCount(totalCount);
        countVo.setSuccessTotal(sucessCount);
        if (exceptionRequestVoList.size() > 0) {
            this.exceptionService.insertBatchException(exceptionRequestVoList);
        }

        return countVo;
    }

    private CountVo processTurnSaveAndUpdatePosition(List<PositionVo> infoVos, String operationType, String type, CountVo countVo) {
        int jSONArraySize = infoVos.size();
        int jSONArrayNum = jSONArraySize % 60 == 0 ? jSONArraySize / 60 : jSONArraySize / 60 + 1;
        int jSONArrayStart = 0;
        int jSONArrayEnd = 0;
        int totalCount = 0;
        int sucessCount = 0;
        List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();

        for(int i = 1; i <= jSONArrayNum; ++i) {
              jSONArrayEnd = Math.min(i * 60, jSONArraySize);
              jSONArrayStart = (i - 1) * 60;
            List<PositionVo> vos = infoVos.subList(jSONArrayStart, jSONArrayEnd);
            totalCount += vos.size();
            int result = 0;

            if (operationType.equals(OperationEnum.ADD.getValue())) {
                result = this.positionService.insertBatchPerson(vos);
            } else {
                result = this.positionService.updateBatchPerson(vos);
            }

            sucessCount += vos.size();
            ExceptionRequestVo exception = new ExceptionRequestVo();
            String personNumbers = (String)vos.stream().filter((a) -> {
                return !StringUtils.isEmpty(a.getPositionCode());
            }).map(PositionVo::getPositionCode).collect(Collectors.joining(","));
            exception.setTaskType(TaskNameEnum.LPOSOTION.getValue());
            exception.setType(type);
            exception.setErrorReason("");
            exception.setIsSucess(result > 0 ? "是" : "否");
            exception.setTaskName(TaskNameEnum.LPOSOTION.getName() + "-" + FinalParamUtil.formatDate(new Date()));
            exception.setRequestParam(personNumbers);
            exception.setResponeParam(TaskNameEnum.LPOSOTION.getName() + OperationEnum.fromVal(operationType).getName() + (result > 0 ? "成功" : "失败"));
            exception.setExcuteDate(new Date());
            exceptionRequestVoList.add(exception);
        }

        countVo.setTotalCount(totalCount);
        countVo.setSuccessTotal(sucessCount);
        if (exceptionRequestVoList.size() > 0) {
            this.exceptionService.insertBatchException(exceptionRequestVoList);
        }

        return countVo;
    }

    private CountVo processTurnSaveAndUpdatePersonOffice(List<PersonOfficeVo> infoVos, String operationType, String type, CountVo countVo) {
        int jSONArraySize = infoVos.size();
        int jSONArrayNum = jSONArraySize % 60 == 0 ? jSONArraySize / 60 : jSONArraySize / 60 + 1;
        int jSONArrayStart = 0;
        int jSONArrayEnd = 0;
        int totalCount = 0;
        int sucessCount = 0;
        List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();

        for(int i = 1; i <= jSONArrayNum; ++i) {
              jSONArrayEnd = Math.min(i * 60, jSONArraySize);
              jSONArrayStart = (i - 1) * 60;
            List<PersonOfficeVo> vos = infoVos.subList(jSONArrayStart, jSONArrayEnd);
            totalCount += vos.size();
            int result = 0;

            if (operationType.equals(OperationEnum.ADD.getValue())) {
                result = this.personOfficeService.insertBatchPerson(vos);
            } else {
                result = this.personOfficeService.updateBatchPerson(vos);
            }

            sucessCount += vos.size();
            ExceptionRequestVo exception = new ExceptionRequestVo();
            String personNumbers = (String)vos.stream().filter((a) -> {
                return !StringUtils.isEmpty(a.getPersonNumber());
            }).map(PersonOfficeVo::getPersonNumber).collect(Collectors.joining(","));
            exception.setTaskType(TaskNameEnum.LPERSONHIS.getValue());
            exception.setType(type);
            exception.setErrorReason("");
            exception.setIsSucess(result > 0 ? "是" : "否");
            exception.setTaskName(TaskNameEnum.LPERSONHIS.getName() + "-" + FinalParamUtil.formatDate(new Date()));
            exception.setRequestParam(personNumbers);
            exception.setResponeParam(TaskNameEnum.LPERSONHIS.getName() + OperationEnum.fromVal(operationType).getName() + (result > 0 ? "成功" : "失败"));
            exception.setExcuteDate(new Date());
            exceptionRequestVoList.add(exception);
        }

        countVo.setTotalCount(totalCount);
        countVo.setSuccessTotal(sucessCount);
        if (exceptionRequestVoList.size() > 0) {
            this.exceptionService.insertBatchException(exceptionRequestVoList);
        }

        return countVo;
    }

    private Result saveJobToType(String bigDat, String endDat, String type) {
        Result result = new Result();
        CountVo addCountVo = new CountVo();
        CountVo updateCountVo = new CountVo();

        try {
            Map<String, String> map = new HashMap();
            map.put("startDate", bigDat);
            map.put("endDate", endDat);
            Response response = this.shrClientUtil.sendShr(this.finalParamUtil.getGtiitLocalJobOsfService(), map);
            JSONArray dataArray = JSONArray.parseArray(response.getData().toString());
            if (dataArray.isEmpty()) {
                result.setFlag(false);
                result.setCode(0);
                result.setMessage("当前时间范围内暂无变更的职务数据！");
                return result;
            }

            List<String> shrIds = (List)dataArray.stream().map((obj) -> {
                return ((JSONObject)obj).getString("SHRID");
            }).collect(Collectors.toList());
            List<JobInfoVo> queryLists = this.queryJobList(shrIds);
            Map<String, JobInfoVo> jobInfoVoHashMap = new HashMap();
            if (queryLists != null && queryLists.size() > 0) {
                jobInfoVoHashMap = (Map)queryLists.stream().collect(Collectors.toMap(JobInfoVo::getId, Function.identity(), (v1, v2) -> {
                    return v1;
                }));
            }

            List<JobInfoVo> addJobInfoVos = new ArrayList();
            List<JobInfoVo> updateJobInfoVos = new ArrayList();
            Iterator var15 = dataArray.iterator();

            while(var15.hasNext()) {
                Object data = var15.next();
                JSONObject dataJson = (JSONObject)data;
                JobInfoVo jobInfoVo = new JobInfoVo();
                String shrid = dataJson.getString("SHRID");
                if (((Map)jobInfoVoHashMap).get(shrid) != null) {
                    jobInfoVo = (JobInfoVo)((Map)jobInfoVoHashMap).get(shrid);
                    updateJobInfoVos.add(this.processJob(jobInfoVo, dataJson));
                } else {
                    addJobInfoVos.add(this.processJob(jobInfoVo, dataJson));
                }
            }

            if (addJobInfoVos != null && addJobInfoVos.size() > 0) {
                addCountVo = this.processJobTurnSaveAndUpdate(addJobInfoVos, OperationEnum.ADD.getValue(), type, addCountVo);
            }

            if (updateJobInfoVos != null && updateJobInfoVos.size() > 0) {
                updateCountVo = this.processJobTurnSaveAndUpdate(updateJobInfoVos, OperationEnum.UPDATE.getValue(), type, updateCountVo);
            }
        } catch (Exception var20) {
            return new Result(false, 0, "系统报错,报错信息为：" + var20.getMessage());
        }

        result.setFlag(true);
        result.setCode(1);
        result.setMessage("操作成功，总条数为：" + (addCountVo.getTotalCount() + updateCountVo.getTotalCount()) + "，新增了" + addCountVo.getSuccessTotal() + "条，更新了" + updateCountVo.getSuccessTotal() + "条");
        return result;
    }

    private JobInfoVo processJob(JobInfoVo jobInfoVo, JSONObject dataJson) {
        jobInfoVo.setId(dataJson.getString("SHRID"));
        jobInfoVo.setJobCode(dataJson.getString("JOB_CODE"));
        jobInfoVo.setJobNameCn(dataJson.getString("JOB_NAME_CN"));
        jobInfoVo.setJobNameEn(dataJson.getString("JOB_NAME_EN"));
        jobInfoVo.setApprovalAuthority(dataJson.getString("APPROVAL_AUTHORITY"));
        jobInfoVo.setErpCreationDate(dataJson.getString("ERP_CREATION_DATE"));
        jobInfoVo.setErpLastUpdateDate(dataJson.getString("ERP_LAST_UPDATE_DATE"));
        return jobInfoVo;
    }

    private List<JobInfoVo> queryJobList(List<String> shrIds) {
        List<JobInfoVo> jobInfoVos = new ArrayList();
        int jSONArraySize = shrIds.size();
        int jSONArrayNum = jSONArraySize % 1000 == 0 ? jSONArraySize / 1000 : jSONArraySize / 1000 + 1;
        int jSONArrayStart = 0;
        int jSONArrayEnd = 0;

        for(int i = 1; i <= jSONArrayNum; ++i) {
              jSONArrayEnd = Math.min(i * 1000, jSONArraySize);
              jSONArrayStart = (i - 1) * 1000;
            List<String> ids = shrIds.subList(jSONArrayStart, jSONArrayEnd);
            Result page = this.jobService.findPage(ids);
            if (page.getData() != null) {
                jobInfoVos.addAll((List)page.getData());
            }
        }

        return jobInfoVos;
    }

    private CountVo processJobTurnSaveAndUpdate(List<JobInfoVo> jobInfoVos, String operationType, String type, CountVo countVo) {
        int jSONArraySize = jobInfoVos.size();
        int jSONArrayNum = jSONArraySize % 60 == 0 ? jSONArraySize / 60 : jSONArraySize / 60 + 1;
        int jSONArrayStart = 0;
        int jSONArrayEnd = 0;
        int totalCount = 0;
        int sucessCount = 0;
        List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();

        for(int i = 1; i <= jSONArrayNum; ++i) {
              jSONArrayEnd = Math.min(i * 60, jSONArraySize);
              jSONArrayStart = (i - 1) * 60;
            List<JobInfoVo> jobs = jobInfoVos.subList(jSONArrayStart, jSONArrayEnd);
            totalCount += jobs.size();
            int result = 0;

            if (operationType.equals(OperationEnum.ADD.getValue())) {
                result = this.jobService.insertBatchJob(jobs);
            } else {
                result = this.jobService.updateBatchJob(jobs);
            }

            sucessCount += jobs.size();
            ExceptionRequestVo exception = new ExceptionRequestVo();
            String personNumbers = (String)jobs.stream().filter((a) -> {
                return !StringUtils.isEmpty(a.getJobCode());
            }).map((a) -> {
                return a.getJobCode();
            }).collect(Collectors.joining(","));
            exception.setTaskType(TaskNameEnum.LJOB.getValue());
            exception.setType(type);
            exception.setErrorReason("");
            exception.setIsSucess(result > 0 ? "是" : "否");
            StringBuilder var10001 = (new StringBuilder()).append(TaskNameEnum.LJOB.getName()).append("-");
            FinalParamUtil var10002 = this.finalParamUtil;
            exception.setTaskName(var10001.append(FinalParamUtil.formatDate(new Date())).toString());
            exception.setRequestParam(personNumbers);
            exception.setResponeParam(TaskNameEnum.LJOB.getName() + OperationEnum.fromVal(operationType).getName() + (result > 0 ? "成功" : "失败"));
            exception.setExcuteDate(new Date());
            exceptionRequestVoList.add(exception);
        }

        countVo.setTotalCount(totalCount);
        countVo.setSuccessTotal(sucessCount);
        if (exceptionRequestVoList != null && exceptionRequestVoList.size() > 0) {
            this.exceptionService.insertBatchException(exceptionRequestVoList);
        }

        return countVo;
    }

    public String formatDate(String dateStr, boolean isStart) throws ParseException {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = inputFormat.parse(dateStr);
        SimpleDateFormat outputFormat;
        if (isStart) {
            outputFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        } else {
            outputFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        }

        return outputFormat.format(date);
    }
}
