package com.xjrsoft.module.hikvision.util;

import cn.hutool.db.Entity;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.xjrsoft.common.enums.OutInStatusEnum;
import com.xjrsoft.common.mybatis.SqlRunnerAdapter;
import com.xjrsoft.common.utils.SqlRunnerAdapterUtil;
import com.xjrsoft.module.attendance.entity.AttendanceRuleDetails;
import com.xjrsoft.module.attendance.vo.AttendanceRuleDetailsUserVo;
import com.xjrsoft.module.teacher.mapper.FaceImportMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


public class OutInRecordUtil {
    private static final Logger log = LoggerFactory.getLogger(OutInRecordUtil.class);

    private void teacherInsertRecord(Long userId, String recordTime, String facePhoto, int status, String eventId, String attendanceStatus){
        String photoValue = (facePhoto != null && !facePhoto.equals("null")) ? facePhoto : "";

        String sql = "INSERT INTO teacher_out_in_record(create_date, user_id, record_time, face_photo, eventId, status,delete_mark,enabled_mark, attendance_status) " +
                "select now(), '"  + userId + "', '" + recordTime + "', '" +
                photoValue + "', '" + eventId + "', '" +status + "',0,1,'" + attendanceStatus + "'" +
                " WHERE NOT EXISTS (SELECT 1 FROM teacher_out_in_record WHERE eventId = '" + eventId + "')";
        SqlRunnerAdapter.db().insert(sql);

//        String updSql = "UPDATE attendance_user_relation SET " +
//                "attendance_status = '" + attendanceStatus + "', " +
//                "attendance_time = '" + recordTime + "', " +
//                "attendance_mode = '人脸' " +
//                "WHERE user_id = '" + userId + "' AND delete_mark = 0";
//        SqlRunnerAdapter.db().update(updSql);
    }

    private void studentInsertRecord(Long userId, Long teacherId, Long classId, String facePhoto, String recordTime, int status, String eventId, String attendanceStatus){
        String photoValue = (facePhoto != null && !facePhoto.equals("null")) ? facePhoto : "";

        String sql = "INSERT INTO student_out_in_record(create_date, user_id, teacher_id, class_id, face_photo, record_time , eventId,status,delete_mark,enabled_mark, attendance_status) " +
                "select now(), " + userId + ", " + teacherId + ", " +
                classId + ", '" + photoValue + "', '" + recordTime + "', '" + eventId + "', '" + status + "',0,1,'" + attendanceStatus + "'" +
                " WHERE NOT EXISTS (SELECT 1 FROM student_out_in_record WHERE eventId = '" + eventId + "')";
        SqlRunnerAdapter.db().insert(sql);

        String updSql = "UPDATE attendance_user_relation SET " +
                "attendance_status = '" + attendanceStatus + "', " +
                "attendance_time = '" + recordTime + "', " +
                "attendance_mode = '人脸' " +
                "WHERE user_id = '" + userId + "' AND delete_mark = 0";
        SqlRunnerAdapter.db().update(updSql);
    }


    public void visitInsertRecord(Long reservation_school_people_id, String recordTime,String facePhoto, String status, String eventId){

        String sql = "INSERT INTO visitor_out_in_record(create_date, reservation_school_people_id, record_time, face_photo, event_id, status,delete_mark,enabled_mark) " +
                "select now(), '"  + reservation_school_people_id + "', '" +
                 recordTime + "', '" + facePhoto + "', '" + eventId + "', '" + status +  "',0,1" +
                "  WHERE NOT EXISTS (SELECT 1 FROM visitor_out_in_record WHERE event_id = '" + eventId + "')";
        SqlRunnerAdapter.db().insert(sql);
    }

    private void vehicleInsertRecord(Long carMessageApplyId, String recordTime, int releaseReason, int category, String facePhoto, int status, String planNo, String crossRecordSyscode,
                                    int releaseResult, int releaseWay, int vehicleType, String phone, String name){
        String phoneValue = (phone != null && !phone.equals("null")) ? phone : "";
        String nameValue = (name != null && !name.equals("null")) ? name : "";
        String photoValue = (facePhoto != null && !facePhoto.equals("null")) ? facePhoto : "";

        String tableName = "car_out_in_record";
        Entity where = Entity.create(tableName);
        where.set("create_date", LocalDateTime.now());
        where.set("car_message_apply_id", carMessageApplyId != 0 ? carMessageApplyId : Types.BIGINT);
        where.set("record_time", recordTime);
        where.set("face_photo", photoValue);
        where.set("status", status);
        where.set("release_reason", releaseReason);
        where.set("plan_no", planNo);
        where.set("cross_record_syscode", crossRecordSyscode);
        where.set("release_result", releaseResult);
        where.set("release_way", releaseWay);
        where.set("vehicle_type", vehicleType);
        where.set("phone", phoneValue);
        where.set("name", nameValue);
        where.set("category", category);
        where.set("delete_mark", 0);
        where.set("enabled_mark", 1);

        SqlRunnerAdapter.db().dynamicInsert(tableName, where);

        //车辆入库后，判定教师考勤状态
        if(carMessageApplyId != 0){
            String selectTable = "car_message_apply";
            Entity selectWhere = Entity.create(selectTable);
            selectWhere.set("id", carMessageApplyId);
            selectWhere.set("car_number", planNo);
            Map<String, Object> objectMap = SqlRunnerAdapter.db().dynamicSelectOne(selectTable, selectWhere);
            Long userId = Long.parseLong(objectMap.get("user_id").toString());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime recordTimeDate = LocalDateTime.parse(recordTime, formatter);
            String attendanceStatus = discernTeacherStatus(recordTimeDate, status, userId);

            String updSql = "UPDATE attendance_user_relation SET " +
                    "attendance_status = '" + attendanceStatus + "', " +
                    "attendance_time = '" + recordTime + "', " +
                    "attendance_mode = '车辆', " +
                    "car_number = '" + planNo + "' " +
                    "WHERE user_id = '" + userId + "' AND delete_mark = 0";
            SqlRunnerAdapter.db().update(updSql);
        }
    }

