package com.xjrsoft.module.hikvision.util;

import cn.hutool.db.Db;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.xjrsoft.module.attendance.entity.AttendanceRuleDetails;
import com.xjrsoft.module.teacher.mapper.FaceImportMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;


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

    private void teacherInsertRecord(Db db, Long userId, String recordTime, String facePhoto, int status, String eventId, String attendanceStatus) throws SQLException {

        String sql = "INSERT INTO teacher_out_in_record(create_date, user_id, record_time, face_photo, eventId, status,delete_mark,enabled_mark, attendance_status) " +
                "VALUES(now(), '"  + userId + "', '" + recordTime + "', '" +
                facePhoto + "', '" + eventId + "', '" +status + "',0,1,'" + attendanceStatus + "')";
        db.execute(sql);
    }

    private void studentInsertRecord(Db db, Long userId, Long teacherId, Long classId, String facePhoto, String recordTime, int status, String eventId, String attendanceStatus) throws SQLException {
        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) " +
                "VALUES(now(), '" + userId + "', '" + teacherId + "', '" +
                classId + "', '" + facePhoto + "', '" + recordTime + "', '" + eventId + "', '" + status + "',0,1,'" + attendanceStatus + "')";
        db.execute(sql);
    }


    public void visitInsertRecord(Db db, Long reservation_school_people_id, String recordTime,String facePhoto, int status) throws SQLException {
        String sql = "INSERT INTO visitor_out_in_record(create_date, reservation_school_people_id, record_time, face_photo, status,delete_mark,enabled_mark) " +
                "VALUES(now(), '"  + reservation_school_people_id + "', '" +
                 recordTime + "', '" + facePhoto + "', '" + status +  "',0,1)";
        db.execute(sql);
    }

    private void vehicleInsertRecord(Db db, Long carMessageApplyId, String recordTime, int releaseReason, int category, String facePhoto, int status, String planNo, String crossRecordSyscode, int releaseResult, int releaseWay) throws SQLException {
        String sql = "INSERT INTO car_out_in_record(create_date, car_message_apply_id, record_time, face_photo, status,release_reason, plan_no, cross_record_syscode, release_result, release_way, category,delete_mark,enabled_mark) " +
                "VALUES(now(), '"  + carMessageApplyId + "', '" +
                recordTime + "', '" + facePhoto + "', '" + status + "', '" + releaseReason + "', '" + planNo + "', '" +
                crossRecordSyscode + "', '" + releaseResult + "', '" + releaseWay + "', '" + category  +  "',0,1)";
        db.execute(sql);
    }

    public void GetTeacherAndStudentRecords(Db use, FaceImportMapper faceImportMapper) throws SQLException, ParseException {
        JsonArray responseBuilder = new JsonArray();

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

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

            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() * pageSize < totalCount;
        }
        // Process the records
        InsertTeacherStudentRecords(use, responseBuilder, faceImportMapper);
    }

    private void InsertTeacherStudentRecords(Db use, JsonArray doorEventsResponse, FaceImportMapper faceImportMapper) throws SQLException, ParseException {
        List<String> teacherEventIdList = faceImportMapper.GetTeacherUrlList();
        List<String> studentEventIdList = faceImportMapper.GetStudentUrlList();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        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 status = item.get("inAndOutType").getAsInt();
            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 (!Objects.equals(faceImportMapper.IsStudentTypeByPersonId(personId), "学生")) {
                // 老师记录
                if (teacherEventIdList.contains(eventId)) {
                    continue;
                }
                LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                String attendanceStatus = discernTeacherStatus(use, recordTimeDate, status, personId);
                teacherInsertRecord(use, personId, recordTimeStr, ApiUtil.GetRedirectURL(uri),status,eventId, attendanceStatus);
            } else {
                // 学生记录
                if (studentEventIdList.contains(eventId)){
                    continue;
                }
                LocalDateTime recordTimeDate = LocalDateTime.parse(recordTimeStr, formatter);
                String attendanceStatus = discernStudentStatus(use, recordTimeDate, status, personId);
                studentInsertRecord(use, personId, faceImportMapper.GetTeacherIdByPersonId(personId),
                        faceImportMapper.GetClassIdByPersonId(personId), ApiUtil.GetRedirectURL(uri), recordTimeStr, status,eventId, attendanceStatus);
            }
        }
    }

    String discernTeacherStatus(Db use, LocalDateTime recordTime, int status, Long userId) throws SQLException {
        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<AttendanceRuleDetails> ruleDetailsList = use.query(sql, AttendanceRuleDetails.class);
        if(!ruleDetailsList.isEmpty()){
            AttendanceRuleDetails ruleDetails = ruleDetailsList.get(0);
            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){
                    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){
                    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 == 0){//出
                    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(Db use, LocalDateTime recordTime, int status, Long studentUserId) throws SQLException {
        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<AttendanceRuleDetails> ruleDetailsList = use.query(sql, AttendanceRuleDetails.class);
        if(!ruleDetailsList.isEmpty()){
            AttendanceRuleDetails ruleDetails = ruleDetailsList.get(0);
            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){
                    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){
                    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){
                    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 == 0){//出
                    if(recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)){
                        attendanceStatus = "早退";
                    }else if(recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)){
                        attendanceStatus = "早退";
                    }else if(recordTime.isBefore(eveningEndTime) && recordTime.isAfter(eveningStartTime)){
                        attendanceStatus = "早退";
                    }else{
                        attendanceStatus = "离校";
                    }
                }else{//进
                    if(recordTime.isBefore(amEndTime) && recordTime.isAfter(amStartTime)){
                        attendanceStatus = "迟到";
                        if(recordTime.isAfter(amStartTime.plusMinutes(40))){
                            attendanceStatus = "旷课";
                        }
                    }else if(recordTime.isBefore(pmEndTime) && recordTime.isAfter(pmStartTime)){
                        attendanceStatus = "迟到";
                        if(recordTime.isAfter(pmStartTime.plusMinutes(40))){
                            attendanceStatus = "旷课";
                        }
                    }else if(recordTime.isBefore(eveningEndTime) && recordTime.isAfter(eveningStartTime)){
                        attendanceStatus = "迟到";
                        if(recordTime.isAfter(eveningStartTime.plusMinutes(40))){
                            attendanceStatus = "旷课";
                        }
                    }else{
                        attendanceStatus = "到校";
                    }
                }
            }
        }
        return attendanceStatus;
    }

    public void GetVisitRecord(Db use, FaceImportMapper faceImportMapper) throws SQLException, 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);

            JsonElement responseElement = new Gson().fromJson(response, JsonElement.class);
            JsonElement responseDoorElement = new Gson().fromJson(responseDoor, JsonElement.class);

            JsonArray dataList = responseElement.getAsJsonObject().getAsJsonObject("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() * pageSize < totalCount;
        }

        InsertVisitRecords(use, responseBuilder,responseDoorBuilder,faceImportMapper);
    }

    private void InsertVisitRecords(Db use, JsonArray eventsResponse, JsonArray doorEventsResponse,FaceImportMapper faceImportMapper) throws SQLException, ParseException {
        List<Long> visit_id_list = faceImportMapper.GetReservationSchoolIdList();

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

            String picUri = item.get("visitorPhotoUri").isJsonNull() ? null : 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());
            //todo: reservationSchoolId
