package com.ningdatech.carapi.irs.task;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.exception.BizException;
import com.ningdatech.basic.util.NdDateUtils;
import com.ningdatech.carapi.car.position.entity.VehiclePositionInfo;
import com.ningdatech.carapi.car.position.service.IVehiclePositionInfoService;
import com.ningdatech.carapi.car.vehicle.model.NdVehicleBaseInfo;
import com.ningdatech.carapi.car.vehicle.service.IVehicleBaseInfoService;
import com.ningdatech.carapi.irs.model.entity.VehicleAccidentIrsData;
import com.ningdatech.carapi.irs.service.AccidentService;
import com.ningdatech.carapi.irs.service.IVehicleAccidentIrsDataService;
import com.ningdatech.carapi.safe.constant.AccidentTypeEnum;
import com.ningdatech.carapi.safe.constant.VehicleAccidentReportStatusEnum;
import com.ningdatech.carapi.safe.entity.NdVehicleAccident;
import com.ningdatech.carapi.safe.entity.NdVehicleAccidentDead;
import com.ningdatech.carapi.safe.service.INdVehicleAccidentDeadService;
import com.ningdatech.carapi.safe.service.INdVehicleAccidentService;
import com.ningdatech.carapi.scheduler.contants.TaskConstant;
import com.ningdatech.carapi.sys.entity.Company;
import com.ningdatech.carapi.sys.helper.RegionsCacheHelper;
import com.ningdatech.carapi.sys.service.CompanyService;
import com.ningdatech.file.utils.StrPool;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @description
 * @since 2023/05/21 15:38
 */
@Component
@Slf4j
@Data
public class MyAccidentQueryTask implements Runnable {

    private final AccidentService accidentService;
    private final IVehicleBaseInfoService vehicleBaseInfoService;
    private final IVehicleAccidentIrsDataService accidentIrsDataService;
    private final CompanyService companyService;
    private final INdVehicleAccidentService vehicleAccidentService;
    private final INdVehicleAccidentDeadService vehicleAccidentDeadService;
    private final RegionsCacheHelper regionsCacheHelper;
    private final IVehiclePositionInfoService iVehiclePositionInfoService;

    /**
     * 接口访问次数限制
     */
    private Integer BIGGEST_ACCESS_NUM = 2950;
    /**
     * 存储数据下标的文件名
     */
    private String ACCIDENT_QUERY_INDEX_FILE = "accidentIndex.txt";
    /**
     * 上次中断的车牌号下标
     */
    private Long lastIndex = 0L;
    /**
     * 上次执行的次数
     */
    private Integer lastCount = 0;
    /**
     * 是否继续执行任务
     */
    private boolean isRunning = true;

    public MyAccidentQueryTask(AccidentService accidentService, IVehicleBaseInfoService vehicleBaseInfoService,
        IVehicleAccidentIrsDataService accidentIrsDataService, CompanyService companyService,
        INdVehicleAccidentService vehicleAccidentService, INdVehicleAccidentDeadService vehicleAccidentDeadService,
        RegionsCacheHelper regionsCacheHelper, IVehiclePositionInfoService iVehiclePositionInfoService) {
        this.accidentService = accidentService;
        this.vehicleBaseInfoService = vehicleBaseInfoService;
        this.accidentIrsDataService = accidentIrsDataService;
        this.companyService = companyService;
        this.vehicleAccidentService = vehicleAccidentService;
        this.vehicleAccidentDeadService = vehicleAccidentDeadService;
        this.regionsCacheHelper = regionsCacheHelper;
        this.iVehiclePositionInfoService = iVehiclePositionInfoService;
    }

