package com.xxfc.platform.order.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.activity.entity.Coupon;
import com.xxfc.platform.activity.user.UserInfoBiz;
import com.xxfc.platform.order.biz.inner.OrderMsgBiz;
import com.xxfc.platform.order.contant.enumerate.AccountTypeEnum;
import com.xxfc.platform.order.contant.enumerate.CrosstownTypeEnum;
import com.xxfc.platform.order.contant.enumerate.DepositRefundStatus;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.entity.*;
import com.xxfc.platform.order.mapper.OrderVehicaleCrosstownMapper;
import com.xxfc.platform.order.pojo.DedDetailDTO;
import com.xxfc.platform.order.pojo.account.OrderAccountDetail;
import com.xxfc.platform.order.pojo.mq.OrderMQDTO;
import com.xxfc.platform.order.pojo.order.CheckUserInfoDto;
import com.xxfc.platform.order.pojo.order.OrderPageVO;
import com.xxfc.platform.order.pojo.order.OrderVehicleCrosstownDto;
import com.xxfc.platform.universal.constant.DictionaryKey;
import com.xxfc.platform.universal.entity.Dictionary;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.common.RestResponse;
import com.xxfc.platform.vehicle.constant.ResCode.ResCode;
import com.xxfc.platform.vehicle.entity.Vehicle;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.CompanyDetail;
import com.xxfc.platform.vehicle.pojo.VehicleArrivalVo;
import com.xxfc.platform.vehicle.pojo.VehicleDepartureVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors;

import static com.xxfc.platform.universal.constant.DictionaryKey.APP_ORDER;

@Service
@Slf4j
public class OrderVehicleCrosstownBiz extends BaseBiz<OrderVehicaleCrosstownMapper, OrderVehicleCrosstown> {

    @Autowired
    OrderVehicleCrosstownBiz orderVehicleCrosstownBiz;

    @Autowired
    OrderUserLicenseBiz orderUserLicenseBiz;
    @Autowired
    ThirdFeign thirdFeign;
    @Autowired
    UserInfoBiz userInfoBiz;
    @Autowired
    VehicleFeign vehicleFeign;
    @Autowired
    UserFeign userFeign;
    @Autowired
    OrderRentVehicleBiz orderRentVehicleBiz;
    @Autowired
    OrderDepositRefundRecordBiz orderDepositRefundRecordBiz;
    @Autowired
    BaseOrderBiz baseOrderBiz;
    @Autowired
    OrderItemBiz orderItemBiz;
    @Autowired
    OrderMsgBiz orderMsgBiz;
    @Autowired
    OrderAccountBiz orderAccountBiz;


    public OrderVehicleCrosstown get(Integer id) {
        return selectById(id);
    }

    public static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd");

