SchedulePlanServiceImpl.java 19.8 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
package com.bsth.service.schedule.impl;

import com.bsth.entity.Line;
import com.bsth.entity.schedule.SchedulePlan;
import com.bsth.entity.schedule.TTInfo;
import com.bsth.entity.schedule.rule.ScheduleRule1Flat;
import com.bsth.repository.schedule.SchedulePlanInfoRepository;
import com.bsth.repository.schedule.SchedulePlanRepository;
import com.bsth.service.BusinessService;
import com.bsth.service.LineService;
import com.bsth.service.schedule.*;
import com.bsth.service.schedule.rules.plan.PlanCalcuParam_input;
import com.bsth.service.schedule.rules.plan.PlanResult;
import com.bsth.service.schedule.rules.shiftloop.ScheduleCalcuParam_input;
import com.bsth.service.schedule.rules.shiftloop.ScheduleResults_output;
import com.bsth.service.schedule.rules.shiftloop.ScheduleRule_input;
import com.bsth.service.schedule.rules.strategy.IStrategy;
import com.bsth.service.schedule.rules.ttinfo.TTInfoCalcuParam_input;
import com.bsth.service.schedule.rules.ttinfo.TTInfoResults_output;
import com.bsth.service.schedule.rules.ttinfo.TTInfo_input;
import com.bsth.service.schedule.rules.ttinfo2.CalcuParam;
import com.bsth.service.schedule.rules.ttinfo2.Result;
import org.joda.time.DateTime;
import org.kie.api.KieBase;
import org.kie.api.runtime.KieSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Created by xu on 16/6/16.
 */
@Service
public class SchedulePlanServiceImpl extends BServiceImpl<SchedulePlan, Long> implements SchedulePlanService {
    @Autowired
    private KieBase kieBase;
    @Autowired
    private IStrategy strategy;
    @Autowired
    private SchedulePlanRepository schedulePlanRepository;
    @Autowired
    private SchedulePlanInfoRepository schedulePlanInfoRepository;
    @Autowired
    private LineService lineService;
    @Autowired
    private TTInfoService ttInfoService;
    @Autowired
    private TTInfoDetailService ttInfoDetailService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private CarConfigInfoService carConfigInfoService;
    @Autowired
    private EmployeeConfigInfoService employeeConfigInfoService;

    /** 日志记录器 */
    private Logger logger = LoggerFactory.getLogger(SchedulePlanServiceImpl.class);

    // 查找线路(未撤销),TODO:到时候放入drl中
    private Line getLine(Integer xlId) {
        Map<String, Object> param = new HashMap<>();
        param.put("id_eq", xlId);
        param.put("destroy_eq", 0); // 未撤销
        List<Line> lines = (List<Line>) lineService.list(param);
        if (CollectionUtils.isEmpty(lines)) {
            throw new RuntimeException("线路找不到,可能已经撤销!");
        }
        return lines.get(0);
    }
    // 查找时刻表(未作废),TODO:到时候放入drl中
    private List<TTInfo> getTTInfos(Integer xlId) {
        // 查询参数
        Map<String, Object> param = new HashMap<>();
        param.put("xl.id_eq", xlId); // 线路Id
        param.put("isCancel_eq", false); // 作废的过滤掉
        Iterator<TTInfo> ttInfoIterator = ttInfoService.list(param).iterator();
        if (!ttInfoIterator.hasNext()) {
            throw new RuntimeException("线路id=" + xlId + " 没有时刻表!");
        }
        List<TTInfo> ttInfos = new ArrayList<>();
        while (ttInfoIterator.hasNext()) {
            TTInfo ttInfo = ttInfoIterator.next();
            ttInfos.add(ttInfo);
        }
        return ttInfos;
    }

