AutomaticSch.java 21.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
package com.bsth.data.zndd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bsth.data.BasicData;
import com.bsth.data.adjg.domain.LargeGap;
import com.bsth.data.directive.DayOfDirectives;
import com.bsth.data.gpsdata_v2.GpsRealData;
import com.bsth.data.gpsdata_v2.entity.GpsEntity;
import com.bsth.data.gpsdata_v2.rfid.RfidHttpLoader;
import com.bsth.data.gpsdata_v2.rfid.entity.RfidInfo;
import com.bsth.data.schedule.DayOfSchedule;
import com.bsth.data.schedule.ScheduleComparator;
import com.bsth.data.schedule.edit_logs.entity.SchEditInfo;
import com.bsth.data.schedule.edit_logs.service.SchEditInfoService;
import com.bsth.data.schedule.late_adjust.LateAdjustHandle;
import com.bsth.entity.directive.D60;
import com.bsth.entity.realcontrol.ScheduleRealInfo;
import com.bsth.entity.zndd.StationPeopleLogger;
import com.bsth.entity.zndd.ZnddYuAn;
import com.bsth.repository.StationRouteRepository;
import com.bsth.service.directive.DirectiveService;
import com.bsth.service.realcontrol.ScheduleRealInfoService;
import com.bsth.service.zndd.ZnddLoggerService;
import com.bsth.service.zndd.ZnddYuAnService;
import com.bsth.util.DateUtils;
import com.bsth.util.HttpClientUtils;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自动检测调度异常
 */
@Component
public class AutomaticSch {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    GpsRealData gpsRealData;
    @Autowired
    DayOfSchedule dayOfSchedule;
    @Autowired
    DayOfDirectives dayOfDirectives;
    @Autowired
    ScheduleRealInfoService scheduleRealInfoService;
    @Autowired
    DirectiveService directiveService;
    @Autowired
    StationRouteRepository stationRouteRepository;
    @Autowired
    OutEntrance outEntrance;
    @Autowired
    carMonitor carMonitor;
    @Autowired
    BasicData basicData;
    @Autowired
    ZnddYuAnService znddYuAnService;

    @Autowired
    ZnddLoggerService znddLoggerService;
    @Autowired
    SchEditInfoService schEditInfoService;


    private static SimpleDateFormat sdfHHmm = new SimpleDateFormat("HH:mm");
    private static SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");

    private static Comparator<ScheduleRealInfo> cpm = new ScheduleComparator.DFSJ2();
    private Map<String,Long> drivreMap =new HashMap<>(); //自动重发map

    String urldkl = "http://10.10.200.202:5580/monitor/api/getMonitorInfoByDay?key=1&solt=1111&t=1&dayStr="; //大间隔接口

    //http://10.10.200.201:8083/wxk-prod-api/service-api/lggj/schedule/drByInfo  维修接口
    String urldkls = "http://10.10.200.140:13089/bsth_passengerflow/klbus/currentInsideNum.do"; //满载接口
    private Map<Long,Long> SFMAP = new HashMap<>();

    //满载
    public  void mz(){
        try {

            List<ScheduleRealInfo> sr = dayOfSchedule.findByBcType("W9G-041","normal");
            ts(addStationPeople(sr.get(5), "MZ", 0L));//第二种 设备未离线 出站时间内未出站

            String chartStr = JSON.toJSONString(sr.get(5));
            logger.info("满载--"+chartStr);
        }
        catch (Exception e){
            logger.error("满载------------------",e);
        }
    }