    @Override
    public void run() {

        log.info("========== 根据IRS更新事故数据 ==========任务开始");
        // 判断当前执行任务的时间是否为月初的1号 如果是月初1号,任务应该从下标1重新开始跑
        LocalDateTime now = LocalDateTime.now();
        int dayOfMonth = now.getDayOfMonth();
        if (TaskConstant.Data.MONTH_VALUE_ONE.equals(dayOfMonth)){
            // 重置文件中的下标
            saveLastIndex(1L, 0);
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        while (isRunning) {
            // 读取上次中断的数据下标和和已经执行的次数
            readLastIndex();
            log.info("读取到的下标为{}", lastIndex);
            log.info("已访问接口次数{}", lastCount);
            Map<Long, String> infoMap =
                vehicleBaseInfoService.list(Wrappers.lambdaQuery(NdVehicleBaseInfo.class)
                        .select(NdVehicleBaseInfo::getId,NdVehicleBaseInfo::getCarPlate))
                        .stream().collect(Collectors.toMap(NdVehicleBaseInfo::getId, NdVehicleBaseInfo::getCarPlate));
            OptionalLong maxKey = infoMap.keySet().stream().mapToLong(Long::longValue).max();
            Long maxIndex = null;
            if (maxKey.isPresent()){
                maxIndex = maxKey.getAsLong();
            }
            // 校验下标对应的车牌号是否一致
            String carNo;
            carNo = infoMap.get(lastIndex);
            while (Objects.isNull(carNo)) {
                log.info("车辆id{}不存在,请检查该车辆信息是否已经被删除!", lastIndex);
                // 查找下一个车辆信息,直到车辆信息存在
                lastIndex++;
                if (Objects.nonNull(maxIndex) && lastIndex.compareTo(maxIndex) > 0){
                    log.info("系统中没有待查询的车牌号");
                    return;
                }
                carNo = infoMap.get(lastIndex);
            }

            // 从车辆信息表中从上次执行中断的下标获取一定数量的车牌号
            int cnt = BIGGEST_ACCESS_NUM - lastCount;
            LambdaQueryWrapper<NdVehicleBaseInfo> query =
                Wrappers.lambdaQuery(NdVehicleBaseInfo.class)
                    .ge(NdVehicleBaseInfo::getId, lastIndex)
                    .last("limit " + cnt)
                    .select(NdVehicleBaseInfo::getCarPlate, NdVehicleBaseInfo::getId)
                    .isNotNull(NdVehicleBaseInfo::getCarPlate);
            List<NdVehicleBaseInfo> list = vehicleBaseInfoService.list(query);
            log.info("此次任务车辆数量为:" + list.size());
            if (CollUtil.isNotEmpty(list)) {
                List<String> carPlateList = list.stream().sorted(Comparator.comparing(NdVehicleBaseInfo::getId))
                    .map(NdVehicleBaseInfo::getCarPlate).collect(Collectors.toList());
                Map<String, Long> carMap = list.stream().collect(Collectors.toMap(NdVehicleBaseInfo::getCarPlate, NdVehicleBaseInfo::getId));
                String[] carPlates = carPlateList.stream().toArray(String[]::new);
                // 执行查询任务
                executeTask(carPlates,carMap);
                // 当访问次数达到当日设定数量时,结束循环，初始化累计访问次数,并更新事故数据
                if (BIGGEST_ACCESS_NUM.equals(lastCount) || lastIndex.equals(maxIndex)) {
                    isRunning = false;
                    // 任务执行完毕后保存最终的数据下标
                    TreeMap<Long, String> sortedMap = new TreeMap<>(infoMap);
                    Map.Entry<Long, String> higherEntry = sortedMap.higherEntry(lastIndex);
                    if (Objects.nonNull(higherEntry)){
                        lastIndex = higherEntry.getKey();
                    }
                    saveLastIndex(lastIndex, 0);
                    // 更新事故数据
                    updateAccidentData();
                    log.info("事故数据更新完成!");
                }
            } else {
                log.info("本月任务已查询完成!");
                return;
            }
        }
        stopWatch.stop();
        log.info("共更新事故数据：" + lastCount + "条");
        log.info("========== 根据IRS更新事故数据==========任务结束 {}s", stopWatch.getTotalTimeSeconds());

    }

    private void executeTask(String[] carPlates, Map<String, Long> carMap) {
        // 获取车牌号的所有事故信息
        Map<String, List<VehicleAccidentIrsData>> accidentIrsDataMap = accidentIrsDataService.list().stream()
                .collect(Collectors.groupingBy(VehicleAccidentIrsData::getCarPlate));
        for (int i = 0; i < carPlates.length; i++) {
            // 执行任务代码
            String carPlate = carPlates[i];
            String dataJsonStr;
            try {
                dataJsonStr = accidentService.accidentQuery(carPlate,i);
                if (Objects.nonNull(dataJsonStr)) {
                    JSONObject jsonObject = JSON.parseObject(dataJsonStr, JSONObject.class);
                    String msg = jsonObject.getString("msg");
                    if (msg.contains("签名错误")) {
                        // 签名错误
                        lastIndex = carMap.get(carPlate);
                        lastCount++;
                        saveLastIndex(lastIndex, lastCount);
                        log.error("签名错误，任务中断时车牌号下标为{}", lastIndex);
                        break;
                    }
                }
            } catch (Exception e) {
                // 接口请求异常,结束循环
                lastIndex = carMap.get(carPlate);
                lastCount++;
                saveLastIndex(lastIndex, lastCount);
                log.error("任务中断时车牌号下标为{},中断原因：{}", lastIndex,e.getMessage());
                break;
            }
            if (Objects.isNull(dataJsonStr)) {
                // 刷新请求秘钥失败,接口调用内容返回空,任务中断，保存下标
                lastIndex = carMap.get(carPlate);
                saveLastIndex(lastIndex, lastCount);
                log.error("车辆事故查询接口调用失败,车牌号为:" + carPlate);
                break;
            }
            int index = i + 1;
            // 如果还有下一个待查询车牌号
            if (index < carPlates.length) {
                lastIndex = carMap.get(carPlates[index]);
            }else {
                // 已经是最后一个车牌号
                lastIndex = carMap.get(carPlates[i]);
            }
            log.info("下次待查询车牌号下标为:" + lastIndex);
            lastCount++;
            log.info("已访问事故查询IRS接口 {} 次", lastCount);
            log.info("此次访问的事故车牌号为 {}", carPlate);

            try {
                JSONObject object = JSON.parseObject(dataJsonStr, JSONObject.class);
                String data = object.getString("datas");
                List<String> array = JSON.parseArray(data, String.class);
                if (CollUtil.isEmpty(array)) {
                    log.info("该车牌号没有事故信息!");
                    continue;
                }
                for (String datas : array) {
                    if (StrUtil.isNotBlank(datas)) {
                        List<JSONObject> accidentArray = JSON.parseArray(datas, JSONObject.class);
                        if (CollUtil.isEmpty(accidentArray)) {
                            log.info("该车牌号没有事故信息!");
                            continue;
                        }

                        for (JSONObject jsonObject : accidentArray) {
                            VehicleAccidentIrsData accidentIrsData = new VehicleAccidentIrsData();
                            accidentIrsData.setCarPlate(carPlate);
                            String jsonString = jsonObject.toJSONString();
                            accidentIrsData.setJsonStrData(jsonString);
                            // 获取事故日期
                            Timestamp sgfssj = jsonObject.getTimestamp("SGFSSJ");
                            LocalDateTime accidentTime = LocalDateTimeUtil.of(sgfssj);
                            if (accidentIrsDataMap.containsKey(carPlate)) {
                                List<VehicleAccidentIrsData> dataList = accidentIrsDataMap.get(carPlate);
                                Map<LocalDateTime, VehicleAccidentIrsData> dataMap = dataList.stream()
                                    .collect(Collectors.toMap(VehicleAccidentIrsData::getAccidentTime, v -> v));
                                if (dataMap.containsKey(accidentTime)) {
                                    VehicleAccidentIrsData irsData = dataMap.get(accidentTime);
                                    // 数据已经存在
                                    accidentIrsData.setId(irsData.getId());
                                }
                            }
                            accidentIrsData.setAccidentTime(accidentTime);
                            accidentIrsData.setCreateOn(LocalDateTime.now());
                            accidentIrsData.setUpdateOn(LocalDateTime.now());
                            accidentIrsDataService.saveOrUpdate(accidentIrsData);
                        }
                    }
                }
            } catch (Exception e) {
                throw new BizException("数据保存失败");
            } finally {
                // 每次执行保存一次下标
                saveLastIndex(lastIndex,lastCount);
            }
        }
    }

    private void saveLastIndex(Long lastIndex, Integer lastCount) {

        File directory = new File("");
        // 临时文件存储路径
        String filePath = directory.getAbsolutePath() + File.separator + "irs";
        File file = new File(filePath + File.separator + ACCIDENT_QUERY_INDEX_FILE);

        try {
            FileWriter fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

            bufferedWriter.write(Long.toString(lastIndex));
            bufferedWriter.newLine();
            bufferedWriter.write(Integer.toString(lastCount));
            bufferedWriter.newLine();

            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readLastIndex() {
        File directory = new File("");
        // 临时文件存储路径
        String filePath = directory.getAbsolutePath() + File.separator + "irs";
        File file = new File(filePath + File.separator + ACCIDENT_QUERY_INDEX_FILE);

        try {
            List<String> dataList = FileUtil.readLines(file, StandardCharsets.UTF_8);
            if (CollUtil.isNotEmpty(dataList) && dataList.size() == 2) {
                lastIndex = Long.valueOf(dataList.get(0));
                lastCount = Integer.valueOf(dataList.get(1));
            }
        } catch (Exception e) {
            log.info("读取下标和车牌号失败!");
            e.printStackTrace();
        }
    }

    /**
     * 从IRS事故数据表中更新数据到车辆事故数据表中
     * 
     * @return void
     * @author CMM
     * @since 2023/05/16 10:26
     */
    private void updateAccidentData() {

        // 从IRS事故数据表中更新数据到车辆事故数据表中
        Map<String, List<VehicleAccidentIrsData>> listMap =
            accidentIrsDataService.list().stream().collect(Collectors.groupingBy(VehicleAccidentIrsData::getCarPlate));

        // 获取车牌号
        Set<String> carPlateList =
            accidentIrsDataService.list().stream().map(VehicleAccidentIrsData::getCarPlate).collect(Collectors.toSet());

        // 获取车辆基本信息
        List<NdVehicleBaseInfo> vehicleBaseInfos = vehicleBaseInfoService
            .list(Wrappers.lambdaQuery(NdVehicleBaseInfo.class).in(NdVehicleBaseInfo::getCarPlate, carPlateList));
        Map<String, NdVehicleBaseInfo> vehicleBaseInfoMap =
            vehicleBaseInfos.stream().collect(Collectors.toMap(NdVehicleBaseInfo::getCarPlate, v -> v));

        // 获取企业信息
        Map<Long, Company> companyMap =
            companyService.list().stream().collect(Collectors.toMap(Company::getId, c -> c));

        // 获取已经存在的事故数据
        List<NdVehicleAccident> accidentTmpVas = vehicleAccidentService
            .list(Wrappers.lambdaQuery(NdVehicleAccident.class).in(NdVehicleAccident::getCarPlate, carPlateList));
        Map<String, NdVehicleAccident> accidentMap = accidentTmpVas.stream()
            .collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(a -> a.getCarPlate() + StrPool.SEMICOLON + a.getAccidentTime()))),
                ArrayList::new))
            .stream().collect(Collectors.toMap(d -> d.getCarPlate() + d.getAccidentTime(), d -> d));