    public List<OrderVehicleCrosstownDto> selectByOrderId(OrderVehicleCrosstownDto orderVehicleCrosstownDto) {
        if (StringUtils.isNotBlank(orderVehicleCrosstownDto.getTypes())) {
            String[] types = orderVehicleCrosstownDto.getTypes().split(",");
            orderVehicleCrosstownDto.setTypeList(Lists.newArrayList(types));
        }
        List<OrderVehicleCrosstownDto> list = mapper.selectByOrderId(orderVehicleCrosstownDto);
        for (OrderVehicleCrosstownDto value : list) {
            if (value != null && value.getOrperaterId() != null && value.getType() != 1) {
                UserDTO userDTO = userFeign.userinfoByUid(value.getOrperaterId()).getData();
                if (userDTO != null) {
                    CompanyDetail branchCompany = vehicleFeign.getCompanyDetail(userDTO.getCompanyId()).getData();
                    if (branchCompany != null) {
                        value.setCustomerPhone(branchCompany.getVehiceServicePhone());
                    }
                }
            }

            if (value.getType() == 2 || value.getType() == 3) {
                List<Coupon> c = baseOrderBiz.getReturnCouponByOrderId(value.getOrderId());
                value.setBackCoupons(c);
                if (StringUtils.isNotBlank(value.getDedDetail())) {
                    List<DedDetailDTO> dddList = JSONUtil.toList(JSONUtil.parseArray(value.getDedDetail()), DedDetailDTO.class);
                    value.setDedDetailDTOList(dddList);
                }
                if (StringUtils.isNotBlank(value.getViolateDetail())) {
                    List<DedDetailDTO> dddList = JSONUtil.toList(JSONUtil.parseArray(value.getViolateDetail()), DedDetailDTO.class);
                    value.setViolateDetailList(dddList);
                }

            }
            if (value.getType()!=1){
                Example example = new Example(OrderAccount.class);
                //获取退还部分押金和剩余押金的记录
                example.createCriteria().andEqualTo("orderId",value.getOrderId()).andIn("accountType",Lists.newArrayList(AccountTypeEnum.OUT_PART_DEPOSIT.getCode(),AccountTypeEnum.OUT_RESIDUE_DEPOSIT.getCode()));
                List<OrderAccount> orderAccounts = orderAccountBiz.selectByExample(example);
                if (CollectionUtil.isEmpty(orderAccounts)) {
                    value.setActualDeposit("定损中");
                }
                for (OrderAccount orderAccount : orderAccounts) {
                    if (AccountTypeEnum.OUT_PART_DEPOSIT.getCode().equals(orderAccount.getAccountType())) {
                        OrderAccountDetail orderAccountDetail = JSONUtil.toBean(orderAccount.getAccountDetail(), OrderAccountDetail.class);
                        value.setActualDeposit(orderAccountDetail.getDepositAmount().toString());
                    }
                    if (AccountTypeEnum.OUT_RESIDUE_DEPOSIT.getCode().equals(orderAccount.getAccountType())) {
                        value.setRefundOfRemainingDeposit(orderAccount.getOriginalAmount());
                        value.setViolationOfCharges(orderAccount.getDeductAmount());
                    }
                }

            }

            updateCrossRecord(value);
            List<DepositRefundRecord> depositRefundRecords = orderDepositRefundRecordBiz.selectByCrossId(value.getId());
            if ( orderVehicleCrosstownDto.getAddress()!=null&&
                    1 == orderVehicleCrosstownDto.getAddress() && CollectionUtil.isNotEmpty(depositRefundRecords)) {
                depositRefundRecords = depositRefundRecords.parallelStream().filter(e -> {
                    if (e.getStatus() == 4||e.getStatus() == 5||e.getStatus() == 1) {
                        return false;
                    }
                    return true;
                }).collect(Collectors.toList());
            }


            value.setDepositRefundRecord(depositRefundRecords == null || depositRefundRecords.size() <= 0 ? null : depositRefundRecords);
        }
        return list;
    }

