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.vo.CountVo;
import com.gtiit.shr.entity.vo.ExceptionRequestVo;
import com.gtiit.shr.service.AttendanceClockInService;
import com.gtiit.shr.service.ExceptionService;
import com.gtiit.shr.utils.FinalParamUtil;
import com.gtiit.shr.utils.HttpUtils;
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.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Transactional
public class AttendanceClockInServiceImpl implements AttendanceClockInService {
    @Autowired
    ExceptionService exceptionService;
    @Autowired
    FinalParamUtil finalParamUtil;
    String typeName = "1";
    @Value("${scheduled.attendance.able}")
    private String cronStatus;
    String accessToken = "";



    @Scheduled(
            cron = "${scheduled.attendance.cron}"
    )
    public void doAttendanceClock() throws IOException {
        if (TaskStatusEnum.ABLE.getValue().equals(this.cronStatus)) {
            this.processArrendance((String)null, (String)null, (String)null, "2");
        }

    }

    public Result doAttendanceClock(String bigDat, String endDat, String attNum) throws IOException {
        return this.processArrendance(bigDat, endDat, attNum, "1");
    }

    private Result processArrendance(String bigDat, String endDat, String attNum, String type) {
        Result result = new Result();
        CountVo countVo = new CountVo();

        try {
            SHRClient sHRClient = new SHRClient();
            Token token = sHRClient.loginShrByUser(this.finalParamUtil.getShrUrl());
            ExceptionRequestVo exceptionRequestVo = new ExceptionRequestVo();
            result.setCode(1);
            Date date = new Date();
            SimpleDateFormat dat = new SimpleDateFormat("yyyy-MM-dd");
            new SimpleDateFormat("HH:mm:ss");
            LocalDate localDate = LocalDate.parse(dat.format(date), DateTimeFormatter.ISO_LOCAL_DATE);
            LocalDate yesterday = localDate.minusDays(1L);
            String yesterdayDat = yesterday.format(DateTimeFormatter.ISO_LOCAL_DATE);
            String toDat = dat.format(date);
            if (!StringUtils.isEmpty(bigDat) && !StringUtils.isEmpty(endDat)) {
                yesterdayDat = bigDat;
                toDat = endDat;
            }

            this.getToken();
            JSONArray attDatas = new JSONArray();
            String getAttNumberUrl = this.finalParamUtil.getAttNumber() + yesterdayDat + "/" + toDat + "/";
            if (!StringUtils.isEmpty(attNum)) {
                getAttNumberUrl = this.finalParamUtil.getAttNumber() + yesterdayDat + "/" + toDat + "/?user_num=" + attNum;
            }

            String attList = HttpUtils.HttpGet(getAttNumberUrl, this.accessToken);
            JSONObject jsonObjectx = JSONObject.parseObject(attList);
            if (!"1000".equals(jsonObjectx.get("code") + "")) {
                exceptionRequestVo.setTaskName("考勤打卡接口获取数据失败");
                exceptionRequestVo.setTaskType(TaskNameEnum.ATTENDANCE.getValue());
                exceptionRequestVo.setType(type);
                exceptionRequestVo.setExcuteDate(new Date());
                exceptionRequestVo.setErrorReason("错误日志:" + jsonObjectx);
                exceptionRequestVo.setIsSucess("否");
                exceptionRequestVo.setRequestParam(getAttNumberUrl);
                exceptionRequestVo.setResponeParam(jsonObjectx.toString());
                this.exceptionService.insertException(exceptionRequestVo);
                result.setData("请求错误，接口返回错误数据:" + jsonObjectx);
                result.setMessage("请求错误，接口返回错误数据:" + jsonObjectx);
                result.setCode(0);
                return result;
            }

            attDatas.addAll(JSONObject.parseArray(jsonObjectx.getString("data")));
            List<ExceptionRequestVo> exceptionList = new ArrayList();
            int jSONArraySize = attDatas.size();
            int jSONArrayNum = jSONArraySize % 50 == 0 ? jSONArraySize / 50 : jSONArraySize / 50 + 1;
            int jSONArrayStart = 0;
            int jSONArrayEnd = 0;

            for(int i = 1; i <= jSONArrayNum; ++i) {
                 jSONArrayEnd = Math.min(i * 50, jSONArraySize);
                 jSONArrayStart = (i - 1) * 50;
                List<Object> objects = attDatas.subList(jSONArrayStart, jSONArrayEnd);
                JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(objects));
                ExceptionRequestVo exception = this.processExcuteToshr(jsonArray, token, sHRClient, type, countVo);
                exceptionList.add(exception);
            }

            this.exceptionService.insertBatchException(exceptionList);
            result.setMessage("操作成功，同步成功" + countVo.getSuccessTotal() + "条,失败" + (countVo.getTotalCount() - countVo.getSuccessTotal()) + "条,考勤打卡接口返回数据格式错误的有" + countVo.getNullTotal() + "条");
        } catch (Exception var30) {
            var30.getMessage();
        }