    //大间隔的情况
    public void dfTz(int k ){
        try{
            StringBuilder sb = HttpClientUtils.get(urldkl + sdfMonth.format(new Date()));
            if (sb == null)
                return;
            JSONObject obj = JSON.parseObject(sb.toString());
            List<LargeGap> lgs = JSON.parseArray(obj.getString("largeGap"), LargeGap.class);
            ScheduleRealInfo sch;
            //数据转换 并推送
            for (LargeGap lg : lgs){
                 if(dayOfSchedule.executeCurr(lg.getNbbm()) != null){
                     sch= dayOfSchedule.executeCurr(lg.getNbbm());
                 }else {
                     continue;
                 }
                 Long t0 = new Date().getTime()  - (1000 * 60 * 2);
                 Long t1 = t0 - (1000 * 60 * 2);
                 Long t2 = t0 + (1000 * 60 * 2);
                 //判断当前间隔是否出现过并且在当前时间段内   大于2分钟  小于1分钟的时间之内
                 if (SFMAP.get(lg.getId()) == null) {
                     if (k == 0) {
                         if (lg.getlGType() == 0) {
                             ts(ConvertDJK(lg, sch, "FCJG"));
                             SFMAP.put(lg.getId(), lg.getTsTime());
                             String chartStr = JSON.toJSONString(sch);
                             logger.info("发车大间隔--" + chartStr);
                         }
                     } else {
                         if (lg.getlGType() != 0) {
                             ts(ConvertDJK(lg, sch, "DJG"));
                             SFMAP.put(lg.getId(), lg.getTsTime());
                             String chartStr = JSON.toJSONString(sch);
                             logger.info("行车大间隔--" + chartStr);
                         }
                     }
                 }
                 //大于10000条的时候开始清理map
                 if (SFMAP.size() > 10000){
                     for (Map.Entry<Long, Long> m : SFMAP.entrySet()){
                         if(m.getValue() < DateUtils.getTimestamp()){
                             SFMAP.remove(m.getKey());
                         }
                     }
                 }
            }

        }catch (Exception e){
            logger.error("大间隔推送失败------------------",e);
        }
    }

    //实发未发检测 -- 车辆GPS掉线的情况下,车辆该出站了
    /**
     * 1。已过待发时间还没发车的
     * 2.设备离线
     * --上一班次还没有抵达终点不做操作
     */
    public void sftz(){
        logger.warn("实发未发扫描开始");
        try {
            //获取所有线路
            Map<String, String> lineMap =  BasicData.lineCode2NameMap;
            for (Map.Entry<String, String> t : lineMap.entrySet()){
                List<ScheduleRealInfo> srList = dayOfSchedule.findByLineCode(t.getKey());
                for (ScheduleRealInfo sr : srList){
                    //1.离线 2.实发时间为空 3.已过待发时间还没发车的
                    long time = System.currentTimeMillis();//实际时间+2分钟
                    //超过待发时间  实发时间还是null的
                    if (sr.getFcsjT() + (1000 * 60 * 3) < time && sr.getFcsjT() + (1000 * 60 * 7) > time) {

                        //第一种 设备离线的情况下改出站
                        Integer staus = 0; //状态
                        if (StringUtils.isEmpty(sr.getFcsjActual())
                                && (sr.getBcType().equals("normal") || sr.getBcType().equals("region"))
                                && (StringUtils.isEmpty(sr.getRemarks()) || sr.getRemarks().equals("_智能调度-异常实发"))) {

                            GpsEntity gps = gpsRealData.getByNbbm(sr.getClZbh());
                            //当前设备离线的情况
                            //1。一直没收到gps
                            //2.gps长时间离线的情况下
                            //3.人为调整过的都跳过
                            if (gps == null || gps.getTimestamp() + (1000 * 60 * 5) < time || (gps.getAbnormalStatus() != null && gps.getAbnormalStatus().equals("offline"))) {
                                String sfsj = null;
                                //rfid 判断
                                List<RfidInfo> list = RfidHttpLoader.load();
                                for (RfidInfo ri : list) {
                                    if (ri.getRecogTime() != null && ri.getRecogTime().getTime() > System.currentTimeMillis() - 300000) {
                                        //最新的rfid是出站状态
                                        if (ri.getNbbm().equals(sr.getClZbh())){
                                            sfsj = sdfHHmm.format(ri.getInoutStation().getTimestamp());
                                        }
                                        if (ri.getNbbm().equals(sr.getClZbh()) && ri.getInoutStation().getInout() == 0) {
                                            sfsj = sdfHHmm.format(ri.getInoutStation().getTimestamp());
                                        }
                                    }
                                }
                                sr.setFcsjActual(sfsj);
                                ts(addStationPeople(sr, "SFTZ_1", 0L));
                                Gson gson = new Gson();
                                String chartStr = gson.toJsonTree(sr).toString();
                                logger.info("实发调整--" + chartStr);
                            }
                        }
                    }
                }

            }
        }catch (Exception e){
            logger.error("自动调度,实发未发推送失败---",e);
        }
        logger.warn("实发未发扫描结束");
    }