    private void updatePicVehicleRecord(String eventId, String photo, int releaseWayInt, int releaseReasonInt, int releaseResultInt) {
        String photoValue = (photo != null && !photo.equals("null")) ? photo : "";

        String tableName = "car_out_in_record";

        Entity params = Entity.create();
        params.set("face_photo", photoValue);
        params.set("release_way", releaseWayInt);
        params.set("release_reason", releaseReasonInt);
        params.set("release_result", releaseResultInt);

        Entity where = Entity.create();
        where.set("cross_record_syscode", eventId);

        // 执行更新操作
        SqlRunnerAdapter.db().dynamicUpdate(tableName, params, where);
    }

    private void updateReleaseVehicleRecord(String eventId, int releaseWayInt, int releaseReasonInt, int releaseResultInt) {
        String tableName = "car_out_in_record";

        Entity params = Entity.create();
        params.set("release_way", releaseWayInt);
        params.set("release_reason", releaseReasonInt);
        params.set("release_result", releaseResultInt);

        Entity where = Entity.create();
        where.set("cross_record_syscode", eventId);

        SqlRunnerAdapter.db().dynamicUpdate(tableName, params, where);
    }

    public void GetTeacherAndStudentRecords(FaceImportMapper faceImportMapper, LocalDateTime startDateTime, LocalDateTime endDateTime) throws ParseException {
        JsonArray responseBuilder = new JsonArray();

        AtomicInteger pageNo = new AtomicInteger(1);
        int pageSize = 1000;
        boolean hasMorePages = true;

        while (hasMorePages) {
            String response = GetDoorEvent(pageNo, pageSize, startDateTime, endDateTime);

            JsonElement responseElement = new Gson().fromJson(response, JsonElement.class);
            JsonArray dataList = responseElement.getAsJsonObject().getAsJsonObject("data").getAsJsonArray("list");

            for (JsonElement item : dataList) {
                responseBuilder.add(item);
            }

            JsonObject responseJson = new Gson().fromJson(response, JsonObject.class);
            int totalCount = responseJson.getAsJsonObject("data").get("totalPage").getAsInt();
            hasMorePages = pageNo.getAndIncrement() < totalCount;
        }
        // Process the records
        InsertTeacherStudentRecords(responseBuilder, faceImportMapper);
    }

