package com.gtiit.shr.service.impl;

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.SynOrgAndDeptService;
import com.gtiit.shr.utils.FinalParamUtil;
import com.gtiit.shr.utils.OATokenUtil;
import com.kingdee.shr.api.Response;
import com.kingdee.shr.api.SHRClient;
import com.kingdee.shr.api.Token;
import java.io.IOException;
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.Set;
import org.apache.axis.utils.StringUtils;
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;

@Service
@Transactional
public class SynOrgAndDeptServiceImpl implements SynOrgAndDeptService {
    @Autowired
    private FinalParamUtil finalParamUtil;
    @Autowired
    private OATokenUtil oaTokenUtil;
    @Autowired
    ExceptionService exceptionService;
    @Value("${scheduled.org.able}")
    private String deptcronStatus;
    @Value("${scheduled.position.able}")
    private String positioncronStatus;
    Token token = null;



    @Scheduled(
            cron = "${scheduled.org.cron}"
    )
    public void SynOrg() throws Exception {
        if (TaskStatusEnum.ABLE.getValue().equals(this.deptcronStatus)) {
            FinalParamUtil var10001 = this.finalParamUtil;
            String var1 = FinalParamUtil.getBeforeOneDay(new Date());
            FinalParamUtil var10002 = this.finalParamUtil;
            this.synOrgToType(var1, FinalParamUtil.formatDate(new Date()), TypeEnum.AUTO.getValue());
        }

    }

    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();
        this.token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
        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系统请求报错，报错信息为：" + var31.getMessage());
        }

        Map<String, Object> mapBody = new HashMap();
        ArrayList<Map<String, String>> listBody = new ArrayList();
        Map<String, Object> paramMap = new HashMap();

        JSONObject result1;
        for(int i = 0; i < jsonAdmArr.size(); ++i) {
            JSONObject jsonObject = JSONObject.parseObject(jsonAdmArr.get(i).toString());
            HashMap<String, String> stringStringHashMap = new HashMap();
            stringStringHashMap.put("superior", jsonObject.getString("superior"));
            stringStringHashMap.put("easdept_id", jsonObject.getString("easdept_id"));
            stringStringHashMap.put("type", "admin");
            String shortname = jsonObject.getString("simpleName");
            if (StringUtils.isEmpty(shortname)) {
                shortname = jsonObject.getString("name");
            }

            HashMap mpBody = new HashMap();
            mpBody.put("@action", "add");
            mpBody.put("code", jsonObject.getString("fnumber"));
            mpBody.put("shortname", shortname);
            mpBody.put("fullname", "~`~`7 " + jsonObject.getString("name") + "`~`8 " + jsonObject.getString("name_L1") + "`~`~");
            mpBody.put("parent_code", jsonObject.getString("supFnumber"));
            mpBody.put("org_code", this.finalParamUtil.getSubcompanycode());
            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("custom_data", result1);
            listBody.add(mpBody);
            paramMap.put(jsonObject.getString("fnumber"), mpBody);
        }

        if (listBody.size() == 0) {
            return new Result(false, 0, "当前时间范围内未找到组织的变动记录");
        } else {
            mapBody.put("data", listBody);
            Map<String, String> ruleMap = new HashMap();
            ruleMap.put("subcompnay", "subcompanycode");
            ruleMap.put("department", "departmentcode");
            ruleMap.put("resource", "workcode");
            ruleMap.put("jobtitle", "jobtitlecode");
            mapBody.put("rule", ruleMap);
            String sendAPIByAddAdmin = "";

            try {
                sendAPIByAddAdmin = this.oaTokenUtil.restful("/api/hrm/resful/synDepartment", JSONObject.toJSONString(mapBody), "sendAPIByAddAdmin");
            } catch (Exception var30) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + var30.getMessage());
            }

            System.out.println("日志打印：" + sendAPIByAddAdmin);
            Integer sucessCount = 0;
            JSONObject jsonObject = JSONObject.parseObject(sendAPIByAddAdmin);
            if ("-1".equals(jsonObject.getString("code"))) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + jsonObject.getString("msg"));
            } else {
                List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();
                result1 = jsonObject.getJSONObject("result");
                int batchSize = 100;
                Set<String> keySet = result1.keySet();
                List<String> keyList = new ArrayList(keySet);
                int totalSize = keyList.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<String> subkeyList = keyList.subList(startIndex, endIndex);
                    Iterator var26 = subkeyList.iterator();

                    while(var26.hasNext()) {
                        String key = (String)var26.next();
                        JSONObject jsonObject1 = result1.getJSONObject(key);
                        jsonObject1.getString("msg");
                        jsonObject1.getString("code");
                        ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                        exceptionRequestVo.setTaskName("OA部门同步-" + key + "-" + (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("msg"));
                        exceptionRequestVo.setIsSucess("否");
                        if ("1".equals(jsonObject1.getString("code"))) {
                            exceptionRequestVo.setIsSucess("是");
                            sucessCount = sucessCount + 1;
                        }

                        exceptionRequestVo.setRequestParam(JSON.toJSONString(paramMap.get(key)));
                        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("操作成功,同步成功" + sucessCount + ",失败" + (listBody.size() - sucessCount) + "条");
                return result;
            }
        }
    }

    @Scheduled(
            cron = "${scheduled.position.cron}"
    )
    public void SynPosition() throws Exception {
        if (TaskStatusEnum.ABLE.getValue().equals(this.positioncronStatus)) {
            FinalParamUtil var10001 = this.finalParamUtil;
            var10001 = this.finalParamUtil;
            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();
        this.token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
        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系统请求报错，报错信息为：" + var29.getMessage());
        }

        Map<String, ArrayList<Map<String, String>>> mapBody = new HashMap();
        ArrayList<Map<String, String>> listBody = new ArrayList();
        Map<String, Object> paramMap = new HashMap();

        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) {
                HashMap<String, String> stringStringHashMap = new HashMap();
                stringStringHashMap.put("superior", "");
                stringStringHashMap.put("easdept_id", jsonObject.getString("eas_id"));
                stringStringHashMap.put("type", "position");
                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 jobtitleremark = "";
                if (!StringUtils.isEmpty(orgName) && "true".equals(this.finalParamUtil.getIsJobTitlePrefixed())) {
                    jobtitleremark = "~`~`7 " + orgName + "-" + name + "`~`8 " + orgName + "-" + namel1 + "`~`~";
                } else {
                    jobtitleremark = "~`~`7 " + name + "`~`8 " + namel1 + "`~`~";
                }

                String jobtitlename = "~`~`7 " + longNamel2 + "`~`8 " + longNamel1 + "`~`~";
                if (StringUtils.isEmpty(longNamel1) || StringUtils.isEmpty(longNamel2)) {
                    jobtitlename = jobtitleremark;
                }

                HashMap mpBody = new HashMap();
                mpBody.put("@action", "add");
                mpBody.put("jobtitlecode", jsonObject.getString("fnumber"));
                mpBody.put("jobtitlename", jobtitlename);
                mpBody.put("jobtitleremark", jobtitleremark);
                listBody.add(mpBody);
                paramMap.put(jsonObject.getString("fnumber"), mpBody);
            }
        }

        if (listBody.size() == 0) {
            return new Result(false, 0, "当前时间范围内未找到岗位的变动记录");
        } else {
            mapBody.put("data", listBody);
            String sendAPIByAddAdmin = "";

            try {
                sendAPIByAddAdmin = this.oaTokenUtil.restful("/api/hrm/resful/synJobtitle", JSONObject.toJSONString(mapBody), "sendAPIByAddPosition");
            } catch (Exception var28) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + var28.getMessage());
            }

            System.out.println("日志打印：" + sendAPIByAddAdmin);
            Integer sucessCount = 0;
            JSONObject jsonObject = JSONObject.parseObject(sendAPIByAddAdmin);
            List<ExceptionRequestVo> exceptionRequestVoList = new ArrayList();
            if ("-1".equals(jsonObject.getString("code"))) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + jsonObject.getString("msg"));
            } else {
                JSONObject result1 = jsonObject.getJSONObject("result");
                int batchSize = 100;
                Set<String> keySet = result1.keySet();
                List<String> keyList = new ArrayList(keySet);
                int totalSize = keyList.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<String> subkeyList = keyList.subList(startIndex, endIndex);
                    Iterator var24 = subkeyList.iterator();

                    while(var24.hasNext()) {
                        String key = (String)var24.next();
                        JSONObject jsonObject1 = result1.getJSONObject(key);
                        jsonObject1.getString("msg");
                        jsonObject1.getString("code");
                        ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                        exceptionRequestVo.setTaskName("OA岗位同步-" + key + "-" + (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("msg"));
                        exceptionRequestVo.setIsSucess("否");
                        if ("1".equals(jsonObject1.getString("code"))) {
                            exceptionRequestVo.setIsSucess("是");
                            sucessCount = sucessCount + 1;
                        }

                        exceptionRequestVo.setRequestParam(JSON.toJSONString(paramMap.get(key)));
                        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("操作成功,同步成功" + sucessCount + ",失败" + (listBody.size() - sucessCount) + "条");
                return result;
            }
        }
    }

    public Response getOSFData(String OsfName, Map map) throws IOException {
        SHRClient client = new SHRClient();
        return client.executeOSFService(this.finalParamUtil.getShrUrl(), this.token, OsfName, map);
    }
}