    //实发撤销检测 -- 出现快一慢三的情况  && 指令重发
    public void sfCX(){
        //查询所有班次
        //remark 人工干预过的的不检测
        try {

            Map<String, String> lineMap =  BasicData.lineCode2NameMap;
            List<ScheduleRealInfo>  oldSchDateList;
            String lineCode;
            for (Map.Entry<String, String> ts : lineMap.entrySet()){
                lineCode =ts.getKey();
                oldSchDateList = dayOfSchedule.findByLineCode(lineCode);

                Map m = new HashMap();
                //排序
                Collections.sort(oldSchDateList, new ScheduleComparator.FCSJ());
                for (ScheduleRealInfo t : oldSchDateList){
                    // 发车误点
                    if (t.getDfsj() != null && t.getFcsjActual() != null
                            && (t.getBcType().equals("normal") || t.getBcType().equals("region"))) {

                        long sjc = t.getFcsjActualTime() - t.getDfsjT();
                        long time = System.currentTimeMillis();//当前时间

                        if (t.getDfsjT() > time) {
                            //快1慢3
                            if (sjc >= -1 * 60 * 1000 && sjc <= 3 * 60 * 1000) {
                                continue;
                            } else {
                                //备注不为null时,查询是否有调度操作记录
                                List<SchEditInfo>  seiList = new ArrayList<>();
                                if (!StringUtils.isEmpty(t.getRemarks())){
                                    Map msp = new HashMap();
                                    msp.put("schId_eq",t.getId());
                                    seiList = (List<SchEditInfo>) schEditInfoService.list(msp);
                                    //有操作记录的跳过
                                    if (seiList.size() > 0)
                                        continue;
                                }
                                //异常实发
                                ts(addStationPeople(t, "YCSF", 0l));
                                Gson gson = new Gson();
                                String chartStr = gson.toJsonTree(t).toString();
                                logger.info("实发撤销--" + chartStr);
                            }
                        }
                    }

                }
            }
        }catch (Exception e){
            logger.error("实发撤销推送接口出错-----------",e);
        }
    }

    public Boolean isLines(String line) {
        //新临专线,新芦专线,临港5路,浦东7路,浦东91路,医疗线
        //线路书院2路、万祥2路、泥城1路、泥城2路、芦潮港1路、浦东56路、临港8路、1077路、申港1路、1043路
        if (line.equals("10636") || line.equals("200828") || line.equals("211208") || line.equals("230226") || line.equals("201012") ||
                line.equals("11077") ||
                line.equals("11078") ||
                line.equals("12101") ||
                line.equals("12103") ||
                line.equals("12106") ||
                line.equals("12153") ||
                line.equals("60041") ||
                line.equals("88813") ||
                line.equals("181221") ||
                line.equals("220825") ||
                line.equals("240829"))
            return Boolean.valueOf(true);
        return Boolean.valueOf(false);
    }