    private void InsertTeacherStudentRecords(JsonArray doorEventsResponse, FaceImportMapper faceImportMapper) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Long> teacherUserIds = faceImportMapper.getTeacherUserIds();
        for (JsonElement element : doorEventsResponse) {
            JsonObject item = element.getAsJsonObject();

            Long personId;
            try {
                personId = item.get("personId").isJsonNull() ? null : item.get("personId").getAsLong();
            }catch (Exception e){
                continue;
            }
            if (personId == null) continue;

            int statusInt = item.get("inAndOutType").getAsInt();
            int status = 1;
            switch (statusInt){
                case 0:
                    status = 1;
                    break;
                case 1:
                    status = 0;
                    break;
            }

            String uri = item.get("picUri").isJsonNull() ? null : item.get("picUri").getAsString();
            String recordTime = item.get("eventTime").isJsonNull() ? null : item.get("eventTime").getAsString();
            String eventId = item.get("eventId").isJsonNull() ? null : item.get("eventId").getAsString();
            String recordTimeStr = ChangeTime(recordTime);
            if (teacherUserIds.contains(personId)) {
                // 老师记录
                LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                String attendanceStatus = discernTeacherStatus(recordTimeDate, status, personId);
                teacherInsertRecord(personId, recordTimeStr, ApiUtil.GetRedirectURL(uri),status,eventId, attendanceStatus);
            } else {
                // 学生记录
                LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                String attendanceStatus = discernStudentStatus(recordTimeDate, status, personId);
                studentInsertRecord(personId, faceImportMapper.GetTeacherIdByPersonId(personId),
                    faceImportMapper.GetClassIdByPersonId(personId), ApiUtil.GetRedirectURL(uri), recordTimeStr, status, eventId, attendanceStatus);
            }
        }
    }

    String discernTeacherStatus(LocalDateTime recordTime, int status, Long userId){
        String attendanceStatus = "";
        String dayOfWeek = recordTime.getDayOfWeek().name();
        String sql = "SELECT t2.* FROM attendance_rule_category t1" +
                " INNER JOIN attendance_rule_details t2 ON t1.id = t2.attendance_rule_category_id" +
                " INNER JOIN attendance_user_relation t3 ON t1.id = t3.attendance_rule_category_id" +
                " WHERE t1.delete_mark = 0 AND t2.delete_mark = 0 AND NOW() BETWEEN start_date AND end_date" +
                " AND t2.date_type = '" + dayOfWeek + "' and t3.user_id = " + userId;
        List<Map<String, Object>> ruleDetailsList = SqlRunnerAdapter.db().selectList(sql, AttendanceRuleDetails.class);
        if(!ruleDetailsList.isEmpty()){
            AttendanceRuleDetails ruleDetails = SqlRunnerAdapterUtil.convertMapToEntity(ruleDetailsList.get(0), AttendanceRuleDetails.class);
            if (ruleDetails != null) {
                if (ruleDetails.getIsAttendance() != null && ruleDetails.getIsAttendance() == 0) {
                    attendanceStatus = "不考勤";
                } else {
                    LocalDateTime amStartTime = null, amEndTime = null, pmStartTime = null, pmEndTime = null, eveningStartTime = null, eveningEndTime = null;
                    if (ruleDetails.getAmStatus() != null && ruleDetails.getAmStatus() == 1
                            && ruleDetails.getAmStartTime() != null && ruleDetails.getAmEndTime() != null) {
                        amStartTime = recordTime.withHour(ruleDetails.getAmStartTime().toLocalTime().getHour())
                                .withMinute(ruleDetails.getAmStartTime().toLocalTime().getMinute())
                                .withSecond(ruleDetails.getAmStartTime().toLocalTime().getSecond());
                        amEndTime = recordTime.withHour(ruleDetails.getAmEndTime().toLocalTime().getHour())
                                .withMinute(ruleDetails.getAmEndTime().toLocalTime().getMinute())
                                .withSecond(ruleDetails.getAmEndTime().toLocalTime().getSecond());
                    }
                    if (ruleDetails.getPmStatus() != null && ruleDetails.getPmStatus() == 1
                            && ruleDetails.getPmEndTime() != null && ruleDetails.getPmStartTime() != null) {
                        pmStartTime = recordTime.withHour(ruleDetails.getPmStartTime().toLocalTime().getHour())
                                .withMinute(ruleDetails.getPmStartTime().toLocalTime().getMinute())
                                .withSecond(ruleDetails.getPmStartTime().toLocalTime().getSecond());
                        pmEndTime = recordTime.withHour(ruleDetails.getPmEndTime().toLocalTime().getHour())
                                .withMinute(ruleDetails.getPmEndTime().toLocalTime().getMinute())
                                .withSecond(ruleDetails.getPmEndTime().toLocalTime().getSecond());
                    }
                    if (status == OutInStatusEnum.goOut.getCode()) {//出
                        if (recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)) {
                            attendanceStatus = "早退";
                        } else if (recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)) {
                            attendanceStatus = "早退";
                        } else {
                            attendanceStatus = "离校";
                        }
                    } else {//进
                        if (recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)) {
                            attendanceStatus = "迟到";
                        } else if (recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)) {
                            attendanceStatus = "迟到";
                        } else {
                            attendanceStatus = "到校";
                        }
                    }
                }
            }
        }
        return attendanceStatus;
    }

    String discernStudentStatus(LocalDateTime recordTime, int status, Long studentUserId){
        String attendanceStatus = "";
        String dayOfWeek = recordTime.getDayOfWeek().name();
        String sql = "SELECT t2.* FROM attendance_rule_category t1" +
                " INNER JOIN attendance_rule_details t2 ON t1.id = t2.attendance_rule_category_id" +
                " INNER JOIN attendance_user_relation t3 ON t1.id = t3.attendance_rule_category_id" +
                " WHERE t1.delete_mark = 0 AND t2.delete_mark = 0 AND NOW() BETWEEN start_date AND end_date" +
                " AND t2.date_type = '" + dayOfWeek + "' and t3.user_id = " + studentUserId;
        List<Map<String, Object>> ruleDetailsList = SqlRunnerAdapter.db().selectList(sql, AttendanceRuleDetails.class);
        if(!ruleDetailsList.isEmpty()){
            AttendanceRuleDetails ruleDetails = SqlRunnerAdapterUtil.convertMapToEntity(ruleDetailsList.get(0), AttendanceRuleDetails.class);
            if(ruleDetails.getIsAllowInOutSchool() != null && ruleDetails.getIsAllowInOutSchool() == 0){
                attendanceStatus = "不考勤";
            }else{
                LocalDateTime amStartTime = null, amEndTime = null, pmStartTime = null, pmEndTime = null, eveningStartTime = null, eveningEndTime = null;
                if(ruleDetails.getAmStatus() != null && ruleDetails.getAmStatus() == 1 && ruleDetails.getAmStartTime() != null
                        &&  ruleDetails.getAmEndTime() != null){
                    amStartTime = recordTime.withHour(ruleDetails.getAmStartTime().toLocalTime().getHour())
                            .withMinute(ruleDetails.getAmStartTime().toLocalTime().getMinute())
                            .withSecond(ruleDetails.getAmStartTime().toLocalTime().getSecond());
                    amEndTime = recordTime.withHour(ruleDetails.getAmEndTime().toLocalTime().getHour())
                            .withMinute(ruleDetails.getAmEndTime().toLocalTime().getMinute())
                            .withSecond(ruleDetails.getAmEndTime().toLocalTime().getSecond());
                }
                if(ruleDetails.getPmStatus() != null && ruleDetails.getPmStatus() == 1 && ruleDetails.getPmStartTime() != null
                        &&  ruleDetails.getPmEndTime() != null){
                    pmStartTime = recordTime.withHour(ruleDetails.getPmStartTime().toLocalTime().getHour())
                            .withMinute(ruleDetails.getPmStartTime().toLocalTime().getMinute())
                            .withSecond(ruleDetails.getPmStartTime().toLocalTime().getSecond());
                    pmEndTime = recordTime.withHour(ruleDetails.getPmEndTime().toLocalTime().getHour())
                            .withMinute(ruleDetails.getPmEndTime().toLocalTime().getMinute())
                            .withSecond(ruleDetails.getPmEndTime().toLocalTime().getSecond());
                }
                if(ruleDetails.getEveningStatus() != null && ruleDetails.getEveningStatus() == 1
                        && ruleDetails.getEveningStartTime() != null
                        &&  ruleDetails.getEveningEndTime() != null){
                    eveningStartTime = recordTime.withHour(ruleDetails.getEveningStartTime().toLocalTime().getHour())
                            .withMinute(ruleDetails.getEveningStartTime().toLocalTime().getMinute())
                            .withSecond(ruleDetails.getEveningStartTime().toLocalTime().getSecond());
                    eveningEndTime = recordTime.withHour(ruleDetails.getEveningEndTime().toLocalTime().getHour())
                            .withMinute(ruleDetails.getEveningEndTime().toLocalTime().getMinute())
                            .withSecond(ruleDetails.getEveningEndTime().toLocalTime().getSecond());
                }
                if(status == OutInStatusEnum.goOut.getCode()){//出
                    if(amEndTime != null && amStartTime != null && recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)){
                        attendanceStatus = "早退";
                    }else if(pmEndTime != null && pmStartTime != null && recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)){
                        attendanceStatus = "早退";
                    }else if(eveningEndTime != null && eveningStartTime != null && recordTime.isBefore(eveningEndTime) && recordTime.isAfter(eveningStartTime)){
                        attendanceStatus = "早退";
                    }else{
                        attendanceStatus = "离校";
                    }
                }else{//进
                    if(amEndTime != null && amStartTime != null && recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)){
                        attendanceStatus = "迟到";
                        LocalDateTime localDateTime = amStartTime;
                        if(ruleDetails.getOverMinutes() != null){
                            localDateTime = amStartTime.plusMinutes(ruleDetails.getOverMinutes());
                        }
                        if(recordTime.isAfter(localDateTime)){
                            attendanceStatus = "旷课";
                        }
                    }else if(pmEndTime != null && pmStartTime != null && recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)){
                        attendanceStatus = "迟到";
                        LocalDateTime localDateTime = pmStartTime;
                        if(ruleDetails.getOverMinutes() != null){
                            localDateTime = pmStartTime.plusMinutes(ruleDetails.getOverMinutes());
                        }
                        if(recordTime.isAfter(localDateTime)){
                            attendanceStatus = "旷课";
                        }
                    }else if(eveningEndTime != null && eveningStartTime != null && recordTime.isBefore(eveningEndTime) && recordTime.isAfter(eveningStartTime)){
                        attendanceStatus = "迟到";
                        LocalDateTime localDateTime = eveningStartTime;
                        if(ruleDetails.getOverMinutes() != null){
                            localDateTime = eveningStartTime.plusMinutes(ruleDetails.getOverMinutes());
                        }
                        if(recordTime.isAfter(localDateTime)){
                            attendanceStatus = "旷课";
                        }
                    }else{
                        attendanceStatus = "到校";
                    }
                }
            }
        }
        return attendanceStatus;
    }

    public void GetVisitRecord(FaceImportMapper faceImportMapper, LocalDateTime startDateTime, LocalDateTime endDateTime) throws ParseException {
        ApiUtil apiUtil = new ApiUtil();

        AtomicInteger pageNo = new AtomicInteger(1);
        int pageSize = 100;
        boolean hasMorePages = true;
        JsonArray responseBuilder = new JsonArray();
        JsonArray responseDoorBuilder = new JsonArray();

        String apiPath = "/api/visitor/v1/event/turnover/search";

        while (hasMorePages) {
            JsonObject paramJson = new JsonObject();
            paramJson.addProperty("pageNo", pageNo.get());
            paramJson.addProperty("pageSize", pageSize);

            String response = apiUtil.doPost(apiPath, String.valueOf(paramJson), null);
            String responseDoor = GetDoorEvent(pageNo, pageSize, startDateTime, endDateTime);

            JsonElement responseElement = new Gson().fromJson(response, JsonElement.class);
            JsonElement responseDoorElement = new Gson().fromJson(responseDoor, JsonElement.class);
            JsonObject data = responseElement.getAsJsonObject().getAsJsonObject("data");
            if(data.isJsonNull()){
                continue;
            }
            JsonArray dataList = data.getAsJsonArray("rows");
            JsonArray dataDoorList = responseDoorElement.getAsJsonObject().getAsJsonObject("data").getAsJsonArray("list");

            for (JsonElement item : dataList) {
                responseBuilder.add(item);
            }

            for (JsonElement item : dataDoorList) {
                responseDoorBuilder.add(item);
            }

            JsonObject responseJson = new Gson().fromJson(response, JsonObject.class);
            int totalCount = responseJson.getAsJsonObject("data").get("total").getAsInt();
            hasMorePages = pageNo.getAndIncrement() < totalCount;
        }

        InsertVisitRecords(responseBuilder,responseDoorBuilder,faceImportMapper);
    }

    private void InsertVisitRecords(JsonArray eventsResponse, JsonArray doorEventsResponse,FaceImportMapper faceImportMapper) throws ParseException {

        for (JsonElement element : eventsResponse) {
            List<String> visit_id_list = faceImportMapper.GetReservationSchoolIdList();
            JsonObject item = element.getAsJsonObject();

            String picUri = item.get("visitorPhotoUri").isJsonNull() ? "" : ApiUtil.GetRedirectURL(item.get("visitorPhotoUri").getAsString());
            String orderId = item.get("orderId").isJsonNull() ? null : item.get("orderId").getAsString();
            String eventTime = item.get("eventTime").isJsonNull() ? null : ChangeTime(item.get("eventTime").getAsString());
            String reservationSchoolId = faceImportMapper.GetReservationSchoolId(orderId) == null ? "0" : String.valueOf(faceImportMapper.GetReservationSchoolId(orderId));
            String eventId = item.get("eventId").isJsonNull() ? null : item.get("eventId").getAsString();
            String deviceDesc = item.get("deviceDesc").isJsonNull() ? null : item.get("deviceDesc").getAsString();

            int status = 1;
            for (JsonElement e : doorEventsResponse){
                JsonObject ele = e.getAsJsonObject();
                if (ele.get("eventId") == item.get("eventId")){
                    status = ele.get("inAndOutType").getAsInt();
                    break;
                }
            }

            if (visit_id_list.contains(eventId)) continue;

            visitInsertRecord(Long.parseLong(reservationSchoolId), eventTime, picUri, status + "", eventId);
        }

    }

    public void GetVehicleRecord(FaceImportMapper faceImportMapper, LocalDateTime startDateTime, LocalDateTime endDateTime) throws ParseException {
        ApiUtil apiUtil = new ApiUtil();

        AtomicInteger pageNo = new AtomicInteger(1);
        int pageSize = 1000;
        boolean hasMorePages = true;
        JsonArray responseBuilder = new JsonArray();

        String apiPath = "/api/pms/v1/crossRecords/page";

        while (hasMorePages) {
            JsonObject paramJson = new JsonObject();
            paramJson.addProperty("pageNo", pageNo.getAndIncrement());
            paramJson.addProperty("pageSize", pageSize);
            paramJson.addProperty("startTime", startDateTime.atOffset(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
            paramJson.addProperty("endTime", endDateTime.atOffset(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

            String response = apiUtil.doPost(apiPath, String.valueOf(paramJson), null);
            JsonElement responseElement = new Gson().fromJson(response, JsonElement.class);
            JsonArray dataList = responseElement.getAsJsonObject().getAsJsonObject("data").getAsJsonArray("list");

            for (JsonElement item : dataList) {
                responseBuilder.add(item);
            }

            JsonObject responseJson = new Gson().fromJson(response, JsonObject.class);
            int totalCount = responseJson.getAsJsonObject("data").get("total").getAsInt();
            hasMorePages = pageNo.getAndIncrement() * pageSize < totalCount;
        }

        InsertVehicleRecords(responseBuilder, faceImportMapper);
    }

    private void InsertVehicleRecords(JsonArray doorEventsResponse, FaceImportMapper faceImportMapper) throws ParseException {
        List<String> vehicle_id_list = faceImportMapper.GetVehicleIdList();

        for (JsonElement element : doorEventsResponse) {
            JsonObject item = element.getAsJsonObject();

            String carMessageApplyIdStr = faceImportMapper.GetCarMessageApplyIdByCarNumber(item.get("plateNo").getAsString().trim());
            Long carId = (carMessageApplyIdStr == null || carMessageApplyIdStr.isEmpty()) ? 0 : Long.parseLong(carMessageApplyIdStr);
            String category = null;
            int categoryInt = 0;
            if (item.has("carCategory")){
                category = item.get("carCategory").isJsonNull() ? null : item.get("carCategory").getAsString();
                switch (category){
                    case "10":
                        categoryInt = 0;
                        break;
                    case "11":
                        categoryInt = 1;
                        break;
                }
            }

            int releaseResultInt = 0;
            if (item.has("releaseResult")){
                releaseResultInt = item.get("releaseResult").isJsonNull() ? null : item.get("releaseResult").getAsInt();
            }

            int releaseWayInt = 0;
            if (item.has("releaseWay")){
                releaseWayInt = item.get("releaseWay").isJsonNull() ? null : item.get("releaseWay").getAsInt();
            }

            int releaseReasonInt = 0;
            if (item.has("releaseReason")){
                releaseReasonInt = item.get("releaseReason").isJsonNull() ? null : item.get("releaseReason").getAsInt();
            }

            int vehicleType = item.get("vehicleType").isJsonNull() ? null : item.get("vehicleType").getAsInt();
            String crossRecordSyscode = item.get("crossRecordSyscode").isJsonNull() ? null : item.get("crossRecordSyscode").getAsString();
            String plateNo = item.get("plateNo").isJsonNull() ? null : item.get("plateNo").getAsString();
            String eventTime = item.get("crossTime").isJsonNull() ? null : ChangeTime(item.get("crossTime").getAsString());

            int status = item.get("vehicleOut").isJsonNull() ? null : item.get("vehicleOut").getAsInt();
            int statusInt = 0;
            switch (status){
                case 0:
                    statusInt = 1;
                    break;
                case 1:
                    statusInt = 0;
                    break;
            }

            JsonElement facePicUriElement = item.get("plateNoPicUri");
            String facePicUri;
            if (facePicUriElement == null || facePicUriElement.isJsonNull()) {
                facePicUri = "null";
            } else {
                facePicUri = ApiUtil.GetRedirectURL(facePicUriElement.getAsString());
            }

            String phone = faceImportMapper.GetPhoneNumberByPlanNum(plateNo);
            String name = faceImportMapper.GetNameByPlanNum(plateNo);

            if(vehicle_id_list.contains(crossRecordSyscode)) continue;

            vehicleInsertRecord(carId, eventTime, releaseReasonInt, categoryInt, facePicUri, statusInt, plateNo,
                    crossRecordSyscode, releaseResultInt, releaseWayInt, vehicleType, phone, name);
        }
    }

    private String GetDoorEvent(AtomicInteger pageNo, int pageSize, LocalDateTime startDateTime, LocalDateTime endDateTime){
        ApiUtil apiUtil = new ApiUtil();
        String apiPath = "/api/acs/v2/door/events";
        JsonObject paramJson = new JsonObject();
        JsonArray eventList = new JsonArray();
        eventList.add(196893); // 只获取人脸通过的
        paramJson.addProperty("pageNo", pageNo.get());
        paramJson.addProperty("pageSize", pageSize);
        paramJson.add("eventTypes", eventList);
        paramJson.addProperty("startTime", startDateTime.atOffset(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
        paramJson.addProperty("endTime", endDateTime.atOffset(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

        return apiUtil.doPost(apiPath, String.valueOf(paramJson), null);
    }

    public String ChangeTime(String recordTime) throws ParseException {
        SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat mysqlFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = isoFormat.parse(recordTime);
        return mysqlFormat.format(date);
    }

    public void GetTeacherAndStudentRecordsTest(FaceImportMapper faceImportMapper, JsonObject data) throws ParseException {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

            JsonObject paramsObject = data.getAsJsonObject("params");
            JsonArray eventsArray = paramsObject.getAsJsonArray("events");

            List<Long> teacherUserIds = faceImportMapper.getTeacherUserIds();
            for (JsonElement eventElement : eventsArray) {
                JsonObject eventObject = eventElement.getAsJsonObject();
                JsonObject dataObject = eventObject.getAsJsonObject("data");

                String idNum = null;
                if (dataObject.has("ExtEventPersonNo")) {
                    String idNumStr = dataObject.get("ExtEventPersonNo").getAsString();
                    if (!idNumStr.isEmpty()) {
                        idNum = idNumStr;
                    }
                }
                String happenTime = eventObject.get("happenTime").getAsString();
                String extEventPictureURL = dataObject.get("ExtEventPictureURL").getAsString();
                int statusInt = dataObject.get("ExtEventInOut").getAsInt();
                int status = 1;
                switch (statusInt){
                    case 0:
                        status = 1;
                        break;
                    case 1:
                        status = 0;
                        break;
                }
                String eventId = eventObject.get("eventId").getAsString();
                String recordTimeStr = ChangeTime(happenTime);

                if (idNum == null) continue;

                if (teacherUserIds.contains(Long.valueOf(idNum))) {
                    // 老师记录
                    LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                    String attendanceStatus = discernTeacherStatus(recordTimeDate, status, Long.valueOf(idNum));
                    teacherInsertRecord(Long.valueOf(idNum), recordTimeStr, ApiUtil.GetRedirectURL(extEventPictureURL), status, eventId, attendanceStatus);
                } else {
                    // 学生记录
                    LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                    String attendanceStatus = discernStudentStatus(recordTimeDate, status, Long.valueOf(idNum));
                    studentInsertRecord(Long.valueOf(idNum), faceImportMapper.GetTeacherIdByPersonId(Long.valueOf(idNum)),
                            faceImportMapper.GetClassIdByPersonId(Long.valueOf(idNum)), ApiUtil.GetRedirectURL(extEventPictureURL), recordTimeStr, status, eventId, attendanceStatus);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void GetVehicleRecordTest(FaceImportMapper faceImportMapper, String data) throws ParseException {
        if (data != null) {
            List<String> vehicle_id_list = faceImportMapper.GetVehicleIdList();
            try {
                JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                JsonObject paramsObject = jsonObject.getAsJsonObject("params");
                JsonArray eventsArray = paramsObject.getAsJsonArray("events");

                for (JsonElement eventElement : eventsArray) {
                    JsonObject eventObject = eventElement.getAsJsonObject();
                    JsonObject dataObject = eventObject.getAsJsonObject("data");
                    if (dataObject.get("eventCmd").getAsInt() == 1){
                        String carNum = dataObject.get("plateNo").getAsString().trim();
                        String eventIndex = dataObject.get("eventIndex").getAsString().trim();
                        String carMessageApplyIdStr = faceImportMapper.GetCarMessageApplyIdByCarNumber(carNum);
                        Long carId = (carMessageApplyIdStr == null || carMessageApplyIdStr.isEmpty()) ? 0 : Long.parseLong(carMessageApplyIdStr);
                        String eventTime = ChangeTime(dataObject.get("time").getAsString());

                        int releaseWayInt = -1;
                        int releaseReasonInt = -1;
                        int releaseResultInt = -1;
                        JsonObject inResultObject = dataObject.getAsJsonObject("inResult");
                        JsonObject outResultObject = dataObject.getAsJsonObject("outResult");
                        JsonObject inoutResult = (inResultObject != null && !inResultObject.isJsonNull()) ? inResultObject : outResultObject;
                        if (inoutResult != null) {
                            JsonObject rlsResultObject = inoutResult.getAsJsonObject("rlsResult");
                            if (rlsResultObject.has("releaseWay") && rlsResultObject.has("releaseReason") && rlsResultObject.has("releaseResult")) {
                                releaseWayInt = rlsResultObject.get("releaseWay").getAsInt();
                                releaseReasonInt = rlsResultObject.get("releaseReason").getAsInt();
                                releaseResultInt = rlsResultObject.get("releaseResult").getAsInt();
                                if (releaseResultInt == 13) releaseResultInt = 1;
                            }
                        }

                        String carAttributeName = dataObject.get("carAttributeName").getAsString().trim();
                        int vehicleType = dataObject.get("vehicleType").getAsInt();
                        int category = -1;
                        switch (carAttributeName){
                            case "临时车":
                                category = 1;
                                break;
                            case "固定车":
                                category = 0;
                                break;
                        }

                        String facePicUri = "";
                        JsonObject picUrlObject = dataObject.getAsJsonObject("picUrl");
                        if (picUrlObject != null && picUrlObject.has("vehiclePicUrl")) {
                            facePicUri = picUrlObject.get("vehiclePicUrl").getAsString();
                        }

                        String statusStr = dataObject.get("roadwayName").getAsString();
                        int statusInt = -1;
                        if (statusStr.contains("入")) {
                            statusInt = 0;
                        } else if (statusStr.contains("出")) {
                            statusInt = 1;
                        }

                        String phone = faceImportMapper.GetPhoneNumberByPlanNum(carNum);
                        String name = faceImportMapper.GetNameByPlanNum(carNum);

                        if (vehicle_id_list.contains(eventIndex)) continue;

                        vehicleInsertRecord(carId, eventTime, releaseReasonInt, category, ApiUtil.GetRedirectURL(facePicUri), statusInt, carNum, eventIndex, releaseResultInt, releaseWayInt,vehicleType,phone,name);
                    }
                }
            } catch (Exception e) {
                log.info(String.valueOf(e));
            }
        }
    }

    public void UpdatePicVehicleRecordTest(String data) {
        if (data != null) {
            try {
                JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                JsonObject paramsObject = jsonObject.getAsJsonObject("params");
                JsonArray eventsArray = paramsObject.getAsJsonArray("events");

                for (JsonElement eventElement : eventsArray) {
                    JsonObject eventObject = eventElement.getAsJsonObject();
                    JsonObject dataObject = eventObject.getAsJsonObject("data");

                    if(dataObject.get("eventCmd").getAsInt() == 2){
                        String eventIndex = dataObject.get("eventIndex").getAsString().trim();

                        int releaseWayInt = -1;
                        int releaseReasonInt = -1;
                        int releaseResultInt = -1;
                        JsonObject inResultObject = dataObject.getAsJsonObject("inResult");
                        JsonObject outResultObject = dataObject.getAsJsonObject("outResult");
                        JsonObject inoutResult = (inResultObject != null && !inResultObject.isJsonNull()) ? inResultObject : outResultObject;
                        if (inoutResult != null) {
                            JsonObject rlsResultObject = inoutResult.getAsJsonObject("rlsResult");
                            if (rlsResultObject.has("releaseWay") && rlsResultObject.has("releaseReason") && rlsResultObject.has("releaseResult")) {
                                releaseWayInt = rlsResultObject.get("releaseWay").getAsInt();
                                releaseReasonInt = rlsResultObject.get("releaseReason").getAsInt();
                                releaseResultInt = rlsResultObject.get("releaseResult").getAsInt();
                                if (releaseResultInt == 13) releaseResultInt = 1;
                            }
                        }

                        String facePicUri = "";
                        JsonObject picUrlObject = dataObject.getAsJsonObject("picUrl");
                        if (picUrlObject != null && picUrlObject.has("vehiclePicUrl")) {
                            facePicUri = picUrlObject.get("vehiclePicUrl").getAsString();
                        }

                        updatePicVehicleRecord(eventIndex, ApiUtil.GetRedirectURL(facePicUri), releaseWayInt, releaseReasonInt, releaseResultInt);
                    }
                }
            } catch (Exception e) {
                log.info(String.valueOf(e));
            }
        }
    }

    public void UpdateReleaseVehicleRecordTest(String data) {
        if (data != null) {
            try {
                JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                JsonObject paramsObject = jsonObject.getAsJsonObject("params");
                JsonArray eventsArray = paramsObject.getAsJsonArray("events");

                for (JsonElement eventElement : eventsArray) {
                    JsonObject eventObject = eventElement.getAsJsonObject();
                    JsonObject dataObject = eventObject.getAsJsonObject("data");

                    if (dataObject.get("eventCmd").getAsInt() == 3 || dataObject.get("eventCmd").getAsInt() == 4) {
                        String eventIndex = dataObject.get("eventIndex").getAsString().trim();

                        int releaseWayInt = -1;
                        int releaseReasonInt = -1;
                        int releaseResultInt = -1;
                        JsonObject inResultObject = dataObject.getAsJsonObject("inResult");
                        JsonObject outResultObject = dataObject.getAsJsonObject("outResult");
                        JsonObject inoutResult = (inResultObject != null && !inResultObject.isJsonNull()) ? inResultObject : outResultObject;
                        if (inoutResult != null) {
                            JsonObject rlsResultObject = inoutResult.getAsJsonObject("rlsResult");
                            if (rlsResultObject.has("releaseWay") && rlsResultObject.has("releaseReason") && rlsResultObject.has("releaseResult")) {
                                releaseWayInt = rlsResultObject.get("releaseWay").getAsInt();
                                releaseReasonInt = rlsResultObject.get("releaseReason").getAsInt();
                                releaseResultInt = rlsResultObject.get("releaseResult").getAsInt();
                                if (releaseResultInt == 13) releaseResultInt = 1;
                            }
                        }

                        updateReleaseVehicleRecord(eventIndex, releaseWayInt, releaseReasonInt, releaseResultInt);
                    }
                }
            } catch (Exception e) {
                log.info(String.valueOf(e));
            }
        }
    }

    public void GetVisitRecordsTest(FaceImportMapper faceImportMapper, String data) throws ParseException {
        if (data != null) {
            List<String> visit_id_list = faceImportMapper.GetVisitIdList();

            try {
                JsonObject jsonObject = new Gson().fromJson(data, JsonObject.class);
                JsonObject paramsObject = jsonObject.getAsJsonObject("params");
                JsonArray eventsArray = paramsObject.getAsJsonArray("events");

                for (JsonElement eventElement : eventsArray) {
                    JsonObject eventObject = eventElement.getAsJsonObject();
                    JsonObject dataObject = eventObject.getAsJsonObject("data");

                    String orderId = dataObject.get("visitorId").getAsString().trim();
                    String eventTime = ChangeTime(eventObject.get("happenTime").getAsString());
                    String picUri = dataObject.get("photoUrl").getAsString().trim();
                    String srcParentIndex = eventObject.get("srcParentIndex").getAsString().trim();
                    String eventId = eventObject.get("eventId").getAsString().trim();
                    String reservationSchoolId = faceImportMapper.GetReservationSchoolId(orderId) == null ? "0" : String.valueOf(faceImportMapper.GetReservationSchoolId(orderId));

                    if (visit_id_list.contains(eventId)) continue;

                    visitInsertRecord(Long.parseLong(reservationSchoolId), eventTime, ApiUtil.GetRedirectURL(picUri), srcParentIndex, eventId);
                }
            } catch (Exception e) {
                log.info(String.valueOf(e));
            }
        }
    }

    public void getTeacherRecords(FaceImportMapper faceImportMapper, LocalDateTime startDateTime, LocalDateTime endDateTime,
                                 Map<Long, AttendanceRuleDetailsUserVo> teacherRules) throws ParseException {
        JsonArray responseBuilder = new JsonArray();

        AtomicInteger pageNo = new AtomicInteger(1);
        int pageSize = 1000;
        boolean hasMorePages = true;

        while (hasMorePages) {
            String response = GetDoorEvent(pageNo, pageSize, startDateTime, endDateTime);

            JsonElement responseElement = new Gson().fromJson(response, JsonElement.class);
            JsonArray dataList = responseElement.getAsJsonObject().getAsJsonObject("data").getAsJsonArray("list");
            responseBuilder.addAll(dataList);
            JsonObject responseJson = new Gson().fromJson(response, JsonObject.class);
            int totalCount = responseJson.getAsJsonObject("data").get("totalPage").getAsInt();
            hasMorePages = pageNo.getAndIncrement() < totalCount;
        }
        //存数据
        if(responseBuilder.size() > 0){
            return;
        }
        InsertTeacherStudentRecords(responseBuilder, faceImportMapper);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Long> teacherUserIds = faceImportMapper.getTeacherUserIds();
        List<String> insertSqls = new ArrayList<>();
        for (JsonElement element : responseBuilder) {
            JsonObject item = element.getAsJsonObject();

            Long personId;
            try {
                personId = item.get("personId").isJsonNull() ? null : item.get("personId").getAsLong();
            }catch (Exception e){
                continue;
            }
            if (personId == null) continue;

            int statusInt = item.get("inAndOutType").getAsInt();
            int status = 1;
            switch (statusInt){
                case 0:
                    status = 1;
                    break;
                case 1:
                    status = 0;
                    break;
            }

            String uri = item.get("picUri").isJsonNull() ? null : item.get("picUri").getAsString();
            String recordTime = item.get("eventTime").isJsonNull() ? null : item.get("eventTime").getAsString();
            String eventId = item.get("eventId").isJsonNull() ? null : item.get("eventId").getAsString();
            String recordTimeStr = ChangeTime(recordTime);
            if (teacherUserIds.contains(personId)) {
                // 老师记录
                LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                String attendanceStatus = discernTeacherStatus(recordTimeDate, status, teacherRules.get(personId));
                String insSql = "INSERT INTO teacher_out_in_record(create_date, user_id, record_time, face_photo, eventId, status,delete_mark,enabled_mark, attendance_status) "
                        + "select now(), '"  + personId + "', '" + recordTimeStr + "', '" +
                        ApiUtil.GetRedirectURL(uri) + "', '" + eventId + "', '" +status + "',0,1,'" + attendanceStatus + "'" +
                        " WHERE NOT EXISTS (SELECT 1 FROM teacher_out_in_record WHERE eventId = '" + eventId + "')";
                insertSqls.add(insSql);
            }
            if(!insertSqls.isEmpty()){
                for (String insertSql : insertSqls) {
                    SqlRunnerAdapter.db().insert(insertSql);
                }
            }
        }
    }

    String discernTeacherStatus(LocalDateTime recordTime, int status, AttendanceRuleDetailsUserVo ruleDetails){
        String attendanceStatus = "";
        if (ruleDetails != null) {
            if (ruleDetails.getIsAttendance() != null && ruleDetails.getIsAttendance() == 0) {
                attendanceStatus = "不考勤";
            } else {
                LocalDateTime amStartTime = null, amEndTime = null, pmStartTime = null, pmEndTime = null, eveningStartTime = null, eveningEndTime = null;
                if (ruleDetails.getAmStatus() != null && ruleDetails.getAmStatus() == 1
                        && ruleDetails.getAmStartTime() != null && ruleDetails.getAmEndTime() != null) {
                    amStartTime = recordTime.withHour(ruleDetails.getAmStartTime().getHour())
                            .withMinute(ruleDetails.getAmStartTime().getMinute())
                            .withSecond(ruleDetails.getAmStartTime().getSecond());
                    amEndTime = recordTime.withHour(ruleDetails.getAmEndTime().getHour())
                            .withMinute(ruleDetails.getAmEndTime().getMinute())
                            .withSecond(ruleDetails.getAmEndTime().getSecond());
                }
                if (ruleDetails.getPmStatus() != null && ruleDetails.getPmStatus() == 1
                        && ruleDetails.getPmEndTime() != null && ruleDetails.getPmStartTime() != null) {
                    pmStartTime = recordTime.withHour(ruleDetails.getPmStartTime().getHour())
                            .withMinute(ruleDetails.getPmStartTime().getMinute())
                            .withSecond(ruleDetails.getPmStartTime().getSecond());
                    pmEndTime = recordTime.withHour(ruleDetails.getPmEndTime().getHour())
                            .withMinute(ruleDetails.getPmEndTime().getMinute())
                            .withSecond(ruleDetails.getPmEndTime().getSecond());
                }
                if (status == OutInStatusEnum.goOut.getCode()) {//出
                    if (recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)) {
                        attendanceStatus = "早退";
                    } else if (recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)) {
                        attendanceStatus = "早退";
                    } else {
                        attendanceStatus = "离校";
                    }
                } else {//进
                    if (recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)) {
                        attendanceStatus = "迟到";
                    } else if (recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)) {
                        attendanceStatus = "迟到";
                    } else {
                        attendanceStatus = "到校";
                    }
                }
            }
        }
        return attendanceStatus;
    }

    String discernStudentStatus(LocalDateTime recordTime, int status, AttendanceRuleDetailsUserVo ruleDetails){
        String attendanceStatus = "";
        if(ruleDetails.getIsAllowInOutSchool() != null && ruleDetails.getIsAllowInOutSchool() == 0){
            attendanceStatus = "不考勤";
        }else{
            LocalDateTime amStartTime = null, amEndTime = null, pmStartTime = null, pmEndTime = null, eveningStartTime = null, eveningEndTime = null;
            if(ruleDetails.getAmStatus() != null && ruleDetails.getAmStatus() == 1 && ruleDetails.getAmStartTime() != null
                    &&  ruleDetails.getAmEndTime() != null){
                amStartTime = recordTime.withHour(ruleDetails.getAmStartTime().getHour())
                        .withMinute(ruleDetails.getAmStartTime().getMinute())
                        .withSecond(ruleDetails.getAmStartTime().getSecond());
                amEndTime = recordTime.withHour(ruleDetails.getAmEndTime().getHour())
                        .withMinute(ruleDetails.getAmEndTime().getMinute())
                        .withSecond(ruleDetails.getAmEndTime().getSecond());
            }
            if(ruleDetails.getPmStatus() != null && ruleDetails.getPmStatus() == 1 && ruleDetails.getPmStartTime() != null
                    &&  ruleDetails.getPmEndTime() != null){
                pmStartTime = recordTime.withHour(ruleDetails.getPmStartTime().getHour())
                        .withMinute(ruleDetails.getPmStartTime().getMinute())
                        .withSecond(ruleDetails.getPmStartTime().getSecond());
                pmEndTime = recordTime.withHour(ruleDetails.getPmEndTime().getHour())
                        .withMinute(ruleDetails.getPmEndTime().getMinute())
                        .withSecond(ruleDetails.getPmEndTime().getSecond());
            }
            if(ruleDetails.getEveningStatus() != null && ruleDetails.getEveningStatus() == 1
                    && ruleDetails.getEveningStartTime() != null
                    &&  ruleDetails.getEveningEndTime() != null){
                eveningStartTime = recordTime.withHour(ruleDetails.getEveningStartTime().getHour())
                        .withMinute(ruleDetails.getEveningStartTime().getMinute())
                        .withSecond(ruleDetails.getEveningStartTime().getSecond());
                eveningEndTime = recordTime.withHour(ruleDetails.getEveningEndTime().getHour())
                        .withMinute(ruleDetails.getEveningEndTime().getMinute())
                        .withSecond(ruleDetails.getEveningEndTime().getSecond());
            }
            if(status == OutInStatusEnum.goOut.getCode()){//出
                if(amEndTime != null && amStartTime != null && recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)){
                    attendanceStatus = "早退";
                }else if(pmEndTime != null && pmStartTime != null && recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)){
                    attendanceStatus = "早退";
                }else if(eveningEndTime != null && recordTime.isBefore(eveningEndTime) && recordTime.isAfter(eveningStartTime)){
                    attendanceStatus = "早退";
                }else{
                    attendanceStatus = "离校";
                }
            }else{//进
                if(amEndTime != null && amStartTime != null && recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)){
                    attendanceStatus = "迟到";
                    LocalDateTime localDateTime = amStartTime;
                    if(ruleDetails.getOverMinutes() != null){
                        localDateTime = amStartTime.plusMinutes(ruleDetails.getOverMinutes());
                    }
                    if(recordTime.isAfter(localDateTime)){
                        attendanceStatus = "旷课";
                    }
                }else if(pmEndTime != null && pmStartTime != null && recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)){
                    attendanceStatus = "迟到";
                    LocalDateTime localDateTime = pmStartTime;
                    if(ruleDetails.getOverMinutes() != null){
                        localDateTime = pmStartTime.plusMinutes(ruleDetails.getOverMinutes());
                    }
                    if(recordTime.isAfter(localDateTime)){
                        attendanceStatus = "旷课";
                    }
                }else if(eveningEndTime != null && recordTime.isBefore(eveningEndTime) && recordTime.isAfter(eveningStartTime)){
                    attendanceStatus = "迟到";
                    LocalDateTime localDateTime = eveningStartTime;
                    if(ruleDetails.getOverMinutes() != null){
                        localDateTime = eveningStartTime.plusMinutes(ruleDetails.getOverMinutes());
                    }
                    if(recordTime.isAfter(localDateTime)){
                        attendanceStatus = "旷课";
                    }
                }else{
                    attendanceStatus = "到校";
                }
            }
        }
        return attendanceStatus;
    }
}
