ScheduleRealInfoServiceImpl.java 15.7 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
package com.bsth.service.impl;

import com.bsth.entity.ChildTaskPlan;
import com.bsth.entity.Equipment;
import com.bsth.entity.ScheduleRealInfo;
import com.bsth.entity.result.RevisedReport;
import com.bsth.repository.ScheduleRealInfoRepository;
import com.bsth.service.CulateService;
import com.bsth.service.ScheduleRealInfoService;
import com.bsth.util.Arith;
import com.bsth.util.DBUtils_MS;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class ScheduleRealInfoServiceImpl implements ScheduleRealInfoService {

    @Autowired
    ScheduleRealInfoRepository scheduleRealInfoRepository;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    CulateService culateService;

    Logger logger = LoggerFactory.getLogger(this.getClass());
    
    List<Equipment> equipmentCodeList = new ArrayList<>();
    
    List<Object[]> gpsDateList = new ArrayList<>();
    
    @Override
    public List<RevisedReport> mileageCorrectionTj(String scheduleDateStr) {
    	try {
//    		logger.info("-----------开始加载设备号!!!!!!!!!");
    		initEquipmentCodeList();
//    		logger.info("-----------设备号个数:"+equipmentCodeList.size());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        List<ScheduleRealInfo> list = new ArrayList<ScheduleRealInfo>();//所有线路
        List<ScheduleRealInfo> list_s = new ArrayList<ScheduleRealInfo>();
        List<ScheduleRealInfo> lists = new ArrayList<ScheduleRealInfo>();//单个线路
        //查询所有线路
        list = scheduleRealInfoRepository.scheduleByDateAndLineTj(scheduleDateStr);
        
        for (int i = 0; i < list.size(); i++) {
            ScheduleRealInfo s=list.get(i);
            Set<ChildTaskPlan> cts = s.getcTasks();
            if(cts != null && cts.size() > 0){
            	 list_s.add(s);
            }else{
	            if(s.getZdsjActual()!=null){
	                list_s.add(s);
	            }
            }
        }
        List<RevisedReport> omList = new ArrayList<RevisedReport>();
        for (int i = 0; i < list.size(); i++) {
            if(i<list.size()-1){
                if(list.get(i+1).getXlBm().equals(list.get(i).getXlBm())){
                    lists.add(list.get(i));
                }else{
                    lists.add(list.get(i));
                    RevisedReport report=staticTj(lists);
                    omList.add(report);
                    lists.clear();
                }
            }else{
                if(list.get(i).getXlBm().equals(list.get(i-1).getXlBm())){
                    lists.add(list.get(i));
                    RevisedReport report=staticTj(lists);
                    omList.add(report);
                }else{
                    lists.add(list.get(i));
                    RevisedReport report=staticTj(lists);
                    omList.add(report);
                    lists.clear();
                }
            }
        }          
        return omList;
    }
    
    public final RevisedReport staticTj(List<ScheduleRealInfo> list){
    	List<Long> bcsj = new ArrayList<>();//多有班次的时间
    	String realExecDate ="";
        Boolean iskt = false;//班次是否跨天
        String lineId = list.get(0).getXlBm();
        List<ScheduleRealInfo>  listSj=new ArrayList<ScheduleRealInfo>();//实际营运的班次
        double wqwxhgl = 0.0;//完全漂移公里
        double bfwxhgl = 0.0;//部分漂移公里
        int wqwxhbc = 0;//完全漂移班次
        int bfwxhbc = 0;//部分漂移班次
        double pygl = 0.0;//子任务公里
        int pybc = 0;//子任务
        for(int i=0;i<list.size();i++){
            ScheduleRealInfo s=list.get(i);
            Set<ChildTaskPlan> cts = s.getcTasks();
            if(cts != null && cts.size() > 0){
            	listSj.add(s);
            }else{
	            if(s.getZdsjActual()!=null){
	            	listSj.add(s);
	            }
            }
            try {
            	if (!realExecDate.equals(s.getRealExecDate())) {
            		iskt = true;
				}
            	realExecDate = s.getRealExecDate();//实际班次日期
            	String fcsj = "";
            	if(s.getFcsjActual() == null || s.getFcsjActual().equals("")) {
        			fcsj = s.getFcsj();
        		} else {						
        			fcsj = s.getFcsjActual();
				}
        		String zdsj = "";
        		if(s.getZdsjActual() == null || s.getZdsjActual().equals("")) {
        			zdsj = s.getZdsj();
        		} else {						
        			zdsj = s.getZdsjActual();
				}
				Long fcsjStr = Long.valueOf(dateToStamp(realExecDate +" " + fcsj  +":00"));
				Long zdsjStr = Long.valueOf(dateToStamp(realExecDate +" " + zdsj  +":00"));
				if (zdsjStr < fcsjStr) {//到站时间跨天 则到站时间加一天时间
					zdsjStr = (1000 * 60 * 60 * 24) + zdsjStr;
				}
				bcsj.add(fcsjStr);
				bcsj.add(zdsjStr);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		String year = realExecDate.split("-")[0];
        logger.info("计算线路:"+lineId);
        if (iskt) {
        	realExecDate = "('"+ orderDate(realExecDate)+"','"+ (orderDate(realExecDate)+1) +"')";
        	initGpsDateList(realExecDate,lineId,Collections.min(bcsj),Collections.max(bcsj),year);
		} else {
			realExecDate = "('"+ orderDate(realExecDate) +"')";
			initGpsDateList(realExecDate,lineId,Collections.min(bcsj),Collections.max(bcsj),year);
		}
        for (int i = 0; i < listSj.size(); i++) {
        	ScheduleRealInfo sr=listSj.get(i);
        	try {
        		realExecDate = sr.getRealExecDate();//实际班次日期
        		String fcsj = "";
        		if(sr.getFcsjActual() == null || sr.getFcsjActual().equals("")) {
        			fcsj = sr.getFcsj();
        		} else {						
        			fcsj = sr.getFcsjActual();
				}
        		String zdsj = "";
        		if(sr.getZdsjActual() == null || sr.getZdsjActual().equals("")) {
        			zdsj = sr.getZdsj();
        		} else {						
        			zdsj = sr.getZdsjActual();
				}
        		Long fcsjStr = Long.valueOf(dateToStamp(realExecDate +" " + fcsj  +":00"));
				Long zdsjStr = Long.valueOf(dateToStamp(realExecDate +" " + zdsj  +":00"));
				if (zdsjStr < fcsjStr) {//到站时间跨天 则到站时间加一天时间
					zdsjStr = (1000 * 60 * 60 * 24) + zdsjStr;
				}
				
    	        double sjgl = culateService.culateSjgl(sr);//一个班次实际公里
    	        double ljgl = culateService.culateLjgl(sr);  //一个班次临加公里
    	        double zyygl = Arith.add(sjgl,ljgl);	//一个班次总运营公里  
       		
        		String equipment_code = getEquipmentCode(sr.getClZbh());
        		List<Long> listTime = getGpsDate(realExecDate, equipment_code, fcsjStr, zdsjStr);
        		if (listTime.size() > 10) {
        			for (int j = 1; j < listTime.size(); j++) {
        				if ((listTime.get(j) - listTime.get(j-1))/ (1000 * 60) > 5) {
        					bfwxhgl = Arith.add(bfwxhgl,zyygl);
        					if (!CulateServiceImpl.isInOut(sr)) {
    							bfwxhbc++;
    						}
        					continue;
						}
        			}
				} else {
					wqwxhgl = Arith.add(wqwxhgl,zyygl);
					if (!CulateServiceImpl.isInOut(sr)) {
						wqwxhbc++;
					}
				}
        		int type = sr.getDriftStatus();
        		if (type == 1 || type ==2) {
        			pygl = Arith.add(pygl,zyygl);
        			if (!CulateServiceImpl.isInOut(sr)) {
						pybc++;
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
        RevisedReport report = new RevisedReport();
    	if(list.size()>0){
	        double ljgl = culateService.culateLjgl(listSj);  //临加公里
	        double sjgl = culateService.culateSjgl(listSj);//实际公里
	        double zyygl = Arith.add(sjgl,ljgl);			//总运营公里       	  
	        int ljbc = culateService.culateLjbc(listSj);
	        int sjbc = culateService.culateSjbc(listSj);
	        int zyybc = ljbc + sjbc;//总(实际)营运班次
	        
	        double sjjccgl=culateService.culateJccgl(listSj);
	        double sjksgl = culateService.culateKsgl(listSj);
	        double zksgl=Arith.add(sjjccgl, sjksgl);//实际空驶公里
	        int sjjccbc=culateService.culateJccbc(listSj);
	        int sjksbc = culateService.culateKsbc(listSj);
	        int zksbc = sjjccbc + sjksbc;//实际空驶班次
	        
	        double zgl = Arith.add(zyygl, zksgl);//实际总公里
	        int zbc = zksbc + zyybc;//实际总
	        
	        double sddfgl =culateService.culatesddfgl(list);//手动待发调整公里
	        double zddfgl = culateService.culatezddfgl(list);//自动待发调整公里
	        double zrwgl = culateService.culateZrwgl(list);//子任务公里
	        int sddfbc =culateService.culatesddfbc(list);//手动待发调整
	        int zddfbc = culateService.culatezddfbc(list);//自动待发调整
	        int zrwbc = culateService.culateZrwbc(list);//子任务
    		report.setCompanyId(list.get(0).getGsBm());
    		report.setSubCompanyId(list.get(0).getFgsBm());
    		report.setCompanyName(list.get(0).getGsName());
    		report.setSubCompanyName(list.get(0).getFgsName());
    		report.setLineCode(list.get(0).getXlBm());
    		report.setLineName(list.get(0).getXlName());
    		report.setZgl(zgl);
    		report.setSjyygl(zyygl);
    		report.setSjksgl(zksgl);
    		report.setSddfgl(sddfgl);
    		report.setZddfgl(zddfgl);
    		report.setWqwxhgl(wqwxhgl);
    		report.setBfwxhgl(bfwxhgl);
    		report.setPygl(pygl);
    		report.setLjgl(ljgl);
    		report.setZrwgl(zrwgl);
    		report.setZbc(zbc);
    		
    		report.setSjyybc(zyybc);
    		report.setSjksbc(zksbc);
    		report.setSddfbc(sddfbc);
    		report.setZddfbc(zddfbc);
    		report.setWqwxhbc(wqwxhbc);
    		report.setBfwxhbc(bfwxhbc);
    		report.setPybc(pybc);
    		report.setLjbc(ljbc);
    		report.setZrwbc(zrwbc);    		
    		
    		report.setRq(list.get(0).getScheduleDateStr());
    		report.setOther(null);
    		report.setCreateDate(new Date());
    	}
        return report;
    }
    
    public void initGpsDateList(String scheduleDateStr, String lineId, Long startTime, Long endTime, String year) {
    	
    	gpsDateList.clear();//清空上一条线路的gps信息
    	Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		Date date=new Date();
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(date);
    	String sql = "select device_id as device_id, ts as ts from bsth_c_gps_info_"+ year +"  where days_year in "+ scheduleDateStr +" and line_id=? and ts>=? and ts<=? ORDER BY device_id , ts";
		try{
			conn = DBUtils_MS.getConnection();
			ps = conn.prepareStatement(sql);
			ps.setString(1, lineId);
			ps.setLong(2, startTime);
			ps.setLong(3, endTime);
			rs = ps.executeQuery();
			while(rs.next()){
				Object obj[] = new Object[2];
				obj[0] = rs.getString("device_id");
				obj[1] = rs.getString("ts");
				gpsDateList.add(obj);
			}
		}catch(Exception e){
			logger.error("", e);
		}finally {
			DBUtils_MS.close(rs, ps, conn);
		}
    }
    
    public void initEquipmentCodeList() throws Exception {
    	
    	String sql = "select inside_code, equipment_code from bsth_c_cars where 1=1";
    	equipmentCodeList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(Equipment.class));
    	
    	/*Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		// 设置连接数据库的配置信息  本地
    	String url = "jdbc:mysql://localhost:3306/control_cope?"
                + "user=root&password=root&useUnicode=true&characterEncoding=UTF8";
		
		// 设置连接数据库的配置信息  服务器
    	String url = "jdbc:mysql://10.10.150.20:3306/control?useUnicode=true&characterEncoding=UTF8";
 
        try {
            // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来,
            // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以
            Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动 
//            System.out.println("成功加载MySQL驱动程序");
            // 一个Connection代表一个数据库连接
            conn = DriverManager.getConnection(url);
            // Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等
            String sql = "select inside_code, equipment_code from bsth_c_cars where 1=1";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
            	Object obj[] = new Object[2];
            	obj[0] = rs.getString("inside_code"); //车辆自编号
            	obj[1] = rs.getString("equipment_code").toString(); //终端设备号
            	equipmentCodeList.add(obj);
            }
        } catch (SQLException e) {
            System.out.println("MySQL操作错误");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        	rs.close();
        	ps.close();
            conn.close();
        }    */	
    }
    
    /** 获取设备终端号 */
    public String getEquipmentCode(String clZbm) throws Exception {
    	String equipment_code = "";
    	for (Equipment equipment:equipmentCodeList) {
			if (equipment.getInside_code().equals(clZbm)) {
				equipment_code = equipment.getEquipment_code().toString();
			}  		
		}
		return equipment_code;
	}
    
    public List<Long> getGpsDate(String daysYear, String equipment_code, Long fcsjStr, Long zdsjStr) throws ParseException {
		List<Long> list = new ArrayList<>();
		for (Object[] obj :gpsDateList ) {
			if (obj[0].equals(equipment_code)) {
				Long ts = Long.valueOf(obj[1].toString());
				if (ts >= fcsjStr && ts <= zdsjStr) {
					list.add(ts);
				}
			}
		}    	
		return list;
    }
    
    /* 
     * 将时间转换为时间戳
     */    
    public static String dateToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }
    
    /* 
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
    
    /* 
     * 计算今天是今年的第几天
     */
    public int orderDate(String dateStr){
	  int dateSum = 0;
	  /*SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	  String dateStr = format.format(date);*/
	  int year = Integer.valueOf(dateStr.substring(0,4));
	  int month = Integer.valueOf(dateStr.substring(5,7));
	  int day = Integer.valueOf(dateStr.substring(8,10));
	  for (int i = 1; i < month; i++){
	   switch(i){
	     case 1: case 3: case 5: case 7: case 8: case 10: case 12:dateSum += 31; break;
	     case 4: case 6: case 9: case 11:dateSum += 30; break;
	     case 2: 
	      if(((year % 4 == 0) & (year % 100 != 0)) | (year % 400 == 0))
	       dateSum += 29;
	      else dateSum += 28;    
	   }
	  }
	  
	  return dateSum = dateSum + day;
	 }
    
}