OutEntrance.java 20.9 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 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
package com.bsth.data.zndd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsth.common.ResponseCode;
import com.bsth.data.BasicData;
import com.bsth.data.schedule.DayOfSchedule;
import com.bsth.data.schedule.ScheduleComparator;
import com.bsth.data.schedule.late_adjust.LateAdjustHandle;
import com.bsth.entity.DKLInfo;
import com.bsth.entity.realcontrol.ScheduleRealInfo;
import com.bsth.entity.zndd.StationSignsLogger;
import com.bsth.entity.zndd.znddStatus;
import com.bsth.repository.zndd.ZnddStatusRepository;
import com.bsth.service.DKLInfoService;
import com.bsth.service.zndd.LoggerZnddService;
import com.bsth.util.HttpClientUtils;
import com.bsth.util.SignUtils;
import com.bsth.websocket.handler.SendUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 对外接口
 * 与站牌、小程序对接接口
 * 调度预案通用接口
 */
@RestController
@RequestMapping("/out")
public class OutEntrance {

    @Autowired
    SendUtils sendUtils;
    @Autowired
    DayOfSchedule dayOfSchedule;


    @Value("${dc.imgurl}")
    private  String imgurl; //存储图片地址

    private  String profile = "profile"; //存储图片地址*/

    @Value("${baidu.ak}")
    private  String ak; //百度api秘钥*/

    static String url= "http://58.34.52.130:9777/xxfb/carMonitor?";  //信息发布地址
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    carMonitor carMonitor;

    @Autowired
    AutomaticSch automaticSch;

    @Autowired
    private DKLInfoService dklInfoService;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    ZnddStatusRepository znddStatusRepository;

    @Autowired
    BasicData basicData;

    @Autowired
    ZnddMessage znddMessage;

    @Autowired
    LoggerZnddService loggerZnddService;

     //调度屏小程序接口。
     @RequestMapping(value = "/OutCar", method = RequestMethod.POST)
     public Map OutCarOutCar(@RequestParam Map m,@RequestBody StationSignsLogger ssLogger) {
         Map rtn = new HashMap<>();
         try {
             logger.info("催发接口调用----");
             if(!SignUtils.validation(ssLogger.getTimestamp(),ssLogger.getSign())){
                 rtn.put("status", "验证失败");
                 return rtn;
             }
             m.put("image", uploadBase64Img(ssLogger.getImage()));
             m.put("lineCode", ssLogger.getLineCode());
             m.put("stationName",BasicData.stationCode2NameMap.get(ssLogger.getLineCode()+"_"+ssLogger.getDir()+"_"+ssLogger.getStation()));
             m.put("lineName",BasicData.lineCode2NameMap.get(ssLogger.getLineCode()));
             m.put("num",ssLogger.getNum());
             m.put("dir",ssLogger.getDir());
             m.put("calleeId",ssLogger.getCalleeId());
             //线调页面推送
             int count=automaticSch.getPenum("DKL","0");
             if(ssLogger.getNum()>count){
                 sendUtils.stationcf(m);
             }


             //查询班次情况自动回复 --拥堵
             //当前日期
             List<Map> dzList = carMonitor.carMonitor(ssLogger.getLineCode(), ssLogger.getDir(), ssLogger.getStation());  //信息发布接口
             if (dzList.size() > 0){
                 String lon=dzList.get(0).get("lon").toString();
                 String lat=dzList.get(0).get("lat").toString();
                 String nbbm=dzList.get(0).get("nbbm").toString();
                 String road=dzList.get(0).get("road").toString();
                 String trafficStatus=getTraffic(nbbm,lon,lat);
                 String s="";
                 if(!"畅通".equals(trafficStatus)){
                     s=road+trafficStatus+",";
                 }
                 rtn.put("message",s+"亲爱的乘客,我们的调度员已接收到通知,车辆预计还有"+dzList.get(0).get("sj")+"抵达,请稍等片刻");
             }else {
                 //第一个班次
                 //所有应发未到的班次--晚点的情况
                 Collection<ScheduleRealInfo> all = LateAdjustHandle.allLateSch();
                 for (ScheduleRealInfo schc : all) {
                     if(schc.getXlBm().equals(m.get("lineCode"))) {
                         Long schId = schc.getId();
                         ScheduleRealInfo sch = null;
                         if (schId != null)
                             sch = dayOfSchedule.get(schId);

                         ScheduleRealInfo prev = dayOfSchedule.prev(sch);
                         List<Map> dzLists = carMonitor.carMonitor(prev.getXlBm(), prev.getXlDir(), prev.getZdzCode());  //信息发布接口
                         for (Map mst : dzLists) {
                             //匹配到当前车辆
                             if (basicData.nbbmCompanyPlateMap.get(prev.getClZbh()) != null && mst.get("terminal").equals(basicData.nbbmCompanyPlateMap.get(prev.getClZbh()).replaceAll("-", ""))) {
                                 if (sch.getXlBm().equals(schc.getXlBm())) {
                                     rtn.put("message", "非常抱歉,车辆因路上交通拥堵,预计还需要" + mst.get("sj").toString() + "抵达,请稍等片刻");
                                     rtn.put("status", ResponseCode.SUCCESS);
                                     return rtn;
                                 }
                             }
                         }
                     }
                 }



                 //筛选方向 -- 正常班次未到发车时间
                 List<ScheduleRealInfo> rs = dayOfSchedule.findByLineAndUpDown(ssLogger.getLineCode(),Integer.parseInt(ssLogger.getDir()));
                 if(rs.size()>0){
                     //排序
                     Collections.sort(rs,new ScheduleComparator.FCSJ());
                     SimpleDateFormat sdf= new SimpleDateFormat("HH:mm");
                     String sjtext = null;
                     LocalTime t1 = LocalTime.parse(sdf.format(new Date()), DateTimeFormatter.ofPattern("HH:mm"));
                     for (ScheduleRealInfo sr:rs) {
                         LocalTime t2 = LocalTime.parse(sr.getFcsj(), DateTimeFormatter.ofPattern("HH:mm"));
                         //最近的运营班次
                         if(t2.isAfter(t1) && (sr.getBcType().equals("normal")||sr.getBcType().equals("region"))){
                             sjtext = sr.getFcsj();
                             break;
                         }
                     }
                     if(sjtext!=null){
                         rtn.put("message","亲爱的乘客,我们的调度员已接收到通知,车辆将按照计划,在"+sjtext+"准时发车,请稍等片刻");
                     }else {
                         rtn.put("message","当日运营已结束");
                     }
                 }else {
                     rtn.put("message","当日运营已结束");
                 }

             }

             rtn.put("status",ResponseCode.SUCCESS);
         } catch (Exception e) {
             rtn.put("status", ResponseCode.ERROR);
             logger.error("",e);
         }
         return rtn;
     }


