package com.gtiit.shr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
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.vo.ExceptionRequestVo;
import com.gtiit.shr.service.ExceptionService;
import com.gtiit.shr.service.SynPersonService;
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 java.io.IOException;
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 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 org.springframework.util.StringUtils;

@Service
@Transactional
public class SynPersonServiceImpl implements SynPersonService {
    @Autowired
    ExceptionService exceptionService;
    @Autowired
    FinalParamUtil finalParamUtil;
    @Autowired
    OATokenUtil oaTokenUtil;
    @Value("${scheduled.person.able}")
    private String cronStatus;
    @Value("${api.oa.statusmap}")
    private String statusmap;



    public Result synPerson(String startDate, String endDate, String personNumber) throws Exception {
        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系统请求报错，报错信息为：" + var8.getMessage());
        }

        JSONObject shrResultJson = JSONObject.parseObject(resultString);
        if (!StringUtils.isEmpty(shrResultJson) && "error".equals(shrResultJson.getString("result"))) {
            return new Result(false, 0, shrResultJson.getString("summary"));
        } else if (shrResultJson.getString("code").equals("1") && shrResultJson.getJSONArray("data").size() > 0) {
            return this.sendOA(shrResultJson, "1");
        } else {
            Result result = new Result();
            result.setMessage("shr端暂无变更的人员信息！");
            return result;
        }
    }

    private Result sendOA(JSONObject shrResultJson, String type) {
        JSONObject STATUS_MAP = JSON.parseObject(this.statusmap);
        Map<String, JSONObject> requestMap = new HashMap();
        JSONArray dataJsonArray = (JSONArray)shrResultJson.get("data");
        Iterator var6 = dataJsonArray.iterator();

        JSONObject requestJson;
        while(var6.hasNext()) {
            Object obj = var6.next();
            requestJson = (JSONObject)obj;
            requestJson.put("subcompany", "{JSON}{\"subcompanycode\": \"" + this.finalParamUtil.getSubcompanycode() + "\"}");
            requestJson.put("jobgroupid", "GTIIT");
            requestJson.put("locationid", "汕头");
            requestJson.put("systemlanguage", "English");
            requestJson.put("status", StringUtils.isEmpty(STATUS_MAP.get(requestJson.getString("status"))) ? "" : STATUS_MAP.get(requestJson.getString("status")));
            requestMap.put(requestJson.getString("workcode"), requestJson);
        }

        JSONArray dataArray = shrResultJson.getJSONArray("data");
        JSONObject rule = new JSONObject();
        rule.put("resource", "workcode");
        requestJson = new JSONObject();
        requestJson.put("rule", rule);
        int jSONArraySize = dataArray.size();
        int jSONArrayNum = jSONArraySize % 100 == 0 ? jSONArraySize / 100 : jSONArraySize / 100 + 1;

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

        for(int i = 1; i <= jSONArrayNum; ++i) {
            int jSONArrayEnd = Math.min(i * 100, jSONArraySize);
            int jSONArrayStart = (i - 1) * 100;
            List<Object> objects = dataArray.subList(jSONArrayStart, jSONArrayEnd);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(objects));
            requestJson.put("data", jsonArray);
            String sendAPIByAddPerson = "";

            try {
                sendAPIByAddPerson = this.oaTokenUtil.restful("/api/hrm/resful/synHrmresource", JSONObject.toJSONString(requestJson, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), "sendAPIByAddPerson");
            } catch (Exception var27) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + var27.getMessage());
            }

            JSONObject oaResultJson = JSON.parseObject(sendAPIByAddPerson);
            if ("-1".equals(oaResultJson.getString("code"))) {
                return new Result(false, 0, "OA系统请求报错，报错信息为：" + oaResultJson.getString("msg"));
            }

            JSONObject oaResultJson_result = oaResultJson.getJSONObject("result");
            if (oaResultJson_result != null) {
                Iterator var22 = oaResultJson_result.entrySet().iterator();

                while(var22.hasNext()) {
                    Map.Entry<String, Object> entry = (Map.Entry)var22.next();
                    JSONObject result_info = (JSONObject)entry.getValue();
                    Long code = result_info.getLong("code");
                    ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
                    exceptionRequestVo.setTaskType(oaStaff.getValue());
                    exceptionRequestVo.setTaskName(oaStaff.getName());
                    exceptionRequestVo.setExcuteDate(new Date());
                    exceptionRequestVo.setType(type);
                    exceptionRequestVo.setIsSucess("是");
                    if (code == -1L) {
                        ++errorSize;
                        exceptionRequestVo.setIsSucess("否");
                    }

                    exceptionRequestVo.setRequestParam(((JSONObject)requestMap.get(entry.getKey())).toJSONString());
                    exceptionRequestVo.setResponeParam(result_info.toJSONString());
                    exceptionRequestVo.setErrorReason(result_info.getString("msg"));
                    exceptionRequestVoList.add(exceptionRequestVo);
                }

                int result = this.exceptionService.insertBatchException(exceptionRequestVoList);
                if (result > 0) {
                    exceptionRequestVoList.clear();
                }
            }
        }

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

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

    @Scheduled(
            cron = "${scheduled.person.cron}"
    )
    public void scheduledSynPerson() throws IOException {
        if (TaskStatusEnum.ABLE.getValue().equals(this.cronStatus)) {
            Map<String, String> param = new HashMap();
            FinalParamUtil var10002 = this.finalParamUtil;
            param.put("startDate", FinalParamUtil.getBeforeOneDay(new Date()));
            var10002 = this.finalParamUtil;
            param.put("endDate", FinalParamUtil.formatDate(new Date()));
            param.put("personNumber", "");
            String resultString = this.getOSFData(this.finalParamUtil.getSynPersonService(), param).getData().toString();
            JSONObject shrResultJson = JSONObject.parseObject(resultString);
            if (shrResultJson.getString("code").equals("1") && shrResultJson.getJSONArray("data").size() > 0) {
                this.sendOA(shrResultJson, "2");
            }
        }

    }
}
