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.admin.feign.rest.UserRestInterface;
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.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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.stream.Collectors;

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

    @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;

    @Override
    public UserFeign getUserFeign() {
        return userFeign;
    }

    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) throws BaseException{
        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.userinfoByUidV2(value.getOrperaterId()).getData();
                if (userDTO != null && userDTO.getCompanyIds() != null && userDTO.getCompanyIds().size() > 0) {
                    CompanyDetail branchCompany = vehicleFeign.getCompanyDetail(userDTO.getCompanyIds().get(0)).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())).andEqualTo("accountStatus", 1);
                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);

        //获取app用户信息 根据用户名（手机号）定位后台商家用户
        UserDTO userDTO = getBusinessUserByAppUser();

        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.getCompanyIds() || !userDTO.getCompanyIds().contains(orderRentVehicleDetail.getStartCompanyId())) {
                return ObjectRestResponse.createFailedResult(3501, "无交车权限");
            }
            userDTO.setCompanyId(orderRentVehicleDetail.getStartCompanyId());
        } else {
            if (null == userDTO.getCompanyIds() || !userDTO.getCompanyIds().contains(orderRentVehicleDetail.getEndCompanyId())) {
                return ObjectRestResponse.createFailedResult(3503, "无收车权限");
            }
            userDTO.setCompanyId(orderRentVehicleDetail.getEndCompanyId());
        }

        //添加验车人信息
        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());
            if (orderVehicleCrosstownDto.getMileage() == null) {
                vehicleDepartureVo.setMileage(0);
            } else {
                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);
                log.info("小程序订单出车成功： " + restResponse.getCode() + restResponse.getMessage());
                if (restResponse.getStatus() != 200) {
                    return ObjectRestResponse.createFailedResult(1001, 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());
            if (orderVehicleCrosstownDto.getMileage() == null) {
                vehicleArrivalVo.setMileage(0);
            } else {
                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());

                //设置订单实际还车公司
                CompanyDetail companyDetail = vehicleFeign.getCompanyDetail(vehicleArrivalVo.getArrivalBranchCompanyId()).getData();
                //业务上先更新修改，业务解耦。
                orderRentVehicleBiz.updateSelectiveById(new OrderRentVehicleDetail(){{
                    setId(orderRentVehicleDetail.getId());
                    setActualEndCompanyId(companyDetail.getId());
                    setActualEndBranchId(companyDetail.getCompanyId());
                }});

                //避免后续代码对 orderRentVehicleDetail 覆盖ActualEndCompanyId  ActualEndBranchId
                orderRentVehicleDetail.setActualEndCompanyId(companyDetail.getId());
                orderRentVehicleDetail.setActualEndBranchId(companyDetail.getCompanyId());
            } 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"));
                    }
                }
            }
        }
        Double violateAmount = 0.0;
        //延期扣除费用
        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.getInteger("type") != 1) {
                        if (jsonObject.getString("cost") != null) {
                            cost += Double.parseDouble(jsonObject.getString("cost"));
                        }
                        if (jsonObject.getString("excessCost") != null) {
                            cost += Double.parseDouble(jsonObject.getString("excessCost"));
                        }
                    } else { //提前还车单独判断
                        if (jsonObject.getString("cost") != null) {
                            violateAmount += Double.parseDouble(jsonObject.getString("cost"));
                        }
                        if (jsonObject.getString("excessCost") != null) {
                            violateAmount += 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 (orderRentVehicleDetail.getGoodsDepositType() != 2) {
                //判断车辆押金是否足额
                if (orderVehicleCrosstownDto.getRestDeposit().compareTo(orderRentVehicleDetail.getVehicleDeposit()) == -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 (orderRentVehicleDetail.getGoodsDepositType() != 2) {
                //判断车辆押金是否足额
                if (orderVehicleCrosstownDto.getRestDeposit().compareTo(orderRentVehicleDetail.getVehicleDeposit()) == -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 = orderRentVehicleDetail.getVehicleDeposit();
        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, orderRentVehicleDetail.getTrafficDeposit());
                //修改订单状态为已完成
                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, orderRentVehicleDetail.getTrafficDeposit());
                //修改订单状态为定损
                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, orderRentVehicleDetail.getTrafficDeposit());
                //修改訂單狀態為已完成
                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 List<OrderVehicleCrosstown> selectOrderList(List<Integer> orderIdList, Integer type, Integer time) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderIdList", orderIdList);
        params.put("type", type);
        params.put("time", time);
        return mapper.selectOrderList(params);
    }


//    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;
    }

}