        // 获取已经存在的死亡事故数据
        List<NdVehicleAccidentDead> deadAccidentTmpVas = vehicleAccidentDeadService.list(
            Wrappers.lambdaQuery(NdVehicleAccidentDead.class).in(NdVehicleAccidentDead::getCarPlate, carPlateList));
        Map<String, NdVehicleAccidentDead> deadAccidentMap = deadAccidentTmpVas.stream()
            .collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(
                    Comparator.comparing(a -> a.getCarPlate() + StrPool.SEMICOLON + a.getAccidentTime()))),
                ArrayList::new))
            .stream().collect(Collectors.toMap(d -> d.getCarPlate() + d.getAccidentTime(), d -> d));

        for (String carPlate : carPlateList) {
            NdVehicleBaseInfo vehicleBaseInfo = vehicleBaseInfoMap.get(carPlate);
            if (Objects.isNull(vehicleBaseInfo)) {
                //log.info("该车牌号不在系统中!");
                continue;
            }
            //// 查出对应车牌号关联的责任驾驶员
            // String driverName = vehicleBaseInfo.getResponsibleDriverFirst();
            //
            // if (Objects.isNull(driverName)) {
            // log.info("该车牌号没有责任驾驶员!");
            // continue;
            // }
            Long companyId = vehicleBaseInfo.getCompanyId();
            Company company = companyMap.get(companyId);

            // 获取IRS事故数据
            List<VehicleAccidentIrsData> accidentIrsDataList = listMap.get(carPlate);

            for (VehicleAccidentIrsData accidentIrsData : accidentIrsDataList) {
                // 解析获取事故时间等信息
                String jsonStrData = accidentIrsData.getJsonStrData();
                JSONObject jsonObject = JSON.parseObject(jsonStrData);

                // 获取行政区划
                String xzqh = jsonObject.getString("XZQH");
                // 获取区域信息
                Long regionId = regionsCacheHelper.getIdByCode(xzqh);
                String regionName = regionsCacheHelper.getDisplayName(regionId);
                // 获取事故地点
                String sgdd = jsonObject.getString("SGDD");
                // 获取车辆类型
                Integer vehicleType = null;
                if (Objects.nonNull(vehicleBaseInfo)) {
                    vehicleType = vehicleBaseInfo.getVehicleType();
                }
                // 获取受伤人数
                Integer ssrs = jsonObject.getInteger("SSRS");
                // 获取事故日期
                Timestamp sgfssj = jsonObject.getTimestamp("SGFSSJ");
                LocalDateTime accidentTime = LocalDateTimeUtil.of(sgfssj);
                // 获取简要案情
                String jyaq = jsonObject.getString("JYAQ");
                // 获取事故编号
                String sgbh = jsonObject.getString("SGBH");
                // 获取经纬度电子坐标
                String dzzb = jsonObject.getString("DZZB");
                String longitude = null;
                String latitude = null;
                if (StringUtils.isNotBlank(dzzb) && dzzb.contains(StrPool.COMMA)) {
                    String[] split = dzzb.split(StrPool.COMMA);
                    Double longitudeD = Double.valueOf(split[0]);
                    Double latitudeD = Double.valueOf(split[1]);
                    DecimalFormat df = new DecimalFormat("#.###");
                    longitude = df.format(longitudeD);
                    latitude = df.format(latitudeD);
                } else {
                    // 交管事故数据未上传经纬度坐标，从当天的GPS数据中根据车牌号和事故时间查询经纬度
                    LocalDateTime startTime = LocalDateTimeUtil.parse(
                        NdDateUtils.format(accidentTime, DatePattern.NORM_DATETIME_MINUTE_PATTERN),
                        DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_MINUTE_PATTERN));
                    LocalDateTime endTime = LocalDateTimeUtil.parse(
                        NdDateUtils.format(accidentTime.plusMinutes(1), DatePattern.NORM_DATETIME_MINUTE_PATTERN),
                        DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_MINUTE_PATTERN));
                    // 如果跨天了就设置相同地查询边界
                    if (!NdDateUtils.format(startTime, DatePattern.NORM_DATE_PATTERN)
                        .equals(NdDateUtils.format(endTime, DatePattern.NORM_DATE_PATTERN))) {
                        endTime = startTime;
                    }

                    List<VehiclePositionInfo> vehiclePositionInfos;
                    try {
                        vehiclePositionInfos = iVehiclePositionInfoService.dynamicGpsTableHistorySearch(carPlate,
                            accidentTime, endTime, NdDateUtils.format(startTime, "yyyy_MM_dd"));
                        if (CollUtil.isNotEmpty(vehiclePositionInfos)) {
                            VehiclePositionInfo positionInfo;
                            List<VehiclePositionInfo> positionInfoList = vehiclePositionInfos.stream()
                                .filter(v -> v.getUpdateTime().equals(accidentTime)).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(positionInfoList)) {
                                positionInfo = positionInfoList.get(0);
                            } else {
                                // 没有时间完全一样的GPS数据，就取第一个
                                positionInfo = vehiclePositionInfos.get(0);
                            }
                            longitude = String.valueOf(positionInfo.getCarLongitude());
                            latitude = String.valueOf(positionInfo.getCarLatitude());
                        }
                    } catch (Exception e) {
                        // GPS数据中查询不到数据(GPS表可能被删除)
                        log.error(e.getMessage());
                    }
                }

                // 获取当场、24小时、3日内、7日内、30日内死亡人数
                Integer swrs = Objects.nonNull(jsonObject.getInteger("SWRS")) ? jsonObject.getInteger("SWRS") : 0;
                Integer swrs24 = Objects.nonNull(jsonObject.getInteger("SWRS24")) ? jsonObject.getInteger("SWRS24") : 0;
                Integer swrs3 = Objects.nonNull(jsonObject.getInteger("SWRS3")) ? jsonObject.getInteger("SWRS3") : 0;
                Integer swrs7 = Objects.nonNull(jsonObject.getInteger("SWRS7")) ? jsonObject.getInteger("SWRS7") : 0;
                Integer swrs30 = Objects.nonNull(jsonObject.getInteger("SWRS30")) ? jsonObject.getInteger("SWRS30") : 0;
                // 有死亡人数,再插入到死亡事故表中
                if (swrs != 0 || swrs24 != 0 || swrs3 != 0 || swrs7 != 0 || swrs30 != 0) {
                    // 插入数据到死亡事故表中
                    NdVehicleAccidentDead accidentDead = new NdVehicleAccidentDead();
                    // 判断是否已经插入过
                    if (deadAccidentMap.containsKey(carPlate + accidentTime)) {
                        NdVehicleAccidentDead dead = deadAccidentMap.get(carPlate + accidentTime);
                        accidentDead.setId(dead.getId());
                    }
                    if (swrs30 != 0) {
                        accidentDead.setDeathToll(swrs30);
                    } else if (swrs7 != 0) {
                        accidentDead.setDeathToll(swrs7);
                    } else if (swrs3 != 0) {
                        accidentDead.setDeathToll(swrs3);
                    } else if (swrs24 != 0) {
                        accidentDead.setDeathToll(swrs24);
                    } else {
                        accidentDead.setDeathToll(swrs);
                    }
                    accidentDead.setInjuries(ssrs);
                    accidentDead.setRegionId(regionId);
                    accidentDead.setRegionName(regionName);
                    // 获取事故时间
                    accidentDead.setAccidentTime(accidentTime);
                    accidentDead.setAccidentAddress(sgdd);
                    // 装配车牌号、事故驾驶员、企业名称
                    accidentDead.setCarPlate(carPlate);
                    // accidentDead.setAccidentDriver(driverName);
                    accidentDead.setCompanyId(companyId);
                    if (Objects.nonNull(company)) {
                        accidentDead.setCompanyName(company.getName());
                    }
                    // 是否上报默认为未上报
                    accidentDead.setReportStatus(VehicleAccidentReportStatusEnum.UNDER_REPORT.getCode());
                    accidentDead.setBriefCase(jyaq);
                    accidentDead.setAccidentNo(sgbh);
                    accidentDead.setLongitude(longitude);
                    accidentDead.setLatitude(latitude);
                    vehicleAccidentDeadService.saveOrUpdate(accidentDead);
                }
                // 插入到事故表中
                NdVehicleAccident accident = new NdVehicleAccident();
                // 判断事故类型
                if (swrs != 0 || swrs24 != 0 || swrs3 != 0 || swrs7 != 0 || swrs30 != 0){
                    accident.setAccidentType(AccidentTypeEnum.DEAD.getCode());
                } else if (Objects.nonNull(ssrs) && ssrs > 0) {
                    accident.setAccidentType(AccidentTypeEnum.INJURY.getCode());
                }else {
                    accident.setAccidentType(AccidentTypeEnum.OTHER.getCode());
                }
                // 获取已经存在的事故信息
                NdVehicleAccident vehicleAccident = accidentMap.get(carPlate + accidentTime);
                // 获取事故时间
                if (accidentMap.containsKey(carPlate + accidentTime)) {
                    accident.setId(vehicleAccident.getId());
                }
                accident.setInjuries(ssrs);
                if (swrs30 != 0) {
                    accident.setDeathToll(swrs30);
                } else if (swrs7 != 0) {
                    accident.setDeathToll(swrs7);
                } else if (swrs3 != 0) {
                    accident.setDeathToll(swrs3);
                } else if (swrs24 != 0) {
                    accident.setDeathToll(swrs24);
                } else {
                    accident.setDeathToll(swrs);
                }
                accident.setRegionId(regionId);
                accident.setRegionName(regionName);
                // 获取事故时间
                accident.setAccidentTime(accidentTime);
                accident.setAccidentAddress(sgdd);
                // 装配车牌号、事故驾驶员、车辆类型、企业名称
                accident.setCarPlate(carPlate);

                // accident.setAccidentDriver(driverName);
                accident.setVehicleType(vehicleType);
                accident.setCompanyId(companyId);
                if (Objects.nonNull(company)) {
                    accident.setCompanyName(company.getName());
                }
                // 是否上报默认为未上报
                accident.setReportStatus(VehicleAccidentReportStatusEnum.UNDER_REPORT.getCode());
                accident.setBriefCase(jyaq);
                accident.setAccidentNo(sgbh);
                accident.setLongitude(longitude);
                accident.setLatitude(latitude);
                vehicleAccidentService.saveOrUpdate(accident);
            }
        }
    }

}