    /**
     * 循环规则输出。
     * @param schedulePlan
     */
    private ScheduleResults_output loopRuleOutput(SchedulePlan schedulePlan) {
        // 获取主线路
        Line xl = strategy.getLine(schedulePlan.getXl().getId());

        // 1-1、构造drools规则输入数据,输出数据
        // 全局计算参数
        ScheduleCalcuParam_input scheduleCalcuParam_input = new ScheduleCalcuParam_input(schedulePlan);
        // 每个规则对应的输入参数
        List<ScheduleRule_input> scheduleRule_inputs = new ArrayList<>();
        Iterator<ScheduleRule1Flat> scheduleRule1FlatIterator = strategy.getScheduleRule(xl.getId()).iterator();
        while (scheduleRule1FlatIterator.hasNext()) {
            ScheduleRule1Flat scheduleRule1Flat_temp = scheduleRule1FlatIterator.next();
            ScheduleRule_input scheduleRule_input = new ScheduleRule_input(scheduleRule1Flat_temp);
            scheduleRule_inputs.add(scheduleRule_input);
        }
        // 规则输出数据
        ScheduleResults_output scheduleResults_output = new ScheduleResults_output();

        // 1-2、构造drools session->载入数据->启动规则->计算->销毁session
        // 创建session,内部配置的是stateful
        KieSession session = kieBase.newKieSession();
        // 设置gloable对象,在drl中通过别名使用
        session.setGlobal("scheduleResult", scheduleResults_output);
        session.setGlobal("log", logger); // 设置日志

        // 载入数据
        session.insert(scheduleCalcuParam_input);
        for (ScheduleRule_input scheduleRule_input : scheduleRule_inputs) {
            session.insert(scheduleRule_input);
        }
        // 执行rule
        session.fireAllRules();

        // 执行完毕销毁,有日志的也要关闭
        session.dispose();

        logger.info("循环规则输出={}", scheduleResults_output.showGuideboardDesc1());

        return scheduleResults_output;
    }

    /**
     * 时刻表选择(判定每天使用的时刻表)。
     * @param schedulePlan
     * @return
     */
    private TTInfoResults_output ttInfoOutput(SchedulePlan schedulePlan) {
        // 获取线路的所有未作废的时刻表
        List<TTInfo> ttInfos = getTTInfos(schedulePlan.getXl().getId());

        // 1-1、构造drools规则输入数据,输出数据
        // 全局计算参数
        TTInfoCalcuParam_input ttInfoCalcuParam_input =
                new TTInfoCalcuParam_input(
                        new DateTime(schedulePlan.getScheduleFromTime()),
                        new DateTime(schedulePlan.getScheduleToTime()),
                        String.valueOf(schedulePlan.getXl().getId())
                );
        // 规则输出数据
        TTInfoResults_output ttInfoResults_output = new TTInfoResults_output();

        // 1-2、构造drools session->载入数据->启动规则->计算->销毁session
        // 创建session,内部配置的是stateful
        KieSession session = kieBase.newKieSession();

        // 设置gloable对象,在drl中通过别名使用
        session.setGlobal("results", ttInfoResults_output);
        session.setGlobal("log", logger); // 设置日志

        // 载入数据
        session.insert(ttInfoCalcuParam_input);
        for (TTInfo ttInfo : ttInfos) {
            TTInfo_input ttInfo_input = new TTInfo_input(ttInfo);
            session.insert(ttInfo_input);
        }

        // 执行rule
        session.fireAllRules();

        // 执行完毕销毁,有日志的也要关闭
        session.dispose();

        return ttInfoResults_output;

    }