    /**
     * 指令重发 -- 芦潮港1路
     * 指令下发后设备未响应后  5分钟后重新发送一次 还未响应的话 未来一小时不自动发送该设备
     */
    public void drivresponse(){
        logger.warn("指令重发扫描开始");
        try {
            Map<String,Object> tempmap =new HashMap<>();
            //所有缓存指令
            Collection<D60> dptArray =  dayOfDirectives.all60();

            Map<String, String> lineMap =  BasicData.lineCode2NameMap;
            List<ScheduleRealInfo>  oldSchDateList;
            String lineCode;
            for (Map.Entry<String, String> ts : lineMap.entrySet()) {
                lineCode = ts.getKey();
               /* if(isLines(lineCode)) {*/
                    oldSchDateList = dayOfSchedule.findByLineCode(lineCode);
                    for (ScheduleRealInfo t : oldSchDateList) {
                        //指令重发
                        //1.班次已经执行过的
                        //2.驾驶员未确认的
                        Long t1 = 1000L * 60 * 5;
                        Long sj = new Date().getTime();
                        if (t.getStatus() == 2 && t.getDirectiveState() != 200 && t.getBcType().equals("normal")) {
                            //还未下发的
                            if (drivreMap.get(t.getClZbh()) == null) {
                                //下发或者处置
                                drivreMap.put(t.getClZbh(), new Date().getTime());
                                directiveService.send60DispatchZndd(t.getId(), "智能调度");

                                //下发实际超过5分钟的
                            } else if (drivreMap.get(t.getClZbh()) + t1 <= sj) {
                                directiveService.send60DispatchZndd(t.getId(), "智能调度");
                                //更新下发时间
                                drivreMap.put(t.getClZbh(), new Date().getTime());
                                //下发时间未超过5分钟返回
                            }
                        }
                    /*}*/
                }
            }
        }catch (Exception e){
            logger.error("自动调度,指令重发---",e);
        }
        logger.warn("指令重发扫描结束");
    }
    //误点检测 调度有的-LateAdjustHandle
    public Map wd(){
        //推送
        try{
            List<ScheduleRealInfo> all = new ArrayList<>(dayOfSchedule.findAll());
            Collections.sort(all, cpm);
            long t = System.currentTimeMillis();
            int size = all.size();
            ScheduleRealInfo sch;
            for(int i = 0; i < size; i ++){
                sch = all.get(i);
                if(sch.getDfsjT() > t)
                    break;

                if(sch.isLate()) //演示使用 不跳过
                    continue;

                if(sch.getStatus() == 0
                        && StringUtils.isEmpty(sch.getFcsjActual())){

                    //检查应发未到 当前班次无起点到达时间
                    if(StringUtils.isEmpty(sch.getQdzArrDatesj())){
                        ScheduleRealInfo prev = dayOfSchedule.prev(sch);
                        //上一个班次也没有实际终点到达时间
                        if(prev != null && StringUtils.isEmpty(prev.getZdsjActual()) && (sch.getBcType().equals("normal")|| sch.getBcType().equals("region"))){
                            //进入误点调整程序
                            LateAdjustHandle.putLate(sch);
                            List<Map> dzList = carMonitor.carMonitor(prev.getXlBm(), prev.getXlDir(), prev.getZdzCode());  //信息发布接口
                            for (Map m : dzList){
                                if (basicData.nbbmCompanyPlateMap.get(prev.getClZbh()) != null && m.get("terminal").equals(basicData.nbbmCompanyPlateMap.get(prev.getClZbh()).replaceAll("-",""))){
                                    sch.setRemark(m.get("sj").toString());
                                    ts(addStationPeople(sch, "WD", 0L));
                                    String chartStr = JSON.toJSONString(sch);
                                    logger.info("误点--"+chartStr);
                                }
                            }
                        }
                    };
                }
            }
        }catch (Exception e){
            logger.error("误点检测推送接口出错---",e);
        }
        return null;
    }



