package com.xxfc.platform.vehicle.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.vehicle.constant.*;
import com.xxfc.platform.vehicle.constant.ResCode.ResCode;
import com.xxfc.platform.vehicle.entity.*;
import com.xxfc.platform.vehicle.mapper.*;
import com.xxfc.platform.vehicle.pojo.*;
import com.xxfc.platform.vehicle.util.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

@Service
@Slf4j
public class VehicleActiveService {

    @Autowired
    VehicleMapper vehicleMapper;

    @Autowired
    VehicleDepartureLogMapper vehicleDepartureLogMapper;

    @Autowired
    VehicleActiveLogMapper vehicleActiveLogMapper;

    @Autowired
    VehicleUpkeepLogMapper vehicleUpkeepLogMapper;

    @Autowired
    VehicleUpkeepItemMapper vehicleUpkeepItemMapper;

    @Autowired
    VehicleBookRecordBiz vehicleBookRecordBiz;

    @Autowired
    VehicleBiz vehicleBiz;

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

    @Value("${vehicle.mileage}")
    private Integer Mileage;

    /**
     * 出车
     *
     * @param departureVo
     */
    public void departure(VehicleDepartureVo departureVo) {
        log.info("出车参数： departureVo = {}", departureVo.toString());
        Vehicle vehicle = vehicleBiz.selectById(departureVo.getVehicleId());
        if (vehicle == null) {
            log.info("出车异常，车辆不存在！");
            throw new BaseException(ResCode.VEHICLE_DEPARTURE_VEHICLE_UNEXIST.getDesc(),
                    ResCode.VEHICLE_DEPARTURE_VEHICLE_UNEXIST.getCode());
        }
//        if (StringUtils.isBlank(departureVo.getCheckMan()) || StringUtils.isBlank(departureVo.getCheckManTel())) {
//            log.error("出车  核销人姓名不能为空！");
//            throw new BaseException(ResCode.CHECKUSER_AND_PHONE_NOT_NULL.getDesc(),
//                    ResCode.CHECKUSER_AND_PHONE_NOT_NULL.getCode());
//        }
        if (vehicle.getStatus().equals(VehicleStatus.DISCARD.getCode()) || vehicle.getIsDel() == 1 || vehicle.getStatus().equals(VehicleStatus.DEPARTURE.getCode())) {
            throw new BaseException(ResCode.VEHICLE_STATUS_IS_NOT_NORMAL.getDesc(),
                    ResCode.VEHICLE_STATUS_IS_NOT_NORMAL.getCode());
        }
        //添加出车时间过滤 再出车开始时间前一天至结束时间内可以出车,并且预定记录为已审核状态
        try {
            checkDateInvalid(departureVo);
        } catch (BaseException b) {
            throw new BaseException(b.getMessage(), b.getStatus());
        }
        Integer MileageLift = vehicle.getMileageLastUpdate();
        Integer MileageLift1 = departureVo.getMileage();
        if (MileageLift1 == null) {
            throw new BaseException(ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getDesc(),
                    ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getCode());
        }
        if (MileageLift == null || MileageLift1 >= MileageLift) {
            // 写入车辆公里数,预计目的地
            vehicle.setMileageLastUpdate(MileageLift1);
            // 修改车辆状态，确认是空闲状态
            if (vehicle.getStatus().equals(VehicleStatus.NORMAL.getCode())) {
                vehicle.setStatus(VehicleStatus.DEPARTURE.getCode());
            }
            vehicleMapper.updateByPrimaryKeySelective(vehicle);



            //修改预约记录状态
            VehicleBookRecord vehicleBookRecord = null;
            if (departureVo.getBookRecordId() != null) {
                vehicleBookRecord = vehicleBookRecordBiz.selectById(departureVo.getBookRecordId());
                updateBookRecordStatus(vehicleBookRecord, 1);
            }
            if (vehicleBookRecord != null) {
                vehicle.setParkBranchCompanyId(vehicleBookRecord.getRetCompany());
            }
            vehicleMapper.updateByPrimaryKeySelective(vehicle);
            VehicleDepartureLogVo vehicleDepartureLogVo = vehicleDepartureLogMapper.selectByBookRecordId(departureVo.getBookRecordId());
            if (vehicleDepartureLogVo != null) {
                BeanUtil.copyProperties(departureVo, vehicleDepartureLogVo, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                VehicleDepartureLog departureLog = vehicleDepartureLogVo.getVehicleDeparture(vehicleDepartureLogVo);
                departureLog.setDepartureTime(new Date());
                departureLog.setUpdateTime(new Date());
                departureLog.setState(VehicleDepartureState.DEPARTURE.getCode());
                departureLog.setDepartureRemark(departureVo.getRemark());
                if (vehicleBookRecord != null) {
                    departureLog.setDepartureBranchCompanyId(vehicleBookRecord.getLiftCompany());
                    departureLog.setUse(BookType.getByCode(vehicleBookRecord.getBookType()));
                    departureLog.setUser(vehicleBookRecord.getVehicleUsername());
                    departureLog.setUserTel(vehicleBookRecord.getVehicleUserPhone());
                }
                vehicleDepartureLogMapper.updateByPrimaryKeySelective(departureLog);
            } else {
                // 出车记录
                VehicleDepartureLog departureLog = new VehicleDepartureLog();
                BeanUtils.copyProperties(departureVo, departureLog);
                departureLog.setDepartureTime(new Date());
                departureLog.setCreateTime(new Date());
                departureLog.setMileageStart(departureVo.getMileage());
                departureLog.setState(VehicleDepartureState.DEPARTURE.getCode());
                departureLog.setBookRecordId(departureVo.getBookRecordId());
                departureLog.setDepartureRemark(departureVo.getRemark());
                if (vehicleBookRecord != null) {
                    departureLog.setDepartureBranchCompanyId(vehicleBookRecord.getLiftCompany());
                    departureLog.setUse(BookType.getByCode(vehicleBookRecord.getBookType()));
                    departureLog.setUser(vehicleBookRecord.getVehicleUsername());
                    departureLog.setUserTel(vehicleBookRecord.getVehicleUserPhone());
                }
                vehicleDepartureLogMapper.insert(departureLog);
            }
            // 车辆活动日志
            VehicleActiveLog activeLog = new VehicleActiveLog();
            activeLog.setVehicleId(departureVo.getVehicleId());
            activeLog.setActiveType(VehicleActiveType.Departure.getCode());
            activeLog.setStartTime(new Date());
            activeLog.setCreateTime(new Date());
            vehicleActiveLogMapper.insert(activeLog);
        } else {
            throw new BaseException(ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getDesc(),
                    ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getCode());
        }
    }


    public String getVehicleStatus(Integer status, String vehicleId) {
        StringBuilder stringBuilder = new StringBuilder();
        switch (status) {
            case 1:
                stringBuilder.append("正常运行");
                break;
            case 2:
                stringBuilder.append("维修");
                break;
            case 3:
                stringBuilder.append("报废");
                break;
            case 4:
                stringBuilder.append("出车");
                break;
            case 5:
                stringBuilder.append("保养");
                break;
        }
        List<VehicleBookRecordVo> vehicleBookRecordVos = vehicleBookRecordBiz.selectByVehicleId(vehicleId);
        if (vehicleBookRecordVos != null && vehicleBookRecordVos.size() > 0) {
            Iterator<VehicleBookRecordVo> iterator = vehicleBookRecordVos.iterator();
            while (iterator.hasNext()) {
                VehicleBookRecordVo vehicleBookRecordVo = iterator.next();
                if (vehicleBookRecordVo.getVehicleDepartureLogVo() != null && vehicleBookRecordVo.getVehicleDepartureLogVo().getState() != 1) { //已经出车
                    stringBuilder.append("中，使用人：");
                    stringBuilder.append(vehicleBookRecordVo.getVehicleUsername());
                    stringBuilder.append(" 使用人电话：");
                    stringBuilder.append(vehicleBookRecordVo.getVehicleUserPhone());
                    return stringBuilder.toString();
                }
            }
        }
        stringBuilder.append(", 请联系管理员修改车辆状态为正常状态");
        return stringBuilder.toString();
    }

    public void arrival(VehicleArrivalVo arrivalVo) {
        log.info("用户还车操作：arrivalVo = {}", arrivalVo.toString());
        Vehicle vehicle = vehicleMapper.selectByPrimaryKey(arrivalVo.getVehicleId());
        if (vehicle == null) {
            throw new BaseException(ResCode.VEHICLE_DEPARTURE_VEHICLE_UNEXIST.getDesc(),
                    ResCode.VEHICLE_DEPARTURE_VEHICLE_UNEXIST.getCode());
        }
        Integer MileageRest = vehicle.getMileageLastUpdate();
        Integer MileageRest1 = arrivalVo.getMileage();
        if (MileageRest1 == null) {
            throw new BaseException(ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getDesc(),
                    ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getCode());
        }
        if (MileageRest != null && MileageRest1 >= MileageRest) {
            VehicleBookRecord vehicleBookRecord = null;
            if (arrivalVo.getBookRecordId() != null) {
                vehicleBookRecord = vehicleBookRecordBiz.selectById(arrivalVo.getBookRecordId());
                updateBookRecordStatus(vehicleBookRecord, 2);
            } else {
                throw new BaseException(ResCode.VEHICLE_BOOK_RECORD_IS_NOT_EXIST.getDesc(),
                        ResCode.VEHICLE_BOOK_RECORD_IS_NOT_EXIST.getCode());
            }
            // 写入车辆公里数,还车分公司id
            vehicle.setMileageLastUpdate(MileageRest1);
            // 出车记录
            VehicleDepartureLogVo departureLogVo = vehicleDepartureLogMapper.selectByBookRecordId(arrivalVo.getBookRecordId());

            if (departureLogVo == null) {
                throw new BaseException(ResCode.VEHICLE_DEPARTURE_VEHICLE_UNDEPARTURE.getDesc(),
                        ResCode.VEHICLE_DEPARTURE_VEHICLE_UNDEPARTURE.getCode());
            }
            // 修改状态，确认是出车状态
            //兼容错误还车流程，先查询,是否有其他出行记录
            boolean flag = true;
            VehicleDepartureLog departureLog = departureLogVo.getVehicleDeparture(departureLogVo);
            List<VehicleDepartureLog> list = vehicleDepartureLogMapper.selectByVehicle(arrivalVo.getVehicleId());
            for (VehicleDepartureLog vehicleDepartureLogVo : list) {
                if (vehicleDepartureLogVo.getState() != 1 && vehicleDepartureLogVo.getId() > departureLog.getId()) { //后面还有未收车的记录
                    flag = false;
                }
            }
            if (flag) { //如果此条记录后面还有未收车记录，就不修改车辆状态
                vehicle.setStatus(VehicleStatus.NORMAL.getCode());
            }
            //2019-11-22 16:30 还原还车时修改车辆停靠分公司需求
            vehicle.setParkBranchCompanyId(vehicleBookRecord.getRetCompany());
            vehicleMapper.updateByPrimaryKeySelective(vehicle);

            DateTime arrivalDate = new DateTime(vehicleBookRecord.getBookEndDate());
            DateTime actualArrivalDate = new DateTime(new Date());
            //提前还车处理
            if (actualArrivalDate.compareTo(arrivalDate) < 0) { //实际还车时间小于预计还车时间，需要释放后面的时间
                BookVehicleVO bookVehicleVo = new BookVehicleVO();
                BeanUtils.copyProperties(vehicleBookRecord, bookVehicleVo);
                bookVehicleVo.setNotCheckTimeLegal(Boolean.TRUE);
                bookVehicleVo.setBookStartDate(null);
                bookVehicleVo.setBookEndDate(null);
                bookVehicleVo.setUnbookStartDate(actualArrivalDate.toString(DATE_TIME_FORMATTER));
                bookVehicleVo.setUnbookEndDate(arrivalDate.toString(DATE_TIME_FORMATTER));
                bookVehicleVo.setRemark(bookVehicleVo.getRemark()==null?"": bookVehicleVo.getRemark()+ "  用户提前还车，取消剩余天数, 初始预定结束时间是，" + new DateTime(vehicleBookRecord.getBookEndDate()).toString(DATE_TIME_FORMATTER));
				vehicleBookRecord.setBookEndDate(new Date());
				vehicleBookRecord.setRemark(bookVehicleVo.getRemark());
                try {
                    Boolean hasSuc = vehicleBiz.unbookVehicle(bookVehicleVo);
                    if (!hasSuc) {
                        throw new BaseException(ResCode.VEHICLE_UNBOOK_FAIL.getDesc(), ResCode.VEHICLE_UNBOOK_FAIL.getCode());
                    }
                } catch (Exception e) {
                    log.error("提前还车失败，bookVehicleVo = {}", bookVehicleVo.toString());
                    log.error(e.getMessage(), e);;
                }
            } else if (actualArrivalDate.compareTo(arrivalDate) > 0) {//实际还车时间大于预计还车时间
                vehicleBookRecord.setRemark(vehicleBookRecord.getRemark()==null?"": vehicleBookRecord.getRemark() + "  用户延期还车，实际占用日期");
            }
            updateBookRecordStatus(vehicleBookRecord, 2);
            departureLog.setMileageEnd(arrivalVo.getMileage());
            departureLog.setRecycleMan(arrivalVo.getRecycleMan());
            departureLog.setRecycleManTel(arrivalVo.getRecycleManTel());
            departureLog.setArrivalBranchCompanyId(arrivalVo.getArrivalBranchCompanyId());
            departureLog.setUpdateTime(new Date());
            departureLog.setArrivalTime(new Date());
            departureLog.setState(VehicleDepartureState.END.getCode());
            departureLog.setIllegalPic(arrivalVo.getIllegalPic());
            departureLog.setIllegalAmount(arrivalVo.getIllegalAmount());
            departureLog.setArrivalPic(arrivalVo.getArrivalPic());
            departureLog.setArrivalRemark(arrivalVo.getRemark());
            if (vehicleBookRecord != null) {
                departureLog.setArrivalBranchCompanyId(vehicleBookRecord.getRetCompany());
            }
            //添加收车成功，后面有当天预定的记录时,取消当天的预定
            boolean unBookStatus = unBookArrivalDateTime(vehicleBookRecord);
            if (!unBookStatus) {
                log.info("还车释放当天bookInfo失败！请手动修改！");
            }
            vehicleDepartureLogMapper.updateByPrimaryKeySelective(departureLog);
            // 车辆活动日志
            VehicleActiveLog activeLog = vehicleActiveLogMapper.selectLastByVehicleId(arrivalVo.getVehicleId());
            if (activeLog == null) {
                throw new BaseException(ResCode.VEHICLE_DEPARTURE_VEHICLE_UNDEPARTURE.getDesc(),
                        ResCode.VEHICLE_DEPARTURE_VEHICLE_UNDEPARTURE.getCode());
            }
            activeLog.setEndTime(new Date());
            activeLog.setUpdateTime(new Date());
            vehicleActiveLogMapper.updateByPrimaryKeySelective(activeLog);
        } else {
            throw new BaseException(ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getDesc(),
                    ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getCode());
        }
    }

    public void save(VehicleDepartureLog vehicleDepartureLog){
        vehicleDepartureLogMapper.insertSelective(vehicleDepartureLog);
    }

    /**
     * 如果还车时，还车当天还有其他预定记录，则不释放当天的bookInfo, 如果没有其他记录，则释放当天的bookInfo
     * @param vehicleBookRecord
     * @return
     */
    public boolean unBookArrivalDateTime(VehicleBookRecord vehicleBookRecord) {
        Map<String, Object> map = new HashMap<>();
        Date startDate = null;
        if (vehicleBookRecord.getActualEndDate() == null) {
            startDate = vehicleBookRecord.getBookEndDate();
        } else {
            startDate = vehicleBookRecord.getActualEndDate();
        }
        DateTime bookStartDate = new DateTime(startDate);
        DateTime unBookEndDate = DateTime.now().withMillis(DateUtils.getEndOfDay());
        map.put("startTime", bookStartDate.toString(DATE_TIME_FORMATTER));
        map.put("endTime", unBookEndDate.toString(DATE_TIME_FORMATTER));
        map.put("status", 1);
        map.put("vehicleId", vehicleBookRecord.getVehicleId());
        log.info("查询还车当天是否有其他预定记录：{}", map);
        List<VehicleBookRecordVo> vehicleBookRecords = vehicleBookRecordBiz.selectAllBookRecord(map).getData();
        if (vehicleBookRecords == null || vehicleBookRecords.size() <= 0) { //没有记录，取消记录
            BookVehicleVO bookVehicleVO = new BookVehicleVO();
            bookVehicleVO.setVehicleId(vehicleBookRecord.getVehicleId());
            DateTime unBookStartDate = DateTime.now().withMillis(DateUtils.getStartOfDay());
            bookVehicleVO.setUnbookStartDate(unBookStartDate.toString(DATE_TIME_FORMATTER));
            bookVehicleVO.setUnbookEndDate(unBookEndDate.toString(DATE_TIME_FORMATTER));
            log.info("释放还车当天bookInfo: {}", bookVehicleVO);
            try {
                return vehicleBiz.unbookVehicle(bookVehicleVO);
            } catch (Exception e) {
                log.info("还车释放当天bookInfo失败");
                e.printStackTrace();
            }
        }
            log.info("还车当天有其他预定记录，不释放当天bookInfo, {}", vehicleBookRecords);
            return true;
    }


    //添加出车时间过滤 再出车开始时间前一天至结束时间内可以出车,并且预定记录为已审核状态
    public void checkDateInvalid(VehicleDepartureVo arrivalVo) {
        if (arrivalVo.getBookRecordId() != null) {
            VehicleBookRecord vehicleBookRecord = vehicleBookRecordBiz.selectById(arrivalVo.getBookRecordId());
            if (vehicleBookRecord != null) {
                DateTime startDate = new DateTime(vehicleBookRecord.getBookStartDate());
                DateTime endDate = new DateTime(vehicleBookRecord.getBookEndDate());
                Map<String, Object> param = new HashMap<>();
                param.put("vehicleId", vehicleBookRecord.getVehicleId());
                param.put("time", new Date());
                List<VehicleBookRecordVo> list = vehicleBookRecordBiz.selectByVehicleIdAndTime(param);
                if (list != null && list.size() > 0) {
                    Iterator<VehicleBookRecordVo> iterator = list.iterator();
                    while (iterator.hasNext()) {
                        VehicleBookRecordVo vehicleBookRecordVo = iterator.next();
                        //未出车且超过出车时间和已出车的和本条记录过滤，剩下为正常未出车记录
                        if ((arrivalVo.getBookRecordId().equals(vehicleBookRecordVo.getId())) || ((vehicleBookRecordVo.getBookStartDate().getTime() - vehicleBookRecord.getBookEndDate().getTime() > 0))) {
                            iterator.remove();
                        }
                    }
                }
                if (!(startDate.minusDays(1).compareTo(DateTime.now()) <= 0 && DateTime.now().compareTo(endDate) <= 0 && vehicleBookRecord.getStatus() == VehicleBookRecordStatus.APPROVE.getCode() && (list == null || list.size() <= 0))) {
                    log.error("出车过滤，有正常未还车记录，请按照预定的日期出车");
                    throw new BaseException(ResCode.VEHICLE_DEPARTURE_DATE_IS_NOT_ABLED.getDesc(),
                            ResCode.VEHICLE_DEPARTURE_DATE_IS_NOT_ABLED.getCode());
                }
            }
        }
    }


    public void updateBookRecordStatus(VehicleBookRecord vehicleBookRecord, Integer type) {
        if (vehicleBookRecord != null) {
            if (type == 1) {
                vehicleBookRecord.setActualStartDate(new Date());
            } else {
                vehicleBookRecord.setActualEndDate(new Date());
            }
            vehicleBookRecordBiz.updateSelectiveByIdRe(vehicleBookRecord);
        } else {
            throw new BaseException(ResCode.VEHICLE_BOOK_RECORD_IS_NOT_EXIST.getDesc(),
                    ResCode.VEHICLE_BOOK_RECORD_IS_NOT_EXIST.getCode());
        }
    }


    /**
     * 车辆保养
     *
     * @param vehicleUpkeepVo
     */
    @Transactional
    public void upkeep(VehicleUpkeepVo vehicleUpkeepVo) {

        Vehicle vehicle = vehicleMapper.selectByPrimaryKey(vehicleUpkeepVo.getVehicleId());
        if (vehicle == null) {
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_UNEXIST.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_UNEXIST.getCode());
        }
        if (!vehicle.getStatus().equals(VehicleStatus.NORMAL.getCode())) {
            // 车辆非正常状态
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_DISABLE.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_DISABLE.getCode());
        }
        Integer lastMileage = vehicleUpkeepVo.getMileage();
        int result = vehicleMapper.upMileageByIdAndStatus(vehicleUpkeepVo.getVehicleId(), VehicleStatus.UPKEEP.getCode(),
                VehicleStatus.NORMAL.getCode(), lastMileage);
        if (result == 0) {
            // 车辆状态异常
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_DISABLE.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_DISABLE.getCode());
        }

        // 维修记录
        VehicleUpkeepLog vehicleUpkeepLog = new VehicleUpkeepLog();
        BeanUtils.copyProperties(vehicleUpkeepVo, vehicleUpkeepLog);
        vehicleUpkeepLog.setCreateTime(new Date());
        vehicleUpkeepLogMapper.insertSelective(vehicleUpkeepLog);

        // 维修项目
        List<Integer> upkeepItems = vehicleUpkeepVo.getUpkeepItems();
        for (Integer itemId : upkeepItems) {
            if (vehicleUpkeepItemMapper.selectByPrimaryKey(itemId) == null) {
                // 保养项目不存在
                throw new BaseException(ResCode.VEHICLE_UPKEEP_ITEM_UNEXIST.getDesc(),
                        ResCode.VEHICLE_UPKEEP_ITEM_UNEXIST.getCode());
            }
        }
        vehicleUpkeepLogMapper.addItems(vehicleUpkeepLog.getId(), upkeepItems);

        // 活动记录
        VehicleActiveLog vehicleActiveLog = new VehicleActiveLog();
        vehicleActiveLog.setVehicleId(vehicleUpkeepVo.getVehicleId());
        vehicleActiveLog.setActiveType(VehicleActiveType.UPKEEP.getCode());
        vehicleActiveLog.setCreateTime(new Date());
        vehicleActiveLog.setStartTime(new Date());
        vehicleActiveLogMapper.insertSelective(vehicleActiveLog);
    }

    /**
     * 保养结束
     *
     * @param vehicleUpkeepEndVo
     */
    @Transactional
    public void upkeepEnd(VehicleUpkeepEndVo vehicleUpkeepEndVo) {
        String vehicleId = vehicleUpkeepEndVo.getVehicleId();
        Vehicle vehicle = vehicleMapper.selectByPrimaryKey(vehicleId);
        if (vehicle == null) {
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_UNEXIST.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_UNEXIST.getCode());
        }
        if (!vehicle.getStatus().equals(VehicleStatus.UPKEEP.getCode())) {
            // 车辆非保养状态
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getCode());
        }
        Integer mileageLastUpdate = vehicle.getMileageLastUpdate() == null ? 0 : vehicle.getMileageLastUpdate();
        Integer maintenance_mileage = Mileage + mileageLastUpdate;
        int result = vehicleMapper.updateMileageStatusByIdAndStatus(vehicleId, VehicleStatus.NORMAL.getCode(), VehicleStatus.UPKEEP.getCode(), maintenance_mileage);
        if (result == 0) {
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getCode());
        }

        VehicleUpkeepLog vehicleUpkeepLog = vehicleUpkeepLogMapper.selectLastByVehicleId(vehicleId);
        if (vehicleUpkeepLog == null) {
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getCode());
        }

        VehicleActiveLog vehicleActiveLog = vehicleActiveLogMapper.selectLastByVehicleId(vehicleId);
        if (vehicleActiveLog == null || !vehicleActiveLog.getActiveType().equals(VehicleActiveType.UPKEEP.getCode())) {
            throw new BaseException(ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getDesc(),
                    ResCode.VEHICLE_UPKEEP_VEHICLE_UNUPKEEP.getCode());
        }
        vehicleActiveLog.setEndTime(new Date());
        vehicleActiveLog.setUpdateTime(new Date());
        vehicleActiveLogMapper.updateByPrimaryKeySelective(vehicleActiveLog);


    }

    public ObjectRestResponse selectDepartureLogByBookRecordId(Long bookRecordId) {
        if (bookRecordId == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        VehicleDepartureLogVo vehicleDepartureLog = vehicleDepartureLogMapper.selectByBookRecordId(bookRecordId);
        if (vehicleDepartureLog == null) {
            return ObjectRestResponse.createFailedResult(ResCode.FIND_DATA_NOT_EXIST.getCode(), ResCode.FIND_DATA_NOT_EXIST.getDesc());
        }
        return ObjectRestResponse.succ(vehicleDepartureLog);
    }


    public static void main(String[] args) {
        DateTime startDate = DateTime.parse("2019-08-21 17:00:00", DATE_TIME_FORMATTER);
        DateTime endDate = DateTime.parse("2019-08-21 21:00:00", DATE_TIME_FORMATTER);
        System.out.println();
        System.out.println(!(DateTime.now().compareTo(endDate) <= 0) && (startDate.minusDays(1).compareTo(DateTime.now()) <= 0));
    }
}