    private PlanResult planResultOutput(
            SchedulePlan schedulePlan,
            ScheduleResults_output scheduleResults_output,
            TTInfoResults_output ttInfoResults_output) {

        // 1-1、构造drools规则输入数据,输出数据
        PlanCalcuParam_input planCalcuParam_input = new PlanCalcuParam_input(
                schedulePlan,
                scheduleResults_output,
                ttInfoResults_output
        );
        // 规则输出数据
        PlanResult planResult = new PlanResult();

        // 1-2、构造drools session->载入数据->启动规则->计算->销毁session
        // 创建session,内部配置的是stateful
        KieSession session = kieBase.newKieSession();

        // 设置gloable对象,在drl中通过别名使用
        session.setGlobal("planResult", planResult);
        session.setGlobal("tTInfoService", ttInfoService);
        session.setGlobal("tTInfoDetailService", ttInfoDetailService);
        session.setGlobal("carConfigInfoService", carConfigInfoService);
        session.setGlobal("employeeConfigInfoService", employeeConfigInfoService);
        session.setGlobal("lineService", lineService);
        session.setGlobal("businessService", businessService);
        session.setGlobal("log", logger); // 设置日志

        // 载入数据
        session.insert(planCalcuParam_input);

        // 执行rule
        session.fireAllRules();

        // 执行完毕销毁,有日志的也要关闭
        session.dispose();

        return planResult;

    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public SchedulePlan save2(SchedulePlan schedulePlan) {
        // 1、循环规则计算输出
        ScheduleResults_output scheduleResults_output = loopRuleOutput(schedulePlan);
        // 2、时刻表选择
        TTInfoResults_output ttInfoResults_output = ttInfoOutput(schedulePlan);
        // 3、计划输出
        PlanResult planResult = planResultOutput(schedulePlan, scheduleResults_output, ttInfoResults_output);

        schedulePlan.getSchedulePlanInfoList().addAll(planResult.getSchedulePlanInfos());
        schedulePlan.setTtInfoId("todo"); // TODO:待修正
        schedulePlan.setTtInfoNames("todo"); // TODO:待修正

        super.save(schedulePlan);

        return new SchedulePlan();
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
    public SchedulePlan save(SchedulePlan schedulePlan) {
        // 2-3、如果排班的数据之前已经有了,删除之前的数据
        schedulePlanInfoRepository.deleteByXlAndScheduleDateGreaterThanEqualAndScheduleDateLessThanEqual(
                schedulePlan.getXl().getId(), schedulePlan.getScheduleFromTime(), schedulePlan.getScheduleToTime()
        );

        // 测试
        return save2(schedulePlan);

//        // 1-1、查找线路具体信息
//        Line xl = strategy.getLine(schedulePlan.getXl().getId());
//        // 1-2、查出指定线路的所有规则
//        TTInfo ttInfo = strategy.getTTInfo(xl.getId()).get(0); // 时刻表id
//        schedulePlan.setTtInfo(ttInfo); // TODO:关联的时刻表,之后改掉
//
//        // 2-1、构造drools规则输入数据,输出数据
//        // 全局计算参数
//        ScheduleCalcuParam_input scheduleCalcuParam_input = new ScheduleCalcuParam_input(schedulePlan);
//        // 每个规则对应的输入参数
//        List<ScheduleRule_input> scheduleRule_inputs = new ArrayList<>();
//        Iterator<ScheduleRule1Flat> scheduleRule1FlatIterator = strategy.getScheduleRule(xl.getId()).iterator();
//        while (scheduleRule1FlatIterator.hasNext()) {
//            ScheduleRule1Flat scheduleRule1Flat_temp = scheduleRule1FlatIterator.next();
//            ScheduleRule_input scheduleRule_input = new ScheduleRule_input(scheduleRule1Flat_temp);
//            scheduleRule_inputs.add(scheduleRule_input);
//        }
//        // 规则输出数据
//        ScheduleResults_output scheduleResults_output = new ScheduleResults_output();
//
//        // 2-2、构造drools session->载入数据->启动规则->计算->销毁session
//        // 创建session,内部配置的是stateful
//        KieSession session = kieBase.newKieSession();
//        // 设置gloable对象,在drl中通过别名使用
//        session.setGlobal("scheduleResult", scheduleResults_output);
//        session.setGlobal("log", logger); // 设置日志
//
//        // 载入数据
//        session.insert(scheduleCalcuParam_input);
//        for (ScheduleRule_input scheduleRule_input : scheduleRule_inputs) {
//            session.insert(scheduleRule_input);
//        }
//        // 执行rule
//        session.fireAllRules();
//
//        // 执行完毕销毁,有日志的也要关闭
//        session.dispose();
//
//        System.out.println(scheduleResults_output.showGuideboardDesc1());
//
//        // 2-3、如果排班的数据之前已经有了,删除之前的数据
//        schedulePlanInfoRepository.deleteByXlAndScheduleDateGreaterThanEqualAndScheduleDateLessThanEqual(
//                xl.getId(), schedulePlan.getScheduleFromTime(), schedulePlan.getScheduleToTime()
//        );
//
//        // 3、根据规则返回,组合最后的输出数据
//        // 3-1、根据注入的策略服务,获取原始数据
//        Map<Date, Multimap<Long, TTInfoDetail>> gbdTTinfoMaps = strategy.getGuideboardXlTTInfoDetailMaps(
//                xl.getId(), schedulePlan.getScheduleFromTime(), schedulePlan.getScheduleToTime());
//
//        Map<Long, CarConfigInfo> carConfigMaps = strategy.getCarConfigMaps(xl.getId()); // 车辆配置对应车辆信息
//        Map<Long, EmployeeConfigInfo> employeeConfigMaps = strategy.getEmployeeConfigMaps(xl.getId()); // 人员配置对应的人员信息
//
//        // 3-2、循环规则输出
//        Map<Long, String> ttInfoMap = new HashMap<>(); // 时刻表映射,id和名字
//        List<SchedulePlanInfo> schedulePlanInfos = new ArrayList<>();
//        for (ScheduleResult_output scheduleResult_output : scheduleResults_output.getResults()) {
//            // 车辆配置对应的车辆
//            CarConfigInfo configInfo = carConfigMaps.get(Long.valueOf(scheduleResult_output.getCarConfigId()));
//            // 人员配置对应的人员,这里需要分班处理的
//            List<EmployeeConfigInfo> employeeConfigInfoList = new ArrayList<>();
//            String[] eids = scheduleResult_output.getEmployeeConfigId().split("-");
//            for (String eid : eids) {
//                employeeConfigInfoList.add(employeeConfigMaps.get(Long.valueOf(eid)));
//            }
//            // 排班明细(这个要迭代的)
//            Collection<TTInfoDetail> ttInfoDetails_ = gbdTTinfoMaps.get(scheduleResult_output.getSd().toDate()).get(
//                    Long.parseLong(scheduleResult_output.getGuideboardId()));
//            List<TTInfoDetail> ttInfoDetails = new ArrayList<>(ttInfoDetails_);
//
//            // 排序ttInfoDetails
//            Collections.sort(ttInfoDetails, new Comparator<TTInfoDetail>() {
//                @Override
//                public int compare(TTInfoDetail o1, TTInfoDetail o2) {
//                    return o1.getFcno().compareTo(o2.getFcno());
//                }
//            });
//
//            Boolean isFb = false; // 是否分班
//            for (int i = 0; i < ttInfoDetails.size(); i++) {
//                TTInfoDetail ttInfoDetail = ttInfoDetails.get(i);
//
//                if (ttInfoDetail.getIsFB())
//                    isFb = ttInfoDetail.getIsFB();
//
//                SchedulePlanInfo schedulePlanInfo = new SchedulePlanInfo(
//                        xl,
//                        scheduleResult_output,
//                        ttInfoDetail,
//                        isFb,
//                        configInfo,
//                        employeeConfigInfoList,
//                        schedulePlan,
//                        i == 0,
//                        i == ttInfoDetails.size() - 1);
//
//                // 获取公司,分公司信息
//                String gsbm = xl.getCompany();
//                String fgsbm = xl.getBrancheCompany();
//                Business gs = null;
//                Business fgs = null;
//
//                Map<String, Object> param = new HashMap<>();
//
//                if (StringUtils.isNotEmpty(gsbm)) {
//                    param.clear();
//                    param.put("businessCode_eq", gsbm);
//                    Iterator<Business> businessIterator = businessService.list(param).iterator();
//                    if (businessIterator.hasNext()) {
//                        gs = businessIterator.next();
//                    }
//                }
//                if (StringUtils.isNotEmpty(gsbm) && StringUtils.isNotEmpty(fgsbm)) {
//                    param.clear();;
//                    param.put("upCode_eq", gsbm);
//                    param.put("businessCode_eq", fgsbm);
//                    Iterator<Business> businessIterator = businessService.list(param).iterator();
//                    if (businessIterator.hasNext()) {
//                        fgs = businessIterator.next();
//                    }
//                }
//
//                if (gs != null) {
//                    schedulePlanInfo.setGsBm(gs.getBusinessCode());
//                    schedulePlanInfo.setGsName(gs.getBusinessName());
//                }
//                if (fgs != null) {
//                    schedulePlanInfo.setFgsBm(fgs.getBusinessCode());
//                    schedulePlanInfo.setFgsName(fgs.getBusinessName());
//                }
//
//                // 操作人,操作时间
//                schedulePlanInfo.setCreateBy(schedulePlan.getCreateBy());
//                schedulePlanInfo.setCreateDate(schedulePlan.getCreateDate());
//                schedulePlanInfo.setUpdateBy(schedulePlan.getUpdateBy());
//                schedulePlanInfo.setUpdateDate(schedulePlan.getUpdateDate());
//
//                schedulePlanInfos.add(schedulePlanInfo);
//                ttInfoMap.put(ttInfoDetail.getTtinfo().getId(), ttInfoDetail.getTtinfo().getName());
//
//            }
//
//        }
//
//        schedulePlan.setTtInfoId(StringUtils.join(ttInfoMap.keySet(), ","));
//        schedulePlan.setTtInfoNames(StringUtils.join(ttInfoMap.values(), ","));
//
//        // 3-2、保存生成的排班和明细
//        schedulePlan.getSchedulePlanInfoList().addAll(schedulePlanInfos); // 关联的排班明细信息
//        super.save(schedulePlan);
//
//        return new SchedulePlan();
    }

    @Override
    public SchedulePlan findSchedulePlanTommorw() {
        DateTime today = new DateTime(new Date());
        DateTime tommorw = new DateTime(today.getYear(), today.getMonthOfYear(), today.getDayOfMonth(), 0, 0).plusDays(1);
        Map<String, Object> param = new HashMap<>();
        param.put("scheduleFromTime_le", tommorw.toDate());
        param.put("scheduleToTime_ge", tommorw.toDate()     );
        Iterator<SchedulePlan> schedulePlanIterator = this.list(param).iterator();
        if (schedulePlanIterator.hasNext()) {
            return schedulePlanIterator.next();
        }
        return null;
    }

    @Override
    public Result validateTTInfo(Integer xlid, Date from, Date to) {
        // 构造drools session->载入数据->启动规则->计算->销毁session
        // 创建session,内部配置的是stateful
        KieSession session = kieBase.newKieSession();
        // 设置gloable对象,在drl中通过别名使用
        session.setGlobal("log", logger);
        session.setGlobal("lineService", lineService);
        session.setGlobal("ttInfoDetailService", ttInfoDetailService);

        Result rs = new Result(); // 输出gloable对象
        session.setGlobal("rs", rs);

        // 载入数据
        CalcuParam calcuParam = new CalcuParam(
                new DateTime(from), new DateTime(to), xlid);
        session.insert(calcuParam);
        List<TTInfo> ttInfos = ttInfoService.findAll();
        for (TTInfo ttInfo: ttInfos)
                session.insert(ttInfo);


        // 执行rule
        session.fireAllRules();

        // 执行完毕销毁,有日志的也要关闭
        session.dispose();


        return rs;
    }
}