    public OrderVehicleCrosstownDto getByOrderId(OrderVehicleCrosstownDto orderVehicleCrosstownDto) {
        List<OrderVehicleCrosstownDto> list = mapper.selectByOrderId(orderVehicleCrosstownDto);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    public void updateCrossRecord(OrderVehicleCrosstownDto value) {
        if (value.getOrperaterId() != null) {
            ObjectRestResponse<UserDTO> userDTOObjectRestResponse = userFeign.userinfoByUid(value.getOrperaterId());
            log.info("操作人用户信息:{}",userDTOObjectRestResponse.getData());
            if (userDTOObjectRestResponse.getData() != null) {
                UserDTO data = userDTOObjectRestResponse.getData();
//                value.setUsername(data.getNickname());
//                value.setOperatorName(data.getRealname());
                value.setOperatorPhone(data.getUsername());
                value.setOperatorTime(value.getCrtTime());
            }
        }
        if (value.getUserLicenseId() != null) {
            List<OrderUserLicense> orderUserLicenses = orderUserLicenseBiz.selectByIds(value.getUserLicenseId()).getData();
            if (orderUserLicenses != null && orderUserLicenses.size() > 0) {
                value.setLicenseIdCard(orderUserLicenses.get(0).getLicenseIdCard());
                value.setLicenseImg(orderUserLicenses.get(0).getLicenseImg());
                value.setLicenseName(orderUserLicenses.get(0).getLicenseName());
                value.setLicensePhone(orderUserLicenses.get(0).getLicensePhone());
            }
        }
    }


    public ObjectRestResponse selectByOrderNo(String no) {
        ObjectRestResponse<OrderPageVO> objectRestResponse = baseOrderBiz.getOrderDetail(no);
        if (objectRestResponse.getData() == null) {
            return ObjectRestResponse.createFailedResult(2379, "订单不存在");
        }
        OrderPageVO orderPageVO = objectRestResponse.getData();
        Map<String, Object> map = new HashedMap<>();
        if (orderPageVO.getStatus() == OrderStatusEnum.ORDER_FINISH.getCode()) {//订单已完成
            map.put("no", orderPageVO.getNo());
            map.put("type", CrosstownTypeEnum.ARRIVE.getCode());
        } else if (orderPageVO.getStatus() == OrderStatusEnum.ORDER_FIXED_LOSS.getCode()) {//订单定损中
            map.put("no", orderPageVO.getNo());
            map.put("type", CrosstownTypeEnum.FIXED_LOSS.getCode());
        } else if (orderPageVO.getStatus() == OrderStatusEnum.ORDER_WAIT.getCode()) {//订单出行中
            map.put("no", orderPageVO.getNo());
            map.put("type", CrosstownTypeEnum.DEPARTURE.getCode());
        } else {
            return ObjectRestResponse.succ();
        }
        OrderVehicleCrosstownDto orderVehicleCrosstownDto = mapper.selectByOrderNo(map);
        updateCrossRecord(orderVehicleCrosstownDto);
        List<DepositRefundRecord> list = orderDepositRefundRecordBiz.selectByCrossId(orderVehicleCrosstownDto.getId());
        orderVehicleCrosstownDto.setDepositRefundRecord(list == null || list.size() <= 0 ? null : list);
        return ObjectRestResponse.succ(orderVehicleCrosstownDto);
    }


    @Transactional(rollbackFor = Exception.class)
    public ObjectRestResponse<OrderVehicleCrosstownDto> add(OrderVehicleCrosstownDto orderVehicleCrosstownDto) {
        log.info("交还车参数：orderVehicleCrosstown = {}", orderVehicleCrosstownDto);
        UserDTO userDTO = userInfoBiz.getAdminUserInfo();
        if (userDTO == null) {
            return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, "token is null or invalid");
        }
        if (orderVehicleCrosstownDto == null || orderVehicleCrosstownDto.getOrderId() == null) {
            return ObjectRestResponse.paramIsEmpty();
        }
        orderVehicleCrosstownDto.setOrperaterId(userDTO.getId());
        BaseOrder baseOrder = baseOrderBiz.selectById(orderVehicleCrosstownDto.getOrderId());
        if (baseOrder == null) {
            return ObjectRestResponse.createFailedResult(ResCode.ORDER_IS_NOT_EXIST.getCode(), ResCode.ORDER_IS_NOT_EXIST.getDesc());
        }

        OrderRentVehicleDetail orderRentVehicleDetail = orderRentVehicleBiz.selectById(baseOrder.getDetailId());
        if (orderVehicleCrosstownDto.getType() == CrosstownTypeEnum.DEPARTURE.getCode()) {
            boolean flag = getTodayTime(orderRentVehicleDetail.getStartTime(), orderRentVehicleDetail.getEndTime());
            if (!flag) {
                return ObjectRestResponse.createFailedResult(3502, "已超过预定还车时间，不能进行交车操作！");
            }
            if (null == userDTO.getCompanyId() || !userDTO.getCompanyId().equals(orderRentVehicleDetail.getStartCompanyId())) {
                return ObjectRestResponse.createFailedResult(3501, "无交车权限");
            }
        } else {
            if (null == userDTO.getCompanyId() || !userDTO.getCompanyId().equals(orderRentVehicleDetail.getEndCompanyId())) {
                return ObjectRestResponse.createFailedResult(3503, "无收车权限");
            }
        }
        Vehicle vehicle = null;
        RestResponse<Vehicle> vehicleRestResponse = vehicleFeign.findById(orderRentVehicleDetail.getVehicleId());
        if (vehicleRestResponse.getData() != null) {
            vehicle = vehicleRestResponse.getData();
        } else {
            return ObjectRestResponse.createFailedResult(ResCode.VEHICLE_DEPARTURE_VEHICLE_UNEXIST.getCode(), ResCode.VEHICLE_DEPARTURE_VEHICLE_UNEXIST.getDesc());
        }
        //非定损状态下要判断车辆公里数
        if (baseOrder.getStatus() != -1) {
            if (vehicle.getMileageLastUpdate() != null) {
                //判断车辆公里数
                if (orderVehicleCrosstownDto.getMileage() == null || orderVehicleCrosstownDto.getMileage() < vehicle.getMileageLastUpdate()) {
                    return ObjectRestResponse.createFailedResult(ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getCode(), ResCode.VEHICLE_BOOKED_RECORD_MILEAGE_CHANGED.getDesc());
                }
            }
        }
        //添加验车人信息
        JSONArray list = new JSONArray();
        CheckUserInfoDto checkUserInfoDto = null;
        if (StringUtils.isNotBlank(orderVehicleCrosstownDto.getCheckUserInfo())) {
             checkUserInfoDto = JSONObject.parseObject(orderVehicleCrosstownDto.getCheckUserInfo(), CheckUserInfoDto.class);
            if (checkUserInfoDto != null) {
                list.add(checkUserInfoDto);
            }
        }
        AppUserDTO appUserDTO = userFeign.userDetailById(baseOrder.getUserId()).getData();
        //调用车辆管理的出车还车
        //出车
        if (orderVehicleCrosstownDto.getType() == CrosstownTypeEnum.DEPARTURE.getCode()) { //交车
            VehicleDepartureVo vehicleDepartureVo = new VehicleDepartureVo();
            vehicleDepartureVo.setVehicleId(orderRentVehicleDetail.getVehicleId());
            vehicleDepartureVo.setDepartureBranchCompanyId(orderRentVehicleDetail.getStartCompanyId());
            vehicleDepartureVo.setExpectArrivalBranchCompanyId(orderRentVehicleDetail.getEndCompanyId());
            vehicleDepartureVo.setMileage(orderVehicleCrosstownDto.getMileage());
            vehicleDepartureVo.setBookRecordId(orderRentVehicleDetail.getBookRecordId());
            if (checkUserInfoDto != null) {
                vehicleDepartureVo.setCheckMan(checkUserInfoDto.getUsername());
                vehicleDepartureVo.setCheckManTel(checkUserInfoDto.getTelephone());
            }
            log.info("小程序订单出车： " + vehicleDepartureVo.toString());
            try {
                RestResponse restResponse = vehicleFeign.departureBySmall(vehicleDepartureVo);
                if (restResponse.getStatus() != 200) {
                    return ObjectRestResponse.createFailedResult(1001, restResponse.getMessage());
                }
                log.info("小程序订单出车成功： " + restResponse.getCode() + restResponse.getMessage());
            } catch (Exception e) {
                return ObjectRestResponse.createFailedResult(1001, e.getMessage());
            }
        } else if (orderVehicleCrosstownDto.getType() == CrosstownTypeEnum.ARRIVE.getCode() || orderVehicleCrosstownDto.getType() == CrosstownTypeEnum.FIXED_LOSS.getCode() || orderVehicleCrosstownDto.getType() == CrosstownTypeEnum.FIXED_LOSS_NOW.getCode()) { //还车
            VehicleArrivalVo vehicleArrivalVo = new VehicleArrivalVo();
            vehicleArrivalVo.setVehicleId(orderRentVehicleDetail.getVehicleId());
            vehicleArrivalVo.setArrivalBranchCompanyId(userDTO.getCompanyId());
            vehicleArrivalVo.setMileage(orderVehicleCrosstownDto.getMileage());
            if (checkUserInfoDto != null) {
                vehicleArrivalVo.setRecycleMan(checkUserInfoDto.getUsername());
                vehicleArrivalVo.setRecycleManTel(checkUserInfoDto.getTelephone());
            }
            vehicleArrivalVo.setBookRecordId(orderRentVehicleDetail.getBookRecordId());
            log.info("小程序订单还车： " + vehicleArrivalVo.toString());
            try {
                RestResponse restResponse = vehicleFeign.arrivalBySmall(vehicleArrivalVo);
                if (restResponse.getStatus() != 200) {
                    return ObjectRestResponse.createFailedResult(1001, restResponse.getMessage());
                }
                log.info("小程序订单还车成功： " + restResponse.getCode() + restResponse.getMessage());
            } catch (Exception e) {
                return ObjectRestResponse.createFailedResult(500, e.getMessage());
            }
        }
        Double cost = 0.0;
        //定损扣除费用
        if (StringUtils.isNotBlank(orderVehicleCrosstownDto.getDedDetail())) {
            JSONArray jsonArray = JSONArray.parseArray(orderVehicleCrosstownDto.getDedDetail());
            if (jsonArray != null && jsonArray.size() > 0) {
                orderVehicleCrosstownDto.setDeduction(true);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
                    if (jsonObject != null) {
                        cost += Double.parseDouble(jsonObject.getString("cost"));
                    }
                }
            }
        }
        //延期扣除费用
        if (StringUtils.isNotBlank(orderVehicleCrosstownDto.getViolateDetail())) {
            JSONArray jsonArray = JSONArray.parseArray(orderVehicleCrosstownDto.getViolateDetail());
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
                    if (jsonObject.getString("cost") != null) {
                        cost += Double.parseDouble(jsonObject.getString("cost"));
                    }
                    if (jsonObject.getString("excessCost") != null) {
                        cost += Double.parseDouble(jsonObject.getString("excessCost"));
                    }
                }
            }
        }
		//延期扣除费用
		if (StringUtils.isNotBlank(orderVehicleCrosstownDto.getDelayVehicleDetail())) {
			JSONArray jsonArray = JSONArray.parseArray(orderVehicleCrosstownDto.getDelayVehicleDetail());
			if (jsonArray != null && jsonArray.size() > 0) {
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
					if (jsonObject.getString("cost") != null) {
						cost += Double.parseDouble(jsonObject.getString("cost"));
					}
				}
			}
		}
        orderVehicleCrosstownDto.setUserLicenseImg(orderVehicleCrosstownDto.getLicenseImg());
        //扣除费用,每次都是重新计算
        BigDecimal amount = new BigDecimal(cost.toString()).divide(new BigDecimal("1"), 2, BigDecimal.ROUND_UP);
        //出车成功后修改订单状态
        List<OrderVehicleCrosstownDto> oldValue = orderVehicleCrosstownBiz.selectByOrderId(orderVehicleCrosstownDto);
        orderVehicleCrosstownDto.setUserLicenseImg(orderVehicleCrosstownDto.getLicenseImg());
        if (oldValue.size() == 1) {
            orderVehicleCrosstownDto.setDeductionCost(amount);
            //扣除费用
            orderVehicleCrosstownDto.setRestDeposit(orderRentVehicleDetail.getDeposit().subtract(orderVehicleCrosstownDto.getDeductionCost()));
            if (orderVehicleCrosstownDto.getRestDeposit().compareTo(getAmount()) == -1) { //剩余金额小于保证金
                return ObjectRestResponse.createFailedResult(500, "押金不足，不能交车，请联系客服！");
            }
            if(StringUtils.isNotBlank(oldValue.get(0).getCheckUserInfo())) {
                JSONArray jsonArray = JSONArray.parseArray(oldValue.get(0).getCheckUserInfo());
                if (jsonArray != null && checkUserInfoDto != null) {
                    jsonArray.add(checkUserInfoDto);
                    orderVehicleCrosstownDto.setCheckUserInfo(jsonArray.toJSONString());
                }
            } else {
                orderVehicleCrosstownDto.setCheckUserInfo(list.toJSONString());
            }
            BeanUtil.copyProperties(orderVehicleCrosstownDto, oldValue.get(0), CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            getOrderLicense(orderVehicleCrosstownDto);
            handleOrderStatus(baseOrder, orderRentVehicleDetail, oldValue.get(0), appUserDTO);
            updateSelectiveByIdRe(oldValue.get(0));
            RestResponse<Vehicle> response = vehicleFeign.findById(orderRentVehicleDetail.getVehicleId());
            if (response.getData() != null) {
                orderVehicleCrosstownDto.setVehicleNumberPlat(response.getData().getNumberPlate());
            }
            return ObjectRestResponse.succ(oldValue.get(0));
        } else if (oldValue.size() <= 0) {
            orderVehicleCrosstownDto.setDeductionCost(amount);
            //剩余押金 = 总押金 - 扣除费用
            orderVehicleCrosstownDto.setRestDeposit(orderRentVehicleDetail.getDeposit().subtract(orderVehicleCrosstownDto.getDeductionCost()));
            if (orderVehicleCrosstownDto.getRestDeposit().compareTo(getAmount()) == -1) { //剩余金额小于保证金
                return ObjectRestResponse.createFailedResult(500, "押金不足，不能交车，请联系客服！");
            }
            orderVehicleCrosstownDto.setCheckUserInfo(list.toJSONString());
            getOrderLicense(orderVehicleCrosstownDto);
            orderVehicleCrosstownBiz.insertSelective(orderVehicleCrosstownDto);
            OrderVehicleCrosstown orderVehicleCrosstown = orderVehicleCrosstownBiz.selectOne(orderVehicleCrosstownDto);
            handleOrderStatus(baseOrder, orderRentVehicleDetail, orderVehicleCrosstown, appUserDTO);
            orderVehicleCrosstownBiz.updateSelectiveByIdRe(orderVehicleCrosstown);
            RestResponse<Vehicle> response = vehicleFeign.findById(orderRentVehicleDetail.getVehicleId());
            if (response.getData() != null) {
                orderVehicleCrosstownDto.setVehicleNumberPlat(response.getData().getNumberPlate());
            }
            return ObjectRestResponse.succ(orderVehicleCrosstownDto);
        }

        return ObjectRestResponse.createDefaultFail();
    }

    private void handleOrderStatus(BaseOrder baseOrder, OrderRentVehicleDetail orderRentVehicleDetail, OrderVehicleCrosstown orderVehicleCrosstown, AppUserDTO appUserDTO) {
        //交车完成 设置订单状态为出行中
        BigDecimal illegalReserve = getAmount();
        BigDecimal totalAmount = orderRentVehicleDetail.getDeposit();
        if (baseOrder.getStatus() == OrderStatusEnum.ORDER_TOSTART.getCode()) {//交车
            baseOrder.setStatus(OrderStatusEnum.ORDER_WAIT.getCode());
            baseOrder = baseOrderBiz.updateSelectiveByIdReT(baseOrder);
            orderMsgBiz.handelMsgWait(orderRentVehicleDetail, null, null, baseOrder, appUserDTO);
        } else if (baseOrder.getStatus() == OrderStatusEnum.ORDER_WAIT.getCode()) { //还车
            if (orderVehicleCrosstown.getType() == CrosstownTypeEnum.ARRIVE.getCode()) {//不定损直接还车
                    //添加非定损押金记录
                    DepositRefundRecord depositRefundRecord = new DepositRefundRecord();
                    depositRefundRecord.setAmount(orderVehicleCrosstown.getDeductionCost());
                    depositRefundRecord.setRestAmount(totalAmount.subtract(illegalReserve).subtract(orderVehicleCrosstown.getDeductionCost()));
                    depositRefundRecord.setTotalAmount(totalAmount.subtract(illegalReserve));
                    depositRefundRecord.setCrosstownId(orderVehicleCrosstown.getId());
                    orderDepositRefundRecordBiz.saveNormalRecord(depositRefundRecord);
                    //修改订单状态为已完成
                    baseOrder.setStatus(OrderStatusEnum.ORDER_FINISH.getCode());
                    baseOrder = baseOrderBiz.updateSelectiveByIdReT(baseOrder);
                    //修改订单详情是否押金全部退还
                    orderRentVehicleDetail.setFixedLossStatus(0);
                    orderRentVehicleBiz.updateSelectiveByIdRe(orderRentVehicleDetail);
                    baseOrderBiz.sendOrderMq(orderRentVehicleDetail, null, null, baseOrder, OrderMQDTO.ORDER_FINISH);
            } else if (orderVehicleCrosstown.getType() == CrosstownTypeEnum.FIXED_LOSS.getCode()) { //延时定损还车，只添加定损记录
                //添加定损记录
                DepositRefundRecord depositRefundRecord = new DepositRefundRecord();
                depositRefundRecord.setAmount(orderVehicleCrosstown.getDeductionCost());
                depositRefundRecord.setRestAmount(totalAmount.subtract(illegalReserve).subtract(orderVehicleCrosstown.getDeductionCost()));
                depositRefundRecord.setTotalAmount(totalAmount.subtract(illegalReserve));
                depositRefundRecord.setCrosstownId(orderVehicleCrosstown.getId());
                orderDepositRefundRecordBiz.saveFixLossRecord(depositRefundRecord, false);
                //修改訂單狀態為定損
                baseOrder.setStatus(OrderStatusEnum.ORDER_FIXED_LOSS.getCode());
                baseOrder = baseOrderBiz.updateSelectiveByIdReT(baseOrder);
                orderRentVehicleDetail.setFixedLossStatus(1);
                orderRentVehicleBiz.updateSelectiveByIdRe(orderRentVehicleDetail);
            } else if (orderVehicleCrosstown.getType() == CrosstownTypeEnum.FIXED_LOSS_NOW.getCode()) { //直接定损还车
                //添加定损押金记录
                orderVehicleCrosstown.setType(CrosstownTypeEnum.FIXED_LOSS.getCode());
                DepositRefundRecord depositRefundRecord = new DepositRefundRecord();
                depositRefundRecord.setAmount(orderVehicleCrosstown.getDeductionCost());
                depositRefundRecord.setRestAmount(totalAmount.subtract(illegalReserve).subtract(orderVehicleCrosstown.getDeductionCost()));
                depositRefundRecord.setTotalAmount(totalAmount.subtract(illegalReserve));
                depositRefundRecord.setCrosstownId(orderVehicleCrosstown.getId());
                orderDepositRefundRecordBiz.saveFixLossRecord(depositRefundRecord, true);
                //修改訂單狀態為已完成
                baseOrder.setStatus(OrderStatusEnum.ORDER_FINISH.getCode());
                baseOrder = baseOrderBiz.updateSelectiveByIdReT(baseOrder);
                orderRentVehicleDetail.setFixedLossStatus(1);
                orderRentVehicleBiz.updateSelectiveByIdRe(orderRentVehicleDetail);
                baseOrderBiz.sendOrderMq(orderRentVehicleDetail, null, null, baseOrder, OrderMQDTO.ORDER_FINISH);
            }
        } else if (baseOrder.getStatus() == OrderStatusEnum.ORDER_FIXED_LOSS.getCode()) {//定损后还车
            DepositRefundRecord depositRefundRecord = orderDepositRefundRecordBiz.findByCrossIdAndStatus(orderVehicleCrosstown.getId(), DepositRefundStatus.FIXLOSSREFUND.getCode());
            if (depositRefundRecord != null) {
                DepositRefundRecord newValue = new DepositRefundRecord();
                BeanUtil.copyProperties(depositRefundRecord, newValue, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
                depositRefundRecord.setIsshow(false);
                orderDepositRefundRecordBiz.updateSelectiveByIdRe(depositRefundRecord);
                newValue.setIscomplete(true); //发起退款显示
                newValue.setAmount(orderVehicleCrosstown.getDeductionCost());
                newValue.setRestAmount(totalAmount.subtract(illegalReserve).subtract(orderVehicleCrosstown.getDeductionCost()));
                newValue.setTotalAmount(totalAmount.subtract(illegalReserve));
                newValue.setCrosstownId(orderVehicleCrosstown.getId());
                newValue.setId(null);
                orderDepositRefundRecordBiz.save(newValue);
                DepositRefundRecord nextValue = orderDepositRefundRecordBiz.findByCrossIdAndStatus(orderVehicleCrosstown.getId(), DepositRefundStatus.FIXLOSSREFUNDARRIVAL.getCode());
                if (nextValue != null) {
                    nextValue.setRestAmount(newValue.getRestAmount());
                    orderDepositRefundRecordBiz.update(nextValue);
                }
            } else {
                throw new BaseException("定损记录不存在！请联系客服");
            }
            baseOrder.setStatus(OrderStatusEnum.ORDER_FINISH.getCode());
            baseOrder = baseOrderBiz.updateSelectiveByIdReT(baseOrder);
            baseOrderBiz.sendOrderMq(orderRentVehicleDetail, null, null, baseOrder, OrderMQDTO.ORDER_FINISH);
        }
    }


    //添加订单驾驶人信息
    public void getOrderLicense(OrderVehicleCrosstownDto orderVehicleCrosstownDto) {
        if (StringUtils.isNotBlank(orderVehicleCrosstownDto.getLicenseIdCard())) {
            OrderUserLicense orderUserLicense = new OrderUserLicense();
            orderUserLicense.setLicenseIdCard(orderVehicleCrosstownDto.getLicenseIdCard());
            orderUserLicense.setLicenseImg(orderVehicleCrosstownDto.getLicenseImg());
            orderUserLicense.setLicenseName(orderVehicleCrosstownDto.getLicenseName());
            orderUserLicense.setLicensePhone(orderVehicleCrosstownDto.getLicensePhone());
            if (orderUserLicense != null) {
                Integer id = orderUserLicenseBiz.add(orderUserLicense).getData().getId();
                orderVehicleCrosstownDto.setUserLicenseId(id + "");
            }
        }
    }

    public BigDecimal getAmount() {
        //设置保留金
        Map<String, Dictionary> dictionaryMap = thirdFeign.dictionaryGetAll4Map().getData();
        BigDecimal illegalReserve = new BigDecimal(dictionaryMap.get(APP_ORDER + "_" + DictionaryKey.ILLEGAL_RESERVE).getDetail());
        return illegalReserve;
    }

    /**
     * 当前时间大于预定开始时间当天0点，小于结束时间当天时间24点 2019.11.04
     * @param startTime
     * @param endTime
     * @return
     */
    public boolean getTodayTime(Long startTime, Long endTime) {
        long current = System.currentTimeMillis();
        if (getDayStart(startTime) <= (current) && current <= getDayStart(endTime) + 1000 * 3600 * 24 - 1) {
            return true;
        }
        return false;
    }

    public static Long getDayStart(Long time) {
        long current = time;
        long zero = current / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
        return zero;
    }

}
