OutEntrance.java 13.3 KB
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.entity.StationRoute;
import com.bsth.entity.realcontrol.ScheduleRealInfo;
import com.bsth.entity.zndd.StationPeopleLogger;
import com.bsth.entity.zndd.StationSignsLogger;
import com.bsth.service.schedule.utils.Md5Util;
import com.bsth.util.HttpClientUtils;
import com.bsth.websocket.handler.SendUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
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.web.bind.annotation.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;

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

    @Autowired
    SendUtils sendUtils;
    @Autowired
    DayOfSchedule dayOfSchedule;


    @Value("${dc.imgurl}")
    private  String imgurl; //存储图片地址
    
    @Value("${dc.profile}")
    private  String 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;

    private static final String PASSWORD="e126853c7f6f43b4857fa8dfe3b28b5d90be9e68";



     //调度屏小程序接口。
     @RequestMapping(value = "/OutCar", method = RequestMethod.POST)
     public Map OutCarOutCar(@RequestParam Map m,@RequestBody StationSignsLogger ssLogger) {
         Map rtn = new HashMap<>();
         try {
             if(!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());

             //线调页面推送
             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 {
                 //筛选方向
                 List<ScheduleRealInfo> rs = dayOfSchedule.findByLineCode(ssLogger.getLineCode());
                 //排序
                 Collections.sort(rs,new ScheduleComparator.FCSJ());
                 SimpleDateFormat sdf= new SimpleDateFormat("HH:ss");
                 String sjtext = "";
                 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(t1.isAfter(t2)){
                         sjtext = sr.getFcsj();
                     }
                 }
                 rtn.put("message","车辆预计"+sjtext+"发车,请耐心等待");
             }

             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 void klyj(@RequestBody JSONObject jsonObject) {
        try {
            if(!validation(Long.parseLong(jsonObject.getString("timestamp")),jsonObject.getString("sign"))){
                return ;
            }
            String num=jsonObject.getString("num");
            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();
                StationRoute stationRoute=BasicData.stationCode2StationMap.get(lineCode+"_"+stationCode);
                Map m = new HashMap();
                m.put("image", img);
                m.put("stationCode", stationCode);
                m.put("lineCode", stationRoute.getLineCode());
                m.put("stationName",BasicData.stationCode2NameMap.get(stationRoute.getLineCode()+"_"+stationRoute.getDirections()+"_"+stationRoute.getStationCode()));
                m.put("lineName",BasicData.lineCode2NameMap.get(stationRoute.getLineCode()));
                m.put("num",num);
                m.put("xlDir",stationRoute.getDirections());
                List<ScheduleRealInfo> srList=dayOfSchedule.findByLineAndUpDown(stationRoute.getLineCode(),stationRoute.getDirections());
                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;
                for (int i1 = 0; i1 < sl.size(); i1++) {//最近的已发车班次
                    ScheduleRealInfo scheduleRealInfo=sl.get(i1);
                    LocalTime fcsj=LocalTime.parse(scheduleRealInfo.getFcsj(),dateTimeFormatter);
                    if((scheduleRealInfo.getBcType().equals("normal")||scheduleRealInfo.getBcType().equals("region")) &&scheduleRealInfo.getXlDir().equals(String.valueOf(stationRoute.getDirections())) && fcsj.isAfter(localTime)){
                        schedule =sl.get(i1-1);;
                        break;
                    }
                }
                //线调页面推送
                if(schedule!=null){
                    m.put("sch",schedule);
                    m.put("uuid",AutomaticSch.UUID());
                    m.put("rq",localTime.format(dateTimeFormatter)); //检测到时间
                    sendUtils.klyj(m);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

        try {
            ObjectMapper mapper = new ObjectMapper();
            //线调页面推送
            sendUtils.sendzndd(m);

            rtn.put("status",ResponseCode.SUCCESS);
        } catch (Exception e) {
            rtn.put("status",ResponseCode.ERROR);
            logger.info("智能调度推送----",e);
        }

        return rtn;
    }


  //智能调度接口-大客流
    @RequestMapping(value="/dkl",method = RequestMethod.POST)
    public Map ddkl(@RequestParam Map m) {
        Map rtn = new HashMap<>();

        try {
            ObjectMapper mapper = new ObjectMapper();
            //map转换实体类
            StationPeopleLogger ssLogger = mapper.convertValue(m, StationPeopleLogger.class);
            
            ssLogger.setType("大客流");
       
            //保存记录
            //znddLoggerService.save(ssLogger);
            //线调页面推送
            //sendUtils.sendzndd(ssLogger);

            rtn.put("status",ResponseCode.SUCCESS);
        } catch (Exception e) {
            rtn.put("status", ResponseCode.ERROR);
            Logger logger = LoggerFactory.getLogger(this.getClass());
        }
        return rtn;
    }




    /**
     * 保存base64图片
     * @param base64Str 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 = "666"+ ".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;
    }

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

    public boolean validation(long timestamp,String sign){
        String md5String=Md5Util.getMd5(timestamp+PASSWORD);
        if(!md5String.equals(sign)){
            return false;
        }
        if(System.currentTimeMillis()-timestamp>60*1000){
            return false;
        }
        return true;
    }

}