//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.kingdee.eas.custom.szpgm.osf.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.bsf.service.app.IHRMsfService;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.tool.function.Strings;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.hr.ats.AttendanceEquipmentFactory;
import com.kingdee.eas.hr.ats.AttendanceEquipmentInfo;
import com.kingdee.eas.hr.ats.AttendanceFileFactory;
import com.kingdee.eas.hr.ats.AttendanceFileInfo;
import com.kingdee.eas.hr.ats.PunchCardRecordCollection;
import com.kingdee.eas.hr.ats.PunchCardRecordFactory;
import com.kingdee.eas.hr.ats.PunchCardRecordInfo;
import com.kingdee.eas.hr.ats.PunchCardSourceEnum;
import com.kingdee.shr.ats.web.util.HRTimeWebUtils;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;

public class CardToShrOSFService implements IHRMsfService {
    private static Logger logger = Logger.getLogger(CardToShrOSFService.class);
    private static final String TIME_RANGE = "timeRange";
    private static final String STOP = "stop";
    private static final String RESTART = "ReStart";
    private static final String SPEND_FACE = "刷脸";

    public Object process(Context ctx, Map param) throws EASBizException, BOSException {
        System.out.println("同步打卡记录开始---------------------------------------------------------------------------------------");
        Map retMap = new HashMap();
        JSONArray formatErrorRecords = new JSONArray();
        JSONArray notExistRecords = new JSONArray();
        JSONArray duplicateRecords = new JSONArray();
        int recordCtn = 0;
        int successCtn = 0;
        String url = (String)param.get("url");
        String sign = (String)param.get("sign");
        String forwardHour = (String)param.get("forwardHour");
        String startDate = (String)param.get("startDate");
        String endDate = (String)param.get("endDate");
        String empNo = (String)param.get("empNo");
        String minusMinutes = (String)param.get("minusMinutes");
        String size = (String)param.get("size");
        LocalDateTime startTime = LocalDateTime.now();
        LocalDateTime endTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        try {
            if (StrUtil.isNotBlank(startDate)) {
                if (startDate.length() > 10) {
                    startTime = LocalDateTime.parse(startDate, formatter);
                } else {
                    LocalDate localDate = LocalDate.parse(startDate, DateTimeFormatter.ISO_LOCAL_DATE);
                    startTime = LocalDateTime.of(localDate, LocalTime.MIN);
                }
            } else if (StrUtil.isNotBlank(minusMinutes)) {
                startTime = startTime.minusMinutes((long)Integer.parseInt(minusMinutes));
            } else {
                startTime = startTime.minusMinutes(5L);
            }

            if (StrUtil.isNotBlank(forwardHour)) {
                startTime = startTime.minusHours((long)Integer.parseInt(forwardHour));
            }

            if (StrUtil.isNotBlank(endDate)) {
                if (startDate.length() > 10) {
                    endTime = LocalDateTime.parse(endDate, formatter);
                } else {
                    LocalDate localDate = LocalDate.parse(endDate, DateTimeFormatter.ISO_LOCAL_DATE);
                    endTime = LocalDateTime.of(localDate, LocalTime.MAX);
                }
            }
        } catch (Exception e) {
            System.out.println("日期格式化异常");
            e.printStackTrace();
        }

        int pageIndex = 0;
        int pageSize = 200;
        if (StrUtil.isNotBlank(size)) {
            pageSize = Integer.parseInt(size);
        }

        int code = 0;
        boolean end = false;
        int pageCount = 0;

        try {
            do {
                ++pageIndex;
                Map<String, Object> paramMap = new HashMap();
                paramMap.put("recordStartDate", startTime.format(formatter));
                paramMap.put("recordEndDate", endTime.format(formatter));
                paramMap.put("pageIndex", pageIndex);
                paramMap.put("pageSize", pageSize);
                paramMap.put("timestamp", System.currentTimeMillis() / 1000L);
                if (StrUtil.isNotBlank(empNo)) {
                    paramMap.put("empNo", empNo);
                }

                paramMap.put("sign", SignUtil.generateSignature(paramMap, sign));
                String jsonResult = null;

                try {
                    paramMap.put("url", url);
                    System.out.println("同步打卡记录参数：" + JSON.toJSONString(paramMap));
                    jsonResult = HttpUtil.post(url, JSON.toJSONString(paramMap));
                    System.out.println("请求结果：" + jsonResult);
                } catch (Exception e) {
                    logger.error("请求异常", e);
                    e.printStackTrace();
                }

                try {
                    if (!StrUtil.isNotBlank(jsonResult)) {
                        code = 1;
                        System.out.println("没有数据");
                    } else {
                        JSONObject jsonObject = JSONObject.parseObject(jsonResult);
                        code = jsonObject.getInteger("code");
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (0 == code && null != data) {
                            pageCount = data.getInteger("pageCount");
                            JSONArray datalist = data.getJSONArray("datalist");
                            JSONArray recordsJson = new JSONArray();
                            recordCtn += datalist.size();

                            for(int i = 0; i < datalist.size(); ++i) {
                                JSONObject record = datalist.getJSONObject(i);
                                String eventType = record.getString("eventType");
                                if ("刷脸".equals(eventType)) {
                                    String EquNo = record.getString("devId");
                                    EquNo = EquNo.replaceAll(" ", "");
                                    record.put("EquNo", EquNo);
                                    String CardId = record.getString("empNo");
                                    CardId = CardId.replaceAll(" ", "");
                                    record.put("CardId", CardId);
                                    String recordTime = record.getString("recordTime");
                                    recordTime = recordTime.replaceAll("/", "-");
                                    String[] Recs = recordTime.split(" ");
                                    String RecDate = Recs[0];
                                    String RecTime = Recs[1];
                                    if (!RecTime.startsWith("0")) {
                                        RecTime = "0" + RecTime;
                                    }

                                    record.put("RecDate", RecDate);
                                    record.put("RecTime", RecTime);
                                    record.put("Address", record.getString("devName"));
                                    recordsJson.add(record);
                                } else {
                                    notExistRecords.add(record);
                                }
                            }

                            try {
                                System.out.println(recordsJson.toJSONString());
                                Map<String, Object> ret = this.saveCards(ctx, recordsJson);
                                successCtn += (Integer)ret.get("successCtn");
                                formatErrorRecords.addAll((JSONArray)ret.get("formatErrorRecords"));
                                notExistRecords.addAll((JSONArray)ret.get("notExistRecords"));
                            } catch (Exception e) {
                                logger.error("数据保存异常", e);
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("保存打卡记录异常", e);
                }
            } while(pageIndex <= pageCount && 0 == code);
        } catch (Exception e) {
            logger.error("处理数据异常", e);
            e.printStackTrace();
        }

        retMap.put("recordCtn", recordCtn);
        retMap.put("successCtn", successCtn);
        retMap.put("formatErrorRecords", formatErrorRecords);
        retMap.put("notExistRecords", notExistRecords);
        retMap.put("duplicateRecords", duplicateRecords);
        System.out.println("同步打卡记录结束---------------------------------------------------------------------------------------");
        return retMap;
    }

    public Map saveCards(Context ctx, JSONArray recordsJson) throws BOSException, EASBizException {
        Map retMap = new HashMap();
        retMap.put("recordCtn", recordsJson.size());
        Set<String> EquNoSet = new HashSet();
        Set<String> setCardId = new HashSet();
        Timestamp minDateTime = null;
        Timestamp maxDateTime = null;
        JSONArray formatErrorRecords = new JSONArray();
        JSONArray notExistRecords = new JSONArray();
        JSONArray duplicateRecords = new JSONArray();
        CoreBaseCollection cardColl = new CoreBaseCollection();

        for(int i = 0; i < recordsJson.size(); ++i) {
            JSONObject jsonObject = recordsJson.getJSONObject(i);
            String EquNo = Strings.nullAsEmpty(jsonObject.getString("EquNo"));
            String CardId = Strings.nullAsEmpty(jsonObject.getString("CardId"));
            String RecDate = Strings.nullAsEmpty(jsonObject.getString("RecDate"));
            String RecTime = Strings.nullAsEmpty(jsonObject.getString("RecTime"));
            String Address = Strings.nullAsEmpty(jsonObject.getString("Address"));
            Date punchCardDate = HRTimeWebUtils.stringToShortDate(RecDate, true);
            Timestamp punchCardTime = HRTimeWebUtils.stringToTimestamp(RecDate + " " + RecTime, true);
            if (!"".equals(EquNo) && !"".equals(CardId) && punchCardDate != null && punchCardTime != null) {
                PunchCardRecordInfo cardInfo = new PunchCardRecordInfo();
                cardInfo.setEquipmentNum(EquNo);
                cardInfo.setAttendanceNum(CardId);
                cardInfo.setPunchCardDate(punchCardDate);
                cardInfo.setPunchCardTime(punchCardTime);
                cardInfo.setPunchCardPlace(Address);
                cardInfo.setPunchCardSource(PunchCardSourceEnum.attenceMachine);
                EquNoSet.add(EquNo);
                setCardId.add(CardId);
                cardColl.add(cardInfo);
                if (minDateTime != null && maxDateTime != null) {
                    if (punchCardTime.getTime() < minDateTime.getTime()) {
                        minDateTime = punchCardTime;
                    } else if (punchCardTime.getTime() > maxDateTime.getTime()) {
                        maxDateTime = punchCardTime;
                    }
                } else {
                    minDateTime = punchCardTime;
                    maxDateTime = punchCardTime;
                }
            } else {
                formatErrorRecords.add(jsonObject);
            }
        }

        Map<String, AttendanceFileInfo> attendanceFileMap = AttendanceFileFactory.getLocalInstance(ctx).getPersonByAttendanceNum(setCardId);
        PunchCardRecordCollection existColl = this.getExistedPunchCardRecordCollection(ctx, minDateTime, maxDateTime, EquNoSet, setCardId);
        CoreBaseCollection cardCollFinally = new CoreBaseCollection();

        for(int i = 0; i < cardColl.size(); ++i) {
            PunchCardRecordInfo cardInfo = (PunchCardRecordInfo)cardColl.get(i);
            JSONObject jsObject = new JSONObject();
            jsObject.put("EquNo", cardInfo.getEquipmentNum());
            jsObject.put("CardId", cardInfo.getAttendanceNum());
            jsObject.put("RecDate", HRTimeWebUtils.dateShortToString(cardInfo.getPunchCardDate()));
            jsObject.put("RecTime", HRTimeWebUtils.timestampToString(cardInfo.getPunchCardTime()).substring(11));
            jsObject.put("Address", cardInfo.getPunchCardPlace());
            if (attendanceFileMap.containsKey(cardInfo.getAttendanceNum())) {
                if (!existColl.contains(cardInfo)) {
                    cardInfo.setPunchCardSource(PunchCardSourceEnum.attenceMachine);
                    AttendanceFileInfo attendanceFileInfo = (AttendanceFileInfo)attendanceFileMap.get(cardInfo.getAttendanceNum());
                    cardInfo.setProposer(attendanceFileInfo.getProposer());
                    cardInfo.setHrOrgUnit(attendanceFileInfo.getHrOrgUnit());
                    cardInfo.setAdminOrgUnit(attendanceFileInfo.getAdminOrgUnit());
                    cardInfo.setAdminOrgUnit(attendanceFileInfo.getAttAdminOrgUnit());
                    cardInfo.setDescription(cardInfo.getEquipmentNum());
                    try {
                        cardInfo.setCreator((UserInfo)ctx.get("UserInfo"));
                        cardInfo.setLastUpdateUser((UserInfo)ctx.get("UserInfo"));
                        cardInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                        cardInfo.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
                    } catch (Exception var23) {
                        var23.printStackTrace();
                    }

                    cardCollFinally.add(cardInfo);
                }
            } else {
                notExistRecords.add(jsObject);
            }
        }

        PunchCardRecordFactory.getLocalInstance(ctx).saveBatchData(cardCollFinally);
        retMap.put("successCtn", cardCollFinally.size());
        retMap.put("formatErrorRecords", formatErrorRecords);
        retMap.put("notExistRecords", notExistRecords);
        retMap.put("duplicateRecords", duplicateRecords);
        return retMap;
    }

    private Map<String, AttendanceEquipmentInfo> getAttendanceEquipmentInfo(Context ctx, Set<String> EquNoSet) throws BOSException {
        new HashSet();
        EntityViewInfo evi = new EntityViewInfo();
        FilterInfo fi = new FilterInfo();
        evi.setFilter(fi);
        evi.getSelector().add(new SelectorItemInfo("id"));
        evi.getSelector().add(new SelectorItemInfo("state"));
        evi.getSelector().add(new SelectorItemInfo("address"));
        evi.getSelector().add(new SelectorItemInfo("number"));
        fi.getFilterItems().add(new FilterItemInfo("state", 1, CompareType.EQUALS));
        fi.getFilterItems().add(new FilterItemInfo("number", EquNoSet, CompareType.INCLUDE));
        CoreBaseCollection coll = AttendanceEquipmentFactory.getLocalInstance(ctx).getCollection(evi);
        Map<String, AttendanceEquipmentInfo> map = new HashMap();

        for(int i = 0; i < coll.size(); ++i) {
            AttendanceEquipmentInfo attendanceEquipmentInfo = (AttendanceEquipmentInfo)coll.get(i);
            map.put(attendanceEquipmentInfo.getNumber(), attendanceEquipmentInfo);
        }

        return map;
    }

    private PunchCardRecordCollection getExistedPunchCardRecordCollection(Context ctx, Timestamp minDateTime, Timestamp maxDateTime, Set<String> EquNoSet, Set<String> setCardId) throws BOSException {
        EntityViewInfo evi = new EntityViewInfo();
        FilterInfo fi = new FilterInfo();
        evi.setFilter(fi);
        evi.getSelector().add(new SelectorItemInfo("punchCardDate"));
        evi.getSelector().add(new SelectorItemInfo("punchCardTime"));
        evi.getSelector().add(new SelectorItemInfo("punchCardSource"));
        evi.getSelector().add(new SelectorItemInfo("equipmentNum"));
        evi.getSelector().add(new SelectorItemInfo("attendanceNum"));
        fi.getFilterItems().add(new FilterItemInfo("equipmentNum", EquNoSet, CompareType.INCLUDE));
        fi.getFilterItems().add(new FilterItemInfo("attendanceNum", setCardId, CompareType.INCLUDE));
        fi.getFilterItems().add(new FilterItemInfo("punchCardTime", maxDateTime, CompareType.LESS_EQUALS));
        fi.getFilterItems().add(new FilterItemInfo("punchCardTime", minDateTime, CompareType.GREATER_EQUALS));
        PunchCardRecordCollection existColl = PunchCardRecordFactory.getLocalInstance(ctx).getPunchCardRecordCollection(evi);
        return existColl;
    }

    public void setErrorMessage(Map<String, Object> param, String bizCode, String errorMsg) {
    }
}