        return result;
    }

    private ExceptionRequestVo processExcuteToshr(JSONArray attDatas, Token token, SHRClient sHRClient, String type, CountVo countVo) throws IOException {
        ExceptionRequestVo exception = new ExceptionRequestVo();
        Map<String, Object> param = new HashMap();
        List<Object> paramList = new ArrayList();
        String error = "";

        JSONObject json;
        for(int i = 0; i < attDatas.size(); ++i) {
            System.out.println("总共" + attDatas.size() + "条数据,正在同步:" + (i + 1) + "条");
            json = JSONObject.parseObject(attDatas.get(i).toString());
            Map<String, String> paramMap = new HashMap();
            paramMap.put("EquNo", json.getString("equ_no"));
            String userNum = json.getString("user_num");
            if (StringUtils.isEmpty(userNum)) {
                countVo.setNullTotal(countVo.getNullTotal() + 1);
            } else {
                paramMap.put("CardId", userNum);
                paramMap.put("RecDate", json.getString("rec_date"));
                paramMap.put("RecTime", json.getString("rec_time"));
                paramList.add(paramMap);
            }
        }

        param.put("records", JSON.toJSONString(paramList));
        System.out.println("param..........." + JSON.toJSONString(param));
        System.out.println("param..........." + JSON.parseArray(param.get("records").toString()));
        Response res = sHRClient.executeOSFService(this.finalParamUtil.getShrUrl(), token, this.finalParamUtil.getTransmitPunchCardRecord(), param);
        System.out.println("res............" + res.getData());
        json = JSON.parseObject(res.getData().toString());
        Integer success = Integer.valueOf(json.get("successCtn").toString());
        System.out.println("同步成功的条数：" + success);
        JSONArray formatErrorRecords = JSON.parseArray(json.get("formatErrorRecords").toString());
        System.out.println("数据为空或数据格式不对：" + formatErrorRecords);
        JSONArray notExistRecords = JSON.parseArray(json.get("notExistRecords").toString());
        System.out.println("匹配不上考勤档案的：" + notExistRecords);
        JSONArray duplicateRecords = JSON.parseArray(json.get("duplicateRecords").toString());
        System.out.println("重复的数据：" + duplicateRecords);
        Integer recordCtn = Integer.valueOf(json.get("recordCtn").toString());
        System.out.println("同步总条数：" + recordCtn);
        String notExistRecord = (String)JSONArray.parseArray(notExistRecords.toString(), Map.class).stream().map((a) -> {
            return (String)a.get("CardId");
        }).collect(Collectors.joining(","));
        String formatErrorRecord = (String)JSONArray.parseArray(formatErrorRecords.toString(), Map.class).stream().map((a) -> {
            return (String)a.get("CardId");
        }).collect(Collectors.joining(","));
        String duplicateRecord = (String)JSONArray.parseArray(duplicateRecords.toString(), Map.class).stream().map((a) -> {
            return (String)a.get("CardId");
        }).collect(Collectors.joining(","));
        error = "同步总条数：" + recordCtn + ",成功条数为：" + success + "";
        if (StringUtils.hasLength(formatErrorRecord)) {
            error = error + ",数据格式错误的为：" + formatErrorRecord + "";
        }

        if (StringUtils.hasLength(duplicateRecord)) {
            error = error + ",重复的数据的为：" + duplicateRecord + "";
        }

        if (StringUtils.hasLength(notExistRecord)) {
            error = error + "考勤档案不存在的为：" + notExistRecord + "";
        }

        countVo.setTotalCount(countVo.getTotalCount() + recordCtn);
        countVo.setSuccessTotal(countVo.getSuccessTotal() + success);
        exception.setTaskType(TaskNameEnum.ATTENDANCE.getValue());
        exception.setType(type);
        exception.setErrorReason(error);
        exception.setIsSucess(success > 0 ? "是" : "否");
        StringBuilder var10001 = (new StringBuilder()).append(TaskNameEnum.ATTENDANCE.getName()).append("-");
        FinalParamUtil var10002 = this.finalParamUtil;
        exception.setTaskName(var10001.append(FinalParamUtil.formatDate(new Date())).toString());
        exception.setRequestParam(param.toString());
        exception.setResponeParam(json.toString());
        exception.setExcuteDate(new Date());
        return exception;
    }

    public JSONArray getAttendAllNumService() throws IOException {
        Map map = new HashMap();
        String serviceName = "attendAllNumService";
        SHRClient client = new SHRClient();
        Response res = client.executeService(this.finalParamUtil.getShrUrl(), serviceName, map);
        JSONArray objects = JSONObject.parseArray(JSONObject.parse(res.getData().toString()).toString());
        return objects;
    }

    public void getToken() {
        try {
            Map mapBody = new HashMap();
            mapBody.put("username", this.finalParamUtil.getUsername());
            mapBody.put("password", this.finalParamUtil.getPassWord());
            String post = HttpUtils.post(this.finalParamUtil.getTokenUrl(), JSONObject.toJSONString(mapBody));
            JSONObject jsonObject = JSONObject.parseObject(post);
            this.accessToken = jsonObject.getString("access");
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }

        if ("".equals(this.accessToken)) {
            throw new RuntimeException("token为空获取失败");
        }
    }
}