//            Long reservationSchoolId = faceImportMapper.GetReservationSchoolId(orderId) == null ? 1 : faceImportMapper.GetReservationSchoolId(orderId);

            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(1)) continue;
            visitInsertRecord(use, Long.parseLong("123"), eventTime, picUri, status);
        }

    }

    public void GetVehicleRecord(Db use, FaceImportMapper faceImportMapper) throws SQLException, 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);

            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(use, responseBuilder,faceImportMapper);
    }

    private void InsertVehicleRecords(Db use, JsonArray doorEventsResponse, FaceImportMapper faceImportMapper) throws SQLException, 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();
            }

            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();

            JsonElement facePicUriElement = item.get("facePicUri");
            String facePicUri;
            if (facePicUriElement == null || facePicUriElement.isJsonNull()) {
                facePicUri = "null";
            } else {
                facePicUri = ApiUtil.GetRedirectURL(facePicUriElement.getAsString());
            }
            System.out.println(facePicUri + "haha");

            if(vehicle_id_list.contains(crossRecordSyscode)) continue;

            vehicleInsertRecord(use, carId, eventTime, releaseReasonInt, categoryInt, facePicUri, status, plateNo, crossRecordSyscode, releaseResultInt, releaseWayInt);
        }
    }

    private String GetDoorEvent(AtomicInteger pageNo, int pageSize){
        ApiUtil apiUtil = new ApiUtil();
        String apiPath = "/api/acs/v2/door/events";
        JsonObject paramJson = new JsonObject();
        paramJson.addProperty("pageNo", pageNo.get());
        paramJson.addProperty("pageSize", pageSize);

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

    private 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(Db use, FaceImportMapper faceImportMapper, String data) throws SQLException, ParseException {
        if (data == null || data.trim().isEmpty()) {
            log.warn("Empty data string, skipping processing");
            return;
        }

        try {
            JsonElement responseElement = new Gson().fromJson(data, JsonElement.class);

            if (!responseElement.isJsonObject()) {
                log.error("Invalid JSON format, expected a JSON object");
                return;
            }

            JsonObject responseObject = responseElement.getAsJsonObject();

            if (!responseObject.has("data") || !responseObject.get("data").isJsonObject()) {
                log.error("Missing or invalid 'data' field in JSON");
                return;
            }

            JsonObject dataObject = responseObject.getAsJsonObject("data");

            if (!dataObject.has("list") || !dataObject.get("list").isJsonArray()) {
                log.error("Missing or invalid 'list' field in JSON");
                return;
            }

            JsonArray dataList = dataObject.getAsJsonArray("list");
            JsonArray responseBuilder = new JsonArray();

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

            InsertTeacherStudentRecords(use, responseBuilder, faceImportMapper);

        } catch (Exception e) {
            log.error("Error processing JSON data", e);
        }
    }


    public void GetVehicleRecordTest(Db use, FaceImportMapper faceImportMapper, String data) throws SQLException, 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");

                    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 = 0;
                    int releaseReasonInt = 0;
                    int releaseResultInt = 0;
                    JsonObject inResultObject = dataObject.getAsJsonObject("inResult");
                    if (inResultObject != null) {
                        JsonObject rlsResultObject = inResultObject.getAsJsonObject("rlsResult");
                        if (rlsResultObject != null && rlsResultObject.has("releaseWay") && rlsResultObject.has("releaseReason") && rlsResultObject.has("releaseResult")) {
                            releaseWayInt = rlsResultObject.get("releaseWay").getAsInt();
                            releaseReasonInt = rlsResultObject.get("releaseReason").getAsInt();
                            releaseResultInt = rlsResultObject.get("releaseResult").getAsInt();
                        }
                    }

                    String carAttributeName = dataObject.get("carAttributeName").getAsString().trim();
                    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();
                    }

                    int status = eventObject.get("status").getAsInt();

                    if (vehicle_id_list.contains(eventIndex)) continue;

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


}