    public void ts(Map m) throws ParseException {

        //储存日志
        StationPeopleLogger splogger = new StationPeopleLogger();
        splogger.setType(m.get("type").toString());
        splogger.setLineName(m.get("lineName").toString());
        splogger.setLineCode(m.get("lineCode").toString());
        splogger.setRq(sdf.format(new Date()));
        splogger.setRqStr(m.get("rqStr").toString());
        splogger.setXlDir(m.get("xlDir").toString());
        splogger.setFcsj(m.get("fcsj").toString());
        splogger.setClZbh(m.get("clzbh").toString());
        znddLoggerService.save(splogger);

        outEntrance.Znddjk(m);//推送
    }




    //大间隔数据转换
    public Map ConvertDJK(LargeGap lg,ScheduleRealInfo sch,String type){
        Map sp = new HashMap();
        sp.put("uuid",UUID());
        sp.put("lineCode",lg.getLineCode());
        sp.put("lineName",lg.getLineName() );
        sp.put("rqStr",lg.getDateStr());
        sp.put("rq",sdfHHmm.format(lg.getTsTime()));
        sp.put("type",type);
        sp.put("xlDir",lg.getUpDown());
        sp.put("numType",lg.getIntervalMinute());
        sp.put("stationCode",lg.getStationName());
        sp.put("stationName",lg.getStationName());
        sp.put("clzbh",lg.getNbbm());
        sp.put("fcsj",lg.getBcfcsj());
        sp.put("ids",sch.getId());
        sp.put("lg",lg);
        sp.put("sch",sch);
        return sp;
    }

    //大间隔数据转换
    public Map ConvertDKL(Map m){
        Map sp = new HashMap();
        sp.put("uuid",UUID());
        sp.put("lineCode",m.get("lineCode"));
        sp.put("lineName",m.get("lineName"));
        sp.put("rqStr",sdf.format(new Date()));
        sp.put("rq",sdfHHmm.format(new Date())); //检测到时间
        return sp;
    }


    //转换
    public Map addStationPeople(ScheduleRealInfo info,String type,Long sst) throws ParseException{
        Map sp = new HashMap();
        sp.put("uuid",UUID());
        sp.put("lineCode",info.getXlBm());
        sp.put("lineName",info.getXlName() );
        sp.put("rqStr",info.getScheduleDateStr());
        sp.put("rq",sdfHHmm.format(new Date())); //检测到时间
        sp.put("type",type);
        sp.put("xlDir",info.getXlDir());
        sp.put("numType",sst);
        sp.put("fcsj",info.getFcsj());
        sp.put("id",info.getId());
        sp.put("clzbh",info.getClZbh());
        sp.put("ids",info.getId());
        sp.put("sch",info);
        return sp;
    }
    //生成唯一id
    public static String  UUID(){
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        uuid=uuid.substring(0,10);
        StringBuilder builder=new StringBuilder();
        builder.append(uuid)
                .append(getRandom(3));
        return builder.toString();
    }


    private static long getRandom(long n) {
        long min = 1, max = 9;
        for (int i = 1; i < n; i++) {
            min *= 10;
            max *= 10;
        }
        long rangeLong = (((long) (new Random().nextDouble() * (max - min)))) + min;
        return rangeLong;
    }

    //调度预案的配置情况
    public String  penum(String type, String types){
        List<ZnddYuAn> znyanList = znddYuAnService.yuanList(type,types);
        for (ZnddYuAn zn : znyanList){
            Map<String, Object> jsonMap = JSON.parseObject(zn.getJsonDate(), new TypeReference<HashMap<String, Object>>() {});

            String typetext =  jsonMap.get("type").toString();
            List<Map> listnodes = (List<Map>) jsonMap.get("nodes");
            if(typetext.equals("pz")){
                if(listnodes.get(1) != null){
                    return listnodes.get(1).get("value").toString();
                }
            }
        }
        return null;
    }

    public int getPenum(String type, String types){
        int count =10;
        String penum=penum(type,types);
        if(penum!=null){
            String regEx="[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(penum);
            String result=m.replaceAll("").trim();
            if(!result.equals("")){
                count=Integer.parseInt(result);
            }
        }
        return count;
    }
}