    @RequestMapping(value = "/klyj", method = RequestMethod.POST)
    public Map klyj(@RequestBody JSONObject jsonObject) {
        Map rtn = new HashMap<>();
        try {
            logger.info("大客流接口调用----");
            if(!SignUtils.validation(Long.parseLong(jsonObject.getString("timestamp")),jsonObject.getString("sign"))){
                rtn.put("status", "验证失败");
                return rtn;
            }
            //大客流开关
            List<znddStatus> znddStatusList = (List<znddStatus>) znddStatusRepository.findAll();
            Boolean isType = false;
            String excuteStatus = null;
            for (znddStatus zs : znddStatusList) {
                if (zs.getType().equals("dkl")) {
                    isType = true;
                    excuteStatus = zs.getExcuteStatus();
                }
            }

            if (!isType){
                logger.info("大客流接口未开启--------------");
                rtn.put("status",ResponseCode.SUCCESS);
                return rtn;
            }

            String num=jsonObject.getString("num");
            int count=automaticSch.getPenum("DKL","0");
            if(Integer.parseInt(num)<count){
                logger.info("大客流人数--"+num);
                rtn.put("status",ResponseCode.SUCCESS);
                return rtn;
            }
            String image=jsonObject.getString("image");
            String img=uploadBase64Img(image);
            JSONArray jsonArray = jsonObject.getJSONArray("stations");
            LocalTime localTime=LocalTime.now();
            DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("HH:mm");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject line=jsonArray.getJSONObject(i);
                String lineCode = line.get("lineCode").toString();
                String stationCode = line.get("stationCode").toString();
                String dir = line.get("dir").toString();
                imgMap.put(lineCode+"_"+dir,img);
                DKLInfo dklInfo =new DKLInfo();
                dklInfo.setLineCode(stationCode);
                String lineName=BasicData.lineCode2NameMap.get(lineCode);
                String stationName=BasicData.stationCode2NameMap.get(lineCode+"_"+dir+"_"+stationCode);
                dklInfo.setLineName(lineName);
                dklInfo.setStationCode(stationCode);
                dklInfo.setStationName(stationName);
                dklInfo.setNum(Integer.parseInt(num));
                dklInfo.setUpDown(dir);
                dklInfo.setImage(img);
                dklInfoService.save(dklInfo);
                if(Integer.parseInt(num)<count){
                    continue;
                }
                Map m = new HashMap();
                m.put("image", img);
                m.put("stationCode", stationCode);
                m.put("lineCode", lineCode);
                m.put("stationName",stationName);
                m.put("lineName",lineName);
                m.put("num",num);
                m.put("xlDir",dir);
                m.put("excuteStatus",excuteStatus);
                List<ScheduleRealInfo> srList=dayOfSchedule.findByLineAndUpDown(lineCode,Integer.parseInt(dir));
                List<ScheduleRealInfo> sl=new ArrayList<>();
                for (ScheduleRealInfo scheduleRealInfo : srList) {//筛选出运营班次
                    if((scheduleRealInfo.getBcType().equals("normal")||scheduleRealInfo.getBcType().equals("region"))){
                        sl.add(scheduleRealInfo);
                    }
                }
                sl.sort(new Comparator<ScheduleRealInfo>() {//按发车时间排序
                    @Override
                    public int compare(ScheduleRealInfo o1, ScheduleRealInfo o2) {
                        return o1.getFcsj().compareTo(o2.getFcsj());
                    }
                });
                ScheduleRealInfo schedule = null;
                ScheduleRealInfo schedule2 = null;
                for (int i1 = 0; i1 < sl.size(); i1++) {//最近的已发车班次
                    ScheduleRealInfo scheduleRealInfo=sl.get(i1);
                    LocalTime fcsj=LocalTime.parse(scheduleRealInfo.getFcsj(),dateTimeFormatter);
                    if(fcsj.isAfter(localTime)){
                        schedule =sl.get(i1-1);
                        if(i1<sl.size()){
                            schedule2 =sl.get(i1);
                        }
                        break;
                    }
                }
                //线调页面推送
                if(schedule!=null){
                    m.put("sch",schedule);
                    m.put("uuid",AutomaticSch.UUID());
                    m.put("rq",localTime.format(dateTimeFormatter)); //检测到时间
                    m.put("ids",AutomaticSch.UUID());
                    m.put("type","KLYJ");
                    LocalTime fcsj = LocalTime.parse(schedule2.getDfsj(),DateTimeFormatter.ofPattern("HH:mm"));
                    LocalTime now = LocalTime.now();
                    if(Duration.between(now,fcsj).toMinutes()==0){
                        m.put("msg","下一个班次即将发车");
                    }else {
                        m.put("msg","下一个班次预计还有"+ Duration.between(now,fcsj).toMinutes() +"分钟发车");
                    }

                    sendUtils.klyj(m);
                }

            }
            rtn.put("status",ResponseCode.SUCCESS);
        } catch (Exception e) {
            rtn.put("status", ResponseCode.ERROR);
            logger.error("",e);
        }
        return rtn;
    }

    /*
    智能调度接口--通用测试接口
     */
    @RequestMapping(value="/zjket",method = RequestMethod.GET)
    public Map Znddjk(@RequestParam Map m) {
        Map rtn = new HashMap<>();

        try {
            List<ScheduleRealInfo> sr = dayOfSchedule.findByBcType(m.get("nbbm").toString(),"normal");
            automaticSch.ts(automaticSch.addStationPeople(sr.get(Integer.parseInt(m.get("num").toString())), m.get("type").toString(), 0L));//测试接口
            rtn.put("status",ResponseCode.SUCCESS);
        } catch (Exception e) {
            rtn.put("err",ResponseCode.ERROR);
            logger.info("智能调度推送----",e);
        }

        return rtn;
    }


    //大客流消息测试接口
    @RequestMapping(value="/znMeeage",method = RequestMethod.GET)
    public Map znddMessagejk(@RequestParam Map m){
        Map rtn = new HashMap<>();
        try {
            List<ScheduleRealInfo> sr = dayOfSchedule.findByBcType(m.get("nbbm").toString(),"normal");
            znddMessage.saveSch(sr.get(Integer.parseInt(m.get("num").toString())));
            rtn.put("status",ResponseCode.SUCCESS);
        } catch (Exception e) {
            rtn.put("err",ResponseCode.ERROR);
            logger.info("大客流消息推送----",e);
        }
        return rtn;
    }




    /**
     * 保存base64图片
     * @param  base base64文件
     * @param  (示例:D:\\1.png)
     * @return
     */
    public  String uploadBase64Img(String base) throws Exception {

        //获取年月日
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //将年、月、日存入数组
        String[] time = sdf.format(new Date()).split("-");
        // 文件保存地址 默认地址为xxxx/年/月/日
        String url = "avat/"+time[0]+"/"+time[1]+"/"+time[2];
        String destDir = imgurl+"/"+url;
        
        
        base=base.replaceAll("data:image/png;base64,","");
        Base64.Decoder decoder =  Base64.getDecoder();
        byte[] imageByte = null;
        try{
            imageByte = decoder.decode(base);
            for (int i = 0; i < imageByte.length; ++i) {
                if (imageByte[i] < 0) {// 调整异常数据
                    imageByte[i] += 256;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (imageByte.length>0) {
            try {
                String filepath = destDir;
                File destfile = new File(filepath);
                if (!destfile.exists()) {
                    destfile.mkdirs();
                }
                //文件新名称
                String fileNameNew = System.currentTimeMillis()+"_"+AutomaticSch.UUID()+ ".png";
                File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);
                // 将字符串转换成二进制,用于显示图片
                // 将上面生成的图片格式字符串 imgStr,还原成图片显示
                InputStream in = new ByteArrayInputStream(imageByte);
                FileOutputStream fos = new FileOutputStream(f);
                byte[] buf = new byte[1024];
                int length;
                length = in.read(buf, 0, buf.length);

                while (length != -1) {
                    fos.write(buf, 0, length);
                    length = in.read(buf);
                }
                fos.flush();
                fos.close();
                in.close();
                return "/"+profile + "/" + url+"/"+fileNameNew;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            }
        }
        return null;
    }

    /**
     * 转移文件图片
     * @param  url 文件路径
     * @param  (示例:D:\\1.png)
     * @return
     */
    public String moveImg(String url) throws Exception {
        try {
            String file = url.replace("/"+profile+"/avat",imgurl+"/img");
            String destDir = file.substring(0,file.lastIndexOf("/"));
            File destPath = new File(destDir);
            if (!destPath.exists()) {
                destPath.mkdirs();
            }
            Path sourceFile= Paths.get(url.replace("/"+profile,imgurl));
            Path destFile= Paths.get(url.replace("/"+profile+"/avat",imgurl+"/img"));
            Files.copy(sourceFile, destFile,StandardCopyOption.REPLACE_EXISTING);
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static ConcurrentMap<String, Map<String,Object>> trafficMap = new ConcurrentHashMap<>();
    public String getTraffic(String nbbm,String lon,String lat){
        Map<String,Object> traffic=trafficMap.get(nbbm);
        try {
            if(traffic==null||(System.currentTimeMillis()-(long)traffic.get("time")>60*1000)){//无数据或者超过有效期重新查询路况
                String trafficStatus="畅通";
                String url="https://api.map.baidu.com/traffic/v1/around?" +
                        "ak="+ak+"&center="+lon+","+lat+"&radius=100&coord_type_input=wgs84";
                String res=HttpClientUtils.get(url).toString();
                JSONObject jsonObject = JSONObject.parseObject(res);
                if((int)jsonObject.get("status")==0){
                    JSONObject evaluation= jsonObject.getJSONObject("evaluation");
                    trafficStatus=evaluation.getString("status_desc");
                }
                traffic=new HashMap<>();
                traffic.put("trafficStatus",trafficStatus);
                traffic.put("time",System.currentTimeMillis());
                trafficMap.put(nbbm,traffic);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return traffic.get("trafficStatus").toString();
    }

/*
    @Scheduled(cron = "0 0 0 * * ?")
    public void clearImg(){
        try {
            LocalDateTime date =LocalDateTime.now().minusDays(7);
            String[] d=date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).split("-");
            File folder=new File(imgurl+"/avat/"+d[0]+"/"+d[1]+"/"+d[2]);
            delete(folder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/

    public static void delete(File folder) throws Exception{
        if(folder.isDirectory()) {
            File[] files = folder.listFiles();
            if(files != null) { // 如果文件夹为空,files可能为null
                for(File file : files) {
                    delete(file); // 递归删除子文件夹和文件
                }
            }
        }
        folder.delete(); // 删除空文件夹或者文件
    }

    private static Map<String,String> imgMap =new HashMap<>();
    //调度获取站台视频
    @RequestMapping(value = "/getStationVideo", method = RequestMethod.GET)
    public String getStationVideo(@RequestParam Map m) {
        if (m.get("lineCode")==null || m.get("upDown")==null){
            return null;
        }
        String sql="select url from station_video where line_code ='"+m.get("lineCode")+"' and up_down ='"+m.get("upDown")+"'";
        String url= null;
        try {
            url = jdbcTemplate.queryForObject(sql,String.class);
        } catch (DataAccessException e) {
            return null;
        }
        return url;
    }

    //调度获取站台图片
    @RequestMapping(value = "/getStationImg", method = RequestMethod.GET)
    public String getStationImg(@RequestParam Map m) {
        String url=imgMap.get(m.get("lineCode")+"_"+m.get("upDown"));
        return url;
    }



    /**
     * schDeepSeep查询班次情况
     * @param
     * @return
     */
    @RequestMapping(value = "schDeepSeep", method = RequestMethod.GET)
    public Map  schDeepSeep(@RequestParam String  message){
        return loggerZnddService.schDeepSeep(message);
    }



}