package com.stylefeng.guns.modular.crossCity.server.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.stylefeng.guns.core.util.ToolUtil; import com.stylefeng.guns.modular.account.unionpay.GetOpenBodySig; import com.stylefeng.guns.modular.account.unionpay.QrCodeConfiguration; import com.stylefeng.guns.modular.account.unionpay.Util; import com.stylefeng.guns.modular.crossCity.dao.*; import com.stylefeng.guns.modular.crossCity.model.*; import com.stylefeng.guns.modular.crossCity.server.ILineService; import com.stylefeng.guns.modular.crossCity.server.ILineSiteService; import com.stylefeng.guns.modular.crossCity.server.IOrderCrossCityService; import com.stylefeng.guns.modular.crossCity.warpper.OrderCrossCityOnBehalfWarpper; import com.stylefeng.guns.modular.crossCity.warpper.OrderCrossCityWarpper; import com.stylefeng.guns.modular.specialTrain.dao.OrderPrivateCarMapper; import com.stylefeng.guns.modular.specialTrain.model.OrderPrivateCar; import com.stylefeng.guns.modular.system.dao.*; import com.stylefeng.guns.modular.system.model.*; import com.stylefeng.guns.modular.system.service.*; import com.stylefeng.guns.modular.system.service.impl.CarServiceImpl; import com.stylefeng.guns.modular.system.util.*; import com.stylefeng.guns.modular.system.warpper.BaseWarpper; import com.stylefeng.guns.modular.system.warpper.MerchantCouponListWarpper; import com.stylefeng.guns.modular.taxi.dao.OrderTaxiMapper; import com.stylefeng.guns.modular.taxi.model.OrderTaxi; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.util.stream.Collectors; @Service @Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public class OrderCrossCityServiceImpl extends ServiceImpl implements IOrderCrossCityService { @Resource private OrderCrossCityMapper orderCrossCityMapper; @Resource private LineShiftDriverMapper lineShiftDriverMapper; @Autowired private ILineService lineService; @Autowired private ILineSiteService lineSiteService; @Autowired private ISystemNoticeService systemNoticeService; @Autowired private PushUtil pushUtil; @Autowired private IIncomeService incomeService; @Autowired private IDriverService driverService; @Resource private UserInfoMapper userInfoMapper; @Autowired private IOpenCityService openCityService; @Autowired private DateUtil dateUtil; @Resource private LinePriceMapper linePriceMapper; @Resource private LineMapper lineMapper; @Resource private DriverSelfTripMapper driverSelfTripMapper; @Autowired private GDMapGeocodingUtil gdMapGeocodingUtil; @Autowired private GDFalconUtil gdFalconUtil; @Resource private RegionMapper regionMapper; @Autowired private ChinaMobileUtil chinaMobileUtil; @Autowired private ITransactionDetailsService transactionDetailsService; @Autowired private GDMapElectricFenceUtil gdMapElectricFenceUtil; @Autowired private IPaymentRecordService paymentRecordService; @Resource private SysIntegralMapper sysIntegralMapper; @Resource private OrderPrivateCarMapper orderPrivateCarMapper; @Resource private OrderTaxiMapper orderTaxiMapper; @Resource private PhoneMapper phoneMapper; @Autowired private IOrderPositionService orderPositionService; @Resource private MongoTemplate mongoTemplate; @Autowired private IOrderCancelService orderCancelService; @Autowired private GeodesyUtil geodesyUtil; @Autowired private PayMoneyUtil payMoneyUtil; @Autowired private CbyzxOrderPayHelper cbyzxOrderPayHelper; @Autowired private IOrderAdditionalFeeService orderAdditionalFeeService; @Resource private RedisTemplate redisTemplate; @Autowired private IMerchantActivityService merchantActivityService; @Autowired private IMerchantActivitySlaveService merchantActivitySlaveService; @Autowired private IUserMerchantCouponService userMerchantCouponService; @Autowired private IMerchantCouponService merchantCouponService; @Autowired private QrCodeConfiguration qrCodeConfiguration; @Autowired private TDriverPromotionActivityService driverPromotionActivityService; @Value("${pushMinistryOfTransport}") private boolean pushMinistryOfTransport; @Value("${callbackPath}") private String callbackPath; @Autowired private CarModelMapper carModelMapper; @Autowired private CarServiceImpl carServiceImpl; @Autowired private ICompanyService companyService; @Autowired private CarServiceMapper carServiceMapper; @Autowired private WeChatUtil weChatUtil; @Value("${filePath}") private String filePath; @Value("${qyt.admin_url}") private String adminUrl; /** * 获取司机抢单页面的订单详情 * @param orderId * @return * @throws Exception */ @Override public Map queryPushOrder(Integer orderId) throws Exception { return orderCrossCityMapper.queryPushOrder(orderId); } /** * 获取司机端首页订单列表 * @param state 1=服务中,2=待服务(30分钟定义预约) * @param driverId * @return * @throws Exception */ @Override public List> queryOrderList(Integer state, Integer driverId) throws Exception { return orderCrossCityMapper.queryOrderList(state, driverId); } /** * 获取我的订单列表数据 * @param state 1=全部,2=待支付,3=已取消 * @param uid * @return * @throws Exception */ @Override public List> queryMyAllOrder(Integer state, Integer uid) throws Exception { return orderCrossCityMapper.queryMyAllOrder(state, uid); } /** * 获取订单详情页(服务中的页面) * @param orderId * @return * @throws Exception */ @Override public Map queryOrderInfo(Integer orderId) throws Exception { Map map = new HashMap<>(); OrderCrossCity orderCrossCity = this.selectById(orderId); List> order = orderCrossCityMapper.queryOrderInfo(orderCrossCity.getOrderNum()); int num = 0; Double serverMoney = 0D; Double totalMoney = 0D; for(Map m : order){ String phone = String.valueOf(m.get("phone")); String s = phone.substring(0, 3) + "xxxx" + phone.substring(7 ); m.put("realPhone", s); if(m.get("telX")!=null){ System.out.println(111); m.put("phone",m.get("telX")); } System.out.println(m); num += Integer.valueOf(m.get("peopleNumber").toString()); totalMoney += Double.valueOf(m.get("payMoney").toString()); List incomes = incomeService.queryData(1, null, 2, Integer.valueOf(m.get("orderId").toString()), 3); for (Income income : incomes){ serverMoney += income.getMoney(); } } if (orderCrossCity.getLineId() <= -1) { LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId()); DriverSelfTrip driverSelfTrip = driverSelfTripMapper.selectById(lineShiftDriver.getCustomerId()); map.put("line", driverSelfTrip.getStartCityName() + "-" + driverSelfTrip.getEndCityName()); map.put("lineId", orderCrossCity.getLineId()); } else { Line line = lineService.selectById(orderCrossCity.getLineId()); map.put("line", line.getName()); map.put("lineId", orderCrossCity.getLineId()); } map.put("peopleNumber", num); map.put("orderNumber", orderCrossCity.getOrderNum()); map.put("totalMoney", new BigDecimal(totalMoney).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); map.put("serverMoney", new BigDecimal(serverMoney).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); OpenCity openCity = openCityService.openCity1(orderCrossCity.getStartLon().toString(), orderCrossCity.getStartLat().toString()); Phone phone = phoneMapper.queryInfo(openCity == null ? 0 : openCity.getId(), 1, 1); map.put("emergencyCall", null != phone ? phone.getPhone() : "110"); if (!order.isEmpty()){ map.put("lineShiftDriverId", order.get(0).get("lineShiftDriverId")); } map.put("orders", JSON.toJSONString(order)); System.out.println("map"+map); return map; } /** * 走订单流程操作 * @param orderId * @param state * @return * @throws Exception */ @Override public ResultUtil process(Integer orderId, Integer state, Double lon, Double lat, String address) throws Exception { OrderCrossCity orderCrossCity = this.selectById(orderId); if(10 == orderCrossCity.getState()){ return ResultUtil.error("订单已被取消,不能继续操作"); } UserInfo userInfo = userInfoMapper.selectById(orderCrossCity.getUserId()); Driver driver = driverService.selectById(orderCrossCity.getDriverId()); Company company = companyService.selectById(driver.getCompanyId()); switch (state){ case 3://出发前往预约点 orderCrossCity.setState(3); orderCrossCity.setSetOutTime(new Date()); systemNoticeService.addSystemNotice(1, "司机已出发,请耐心等待", orderCrossCity.getUserId(), 1); break; case 4://到达预约点,等待客户上车 orderCrossCity.setState(4); orderCrossCity.setArriveTime(new Date()); systemNoticeService.addSystemNotice(1, "司机已到达您设置的预约地点,请及时上车", orderCrossCity.getUserId(), 1); break; case 5://开始服务 orderCrossCity.setBoardingLon(lon); orderCrossCity.setBoardingLat(lat); orderCrossCity.setBoardingAddress(address); orderCrossCity.setBoardingTime(new Date()); orderCrossCity.setState(5); orderCrossCity.setStartServiceTime(new Date()); pushUtil.pushDriverPosition(orderCrossCity.getId(), 3);//主动推送司机定位 break; case 6://结束服务 orderCrossCity.setGetoffLon(lon); orderCrossCity.setGetoffLat(lat); orderCrossCity.setGetoffAddress(address); orderCrossCity.setGetoffTime(new Date()); orderCrossCity.setState(8);//跨城直接到待评价 orderCrossCity.setEndServiceTime(new Date()); this.updateById(orderCrossCity); //添加抽成及收入记录 //非追缴单才需要记录收入 if(0 == orderCrossCity.getRecoveryOrder()){ //添加收入 Double orderMoney = (2 == orderCrossCity.getAbnormal() && 2 == orderCrossCity.getAbnormalStatus() ? orderCrossCity.getResponsibilityMoney().doubleValue() : orderCrossCity.getOrderMoney()); Map map = incomeService.saveIncome(orderCrossCity.getId(), 3, orderMoney); orderCrossCity.setSplitAllocation(JSON.toJSONString(map)); } //待审核的异常单修改状态为已关闭 if(2 == orderCrossCity.getAbnormal() && 1 == orderCrossCity.getAbnormalStatus()){ orderCrossCity.setAbnormalStatus(3); orderCrossCity.setResponsibilityMoney(new BigDecimal(orderCrossCity.getOrderMoney())); orderCrossCity.setResponsibilityType(3); orderCrossCity.setAbnormalRemark("乘客已支付订单,申诉已自动关闭"); } //还原座位数 LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId()); if(1 == orderCrossCity.getTravelMode()){ lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() + orderCrossCity.getPeopleNumber()); }else{ Car car = carServiceImpl.selectById(driver.getCarId()); CarModel carModel = carModelMapper.selectById(car.getCarModelId()); lineShiftDriver.setLaveSeat(carModel.getSeat() - 1); } lineShiftDriver.setLaveSeatNumber( (ToolUtil.isNotEmpty(lineShiftDriver.getLaveSeatNumber()) ? lineShiftDriver.getLaveSeatNumber() + "," : "") + orderCrossCity.getSeatNumber() ); lineShiftDriverMapper.updateById(lineShiftDriver); //修改司机空闲状态 List orderCrossCities = orderCrossCityMapper.queryWithin30Minutes(orderCrossCity.getDriverId(), 2, 3, 4, 5, 11); if(orderCrossCities.size() <= 1){ driver = driverService.selectById(orderCrossCity.getDriverId()); driver.setState(2); driverService.updateById(driver); } //存储商家优惠券到redis {"phone":[{...}]} //订单数要加1,因为这里是后修改订单状态 List list = orderCrossCityMapper.queryByState(userInfo.getId(), 8, 9); List merchantActivities = merchantActivityService.selectList(new EntityWrapper().eq("companyId", orderCrossCity.getCompanyId()).eq("activityType", 1).eq("auditStatus", 2).eq("status", 1) .eq("state", 1).like("orderType", "3").where("((orderAmountFull is not null and orderAmountFull <= " + orderCrossCity.getOrderMoney() + ") or (orderNumber is not null and orderNumber <= " + (list.size() + 1) + "))") .in("id", merchantActivitySlaveService.selectList(new EntityWrapper().gt("laveNumber", 0)).stream().map(MerchantActivitySlave::getMerchantActivityId).collect(Collectors.toList())) .notIn("id", userMerchantCouponService.selectList(new EntityWrapper().eq("userType", 1).eq("userId", userInfo.getId()).eq("state", 1)).stream().map(UserMerchantCoupon::getMerchantActivityId).collect(Collectors.toList())) ); List listWarppers = new ArrayList<>(); if(merchantActivities.size() > 0){ for(MerchantActivity merchantActivity :merchantActivities){ List merchantActivitySlaves = merchantActivitySlaveService.selectList(new EntityWrapper().eq("merchantActivityId", merchantActivity.getId()).gt("laveNumber", 0)); for(MerchantActivitySlave merchantActivitySlave : merchantActivitySlaves){ UserMerchantCoupon userMerchantCoupon = new UserMerchantCoupon(); try { userMerchantCoupon.setCode(UUIDUtil.getRandomCode(16)); } catch (Exception e) { e.printStackTrace(); } userMerchantCoupon.setUserType(1); userMerchantCoupon.setUserId(userInfo.getId()); userMerchantCoupon.setMerchantActivityId(merchantActivity.getId()); userMerchantCoupon.setMerchantCouponId(merchantActivitySlave.getMerchantCouponId()); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + merchantActivity.getEffectiveDays()); userMerchantCoupon.setEndTime(calendar.getTime()); userMerchantCoupon.setStatus(1); userMerchantCoupon.setState(1); userMerchantCoupon.setCreateTime(new Date()); userMerchantCouponService.insert(userMerchantCoupon); MerchantCoupon merchantCoupon = merchantCouponService.selectById(merchantActivitySlave.getMerchantCouponId()); MerchantCouponListWarpper merchantCouponListWarpper = new MerchantCouponListWarpper(); merchantCouponListWarpper.setId(merchantActivitySlave.getMerchantCouponId()); merchantCouponListWarpper.setName(merchantCoupon.getName()); merchantCouponListWarpper.setType(merchantCoupon.getType()); merchantCouponListWarpper.setFullAmount(merchantCoupon.getFullAmount()); merchantCouponListWarpper.setDiscount(merchantCoupon.getDiscount()); listWarppers.add(merchantCouponListWarpper); merchantActivitySlave.setLaveNumber(merchantActivitySlave.getLaveNumber() - 1); if(merchantActivitySlave.getLaveNumber() == 0){ merchantActivity.setStatus(2); } } if(merchantActivitySlaves.size() > 0){ merchantActivitySlaveService.updateBatchById(merchantActivitySlaves); } } merchantActivityService.updateBatchById(merchantActivities); } String value = (String) redisTemplate.opsForValue().get("merchantVoucher"); JSONObject jsonObject = JSON.parseObject(value); if(null == jsonObject){ jsonObject = new JSONObject(); } jsonObject.put(userInfo.getPhone(), listWarppers); redisTemplate.opsForValue().set("merchantVoucher", jsonObject.toJSONString()); pushUtil.removeTask(orderId, 3);//删除定时任务,结束推送数据 systemNoticeService.addSystemNotice(1, "司机已结束本次行程,谢谢使用", orderCrossCity.getUserId(), 1); promotion(orderId); break; } this.updateById(orderCrossCity); // TODO: 2020/6/5 推送状态 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderCrossCity.getUserId(), orderCrossCity.getId(), 3, orderCrossCity.getState()); pushUtil.pushOrderState(2, orderCrossCity.getDriverId(), orderCrossCity.getId(), 3, orderCrossCity.getState()); } }).start(); return ResultUtil.success(); } public void promotion(Integer orderId) { OrderCrossCity orderCrossCity = this.baseMapper.selectById(orderId); UserInfo userInfo = userInfoMapper.selectById(orderCrossCity.getUserId()); if(orderCrossCity.getPromotionDriverId()!=null ){ String registAreaCode = userInfo.getRegistAreaCode(); TDriverPromotionActivity tDriverPromotionActivity = driverPromotionActivityService.selectOne(new EntityWrapper().eq("districtCode", registAreaCode).le("startTime", new Date()).ge("endTime", new Date()).last("AND FIND_IN_SET(" + 3 + ", bizType) limit 1")); System.out.println("ddddd"+tDriverPromotionActivity); if(tDriverPromotionActivity!=null){ Double payMoney = orderCrossCity.getPayMoney(); System.out.println(payMoney); BigDecimal bigDecimal = tDriverPromotionActivity.getCommissionRatio().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(payMoney)).setScale(2, RoundingMode.HALF_UP); System.out.println(bigDecimal); orderCrossCity.setPromotionDriverId(userInfo.getBindDriverId()); orderCrossCity.setPromotionMoney(bigDecimal); orderCrossCity.setPromotionActivityId(tDriverPromotionActivity.getId()); orderCrossCity.setSuccessTime(new Date()); this.baseMapper.updateById(orderCrossCity); } } } /** * 获取订单明细 * @param orderId * @return * @throws Exception */ @Override public Map queryOrderCrossCityInfo(Integer orderId) throws Exception { return orderCrossCityMapper.queryOrderCrossCityInfo(orderId); } /** * 修改订单顺序 * @param orderId * @throws Exception */ @Override public void setOrderCrossCitySort(Integer orderId) throws Exception { OrderCrossCity orderCrossCity = this.selectById(orderId); List orderCrossCities = orderCrossCityMapper.selectList(new EntityWrapper().eq("orderNum", orderCrossCity.getOrderNum()).ne("state", 10).orderBy("sort")); for(int i = 0; i < orderCrossCities.size(); i++){ if(orderCrossCities.get(i).getId().compareTo(orderId) == 0){ if(i == 0){ break; } OrderCrossCity orderCrossCity2 = orderCrossCities.get(i); Integer sort = orderCrossCity2.getSort(); OrderCrossCity orderCrossCity1 = orderCrossCities.get(i - 1); orderCrossCity2.setSort(orderCrossCity1.getSort()); orderCrossCity1.setSort(sort); orderCrossCityMapper.updateById(orderCrossCity2); orderCrossCityMapper.updateById(orderCrossCity1); break; } } } /** * 跨城下单操作 * @param orderCrossCityWarpper * @param uid * @return * @throws Exception */ @Override public synchronized ResultUtil orderCrossCity(OrderCrossCityWarpper orderCrossCityWarpper, Integer uid) throws Exception { /** * 先判断司机座位数是否符合出行人数 */ LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCityWarpper.getLineShiftDriverId()); if(orderCrossCityWarpper.getTravelMode() == 1){ if(lineShiftDriver.getLaveSeat() < orderCrossCityWarpper.getPeopleNumber()){ return ResultUtil.error("司机剩余座位数小于出行人数"); } }else{ if(lineShiftDriver.getLaveSeat() != lineShiftDriver.getTotalSeat()){ return ResultUtil.error("司机车辆上已经有人占座了,不能下包车订单"); } if(lineShiftDriver.getLaveSeat() == 0){ return ResultUtil.error("司机剩余座位数不足"); } } Driver driver = driverService.selectById(orderCrossCityWarpper.getDriverId()); if(driver.getState() == 1){ return ResultUtil.error("司机处于离线状态"); } OrderCrossCity orderCrossCity = new OrderCrossCity(); String phone = orderCrossCityWarpper.getPassengersPhone(); UserInfo userInfo = userInfoMapper.queryByPhone(phone); if(userInfo == null){//添加用户信息 Integer integer = userInfoMapper.selectCount(null) + 1000001; String nickName = ToolUtil.isNotEmpty(orderCrossCityWarpper.getPassengers()) ? orderCrossCityWarpper.getPassengers() : "GRJY" + String.valueOf(integer).substring(1); userInfo = new UserInfo(); userInfo.setNickName(nickName); userInfo.setName(orderCrossCityWarpper.getPassengers()); userInfo.setPhone(orderCrossCityWarpper.getPassengersPhone()); userInfo.setState(1); userInfo.setFlag(1); userInfo.setInsertTime(new Date()); userInfo.setInsertUser(uid); userInfoMapper.insert(userInfo); } orderCrossCity.setUserId(userInfo.getId()); /** * 1.出租车、专车、跨城有待支付的订单不能叫车 * 2.小件物流有未完成的订单可以下跨城、专车、出租车 * 3.出租车、专车、跨城有预约单可以下即时单 */ List orderPrivateCars = orderPrivateCarMapper.queryByState(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12); if(orderPrivateCars.size() > 0){ return ResultUtil.error("有未完成的订单"); } List list = orderTaxiMapper.queryByState_(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12); if(list.size() > 0){ return ResultUtil.error("有未完成的订单"); } List orderCrossCities1 = orderCrossCityMapper.queryByState(userInfo.getId(), 1, 2, 3, 4, 5, 6, 7, 11, 12); if(orderCrossCities1.size() > 0){ return ResultUtil.error("有未完成的订单"); } List orderCrossCities2 = orderCrossCityMapper.queryOrders(orderCrossCityWarpper.getDriverId(), orderCrossCityWarpper.getLineShiftDriverId(), Arrays.asList(5)); if(orderCrossCities2.size() > 0){ return ResultUtil.error("司机正在服务中"); } orderCrossCity.setPassengers(orderCrossCityWarpper.getPassengers()); orderCrossCity.setPassengersPhone(orderCrossCityWarpper.getPassengersPhone()); orderCrossCity.setServerCarModelId(orderCrossCityWarpper.getServerCarModelId()); orderCrossCity.setDriverId(orderCrossCityWarpper.getDriverId()); orderCrossCity.setLineId(orderCrossCityWarpper.getLineId()); orderCrossCity.setCarId(orderCrossCityWarpper.getCarId()); orderCrossCity.setOrderNum(this.getOrderNum(orderCrossCityWarpper.getDriverId(), orderCrossCityWarpper.getLineShiftDriverId())); orderCrossCity.setPlacementLon(orderCrossCityWarpper.getPlacementLon()); orderCrossCity.setPlacementLat(orderCrossCityWarpper.getPlacementLat()); String placementAddress = orderCrossCityWarpper.getPlacementAddress(); placementAddress = placementAddress.replaceAll("& #40;", "("); placementAddress = placementAddress.replaceAll("& #41;", ")"); orderCrossCity.setPlacementAddress(placementAddress); orderCrossCity.setStartLon(orderCrossCityWarpper.getStartLon()); orderCrossCity.setStartLat(orderCrossCityWarpper.getStartLat()); String startAddress = orderCrossCityWarpper.getStartAddress(); startAddress = startAddress.replaceAll("& #40;", "("); startAddress = startAddress.replaceAll("& #41;", ")"); orderCrossCity.setStartAddress(startAddress); orderCrossCity.setEndLon(orderCrossCityWarpper.getEndLon()); orderCrossCity.setEndLat(orderCrossCityWarpper.getEndLat()); String endAddress = orderCrossCityWarpper.getEndAddress(); endAddress = endAddress.replaceAll("& #40;", "("); endAddress = endAddress.replaceAll("& #41;", ")"); orderCrossCity.setEndAddress(endAddress); orderCrossCity.setMileage(0D); ResultUtil> price = this.getPriceV2(orderCrossCityWarpper.getLineId(), null, orderCrossCityWarpper.getTotalSeat(), orderCrossCityWarpper.getPeopleNumber(), orderCrossCityWarpper.getEndLon(), orderCrossCityWarpper.getEndLat(), orderCrossCityWarpper.getLineShiftDriverId()); if (price.getCode() != 200) { return ResultUtil.error("计算价格失败"); } Double money = Double.valueOf(price.getData().get("price").toString()); if (money < 0) { return ResultUtil.error("计算价格失败"); } orderCrossCity.setOrderMoney(money); Integer companyId = driver.getCompanyId(); orderCrossCity.setCompanyId(companyId); orderCrossCity.setPeopleNumber(orderCrossCityWarpper.getPeopleNumber()); orderCrossCity.setSeatNumber(orderCrossCityWarpper.getSeatNumber()); List orderCrossCities = this.selectList(new EntityWrapper().eq("orderNum", orderCrossCity.getOrderNum()).eq("isDelete", 1)); orderCrossCity.setSort(orderCrossCities.size() + 1); orderCrossCity.setState(7);//待支付 orderCrossCity.setInsertTime(new Date()); orderCrossCity.setTravelTime(orderCrossCityWarpper.getTravelTime()); orderCrossCity.setSnatchOrderTime(new Date()); orderCrossCity.setTravelMode(orderCrossCityWarpper.getTravelMode()); orderCrossCity.setIsDelete(1); orderCrossCity.setIsReassign(1); orderCrossCity.setLineShiftDriverId(orderCrossCityWarpper.getLineShiftDriverId()); //调用高德创建轨迹 // String s = gdFalconUtil.selectTerminal(driver.getPhone()); // String track = gdFalconUtil.createTrack(s); // orderCrossCity.setTrackId(track); //调用移动的小号接口 // Map map = chinaMobileUtil.midAxbBindSend(orderCrossCity.getPassengersPhone(), driver.getPhone(), (System.currentTimeMillis() + 86400000)); // if(String.valueOf(map.get("code")).equals("200")){ // orderCrossCity.setTelX(map.get("telX")); // orderCrossCity.setBindId(map.get("bindId")); // } if(orderCrossCityWarpper.getTravelMode() == 2){//包车 // orderCrossCity.setSeatNumber(lineShiftDriver.getLaveSeatNumber()); // orderCrossCity.setPeopleNumber(lineShiftDriver.getLaveSeat()); } orderCrossCity.setOrderSource(4); this.insert(orderCrossCity); Double t = 0D; if(ToolUtil.isNotEmpty(orderCrossCityWarpper.getAdditionalFee())){//附加费 JSONArray jsonArray = JSON.parseArray(orderCrossCityWarpper.getAdditionalFee()); for(int i = 0; i < jsonArray.size(); i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); Integer id = jsonObject.getInteger("id"); Double amount = jsonObject.getDouble("amount"); OrderAdditionalFee orderAdditionalFee = new OrderAdditionalFee(); orderAdditionalFee.setOrderType(3); orderAdditionalFee.setOrderId(orderCrossCity.getId()); orderAdditionalFee.setAdditionalFeeId(id); orderAdditionalFee.setAmount(amount); orderAdditionalFeeService.insert(orderAdditionalFee); t += amount; } } orderCrossCity.setOrderMoney(orderCrossCity.getOrderMoney() + t); this.updateById(orderCrossCity); if(driver.getState() == 2){ driver.setState(3); driverService.updateById(driver); } //修改预约班次的数据 if(orderCrossCity.getTravelMode() == 2){//包车 lineShiftDriver.setLaveSeat(0); lineShiftDriver.setLaveSeatNumber(""); }else{//拼车 lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() - orderCrossCity.getPeopleNumber()); String[] split1 = lineShiftDriver.getLaveSeatNumber().split(","); if (StringUtils.isNotEmpty(orderCrossCity.getSeatNumber())){ // 用户已选座的情况 String[] split = orderCrossCity.getSeatNumber().split(","); String seatNumber = ""; //先判断选中座位号和剩余座位号是否匹配 for(String spl : split){ boolean b = true; for(String sp : split1){ if(ToolUtil.isNotEmpty(spl) && ToolUtil.isNotEmpty(sp) && sp.equals(spl)){ b = false; break; } } if(b){ throw new SystemException("您选中的" + spl + "号座位已被占用,请选择其他座位!"); } } for(String sp : split1){ boolean b = true; for(String spl : split){ if(ToolUtil.isNotEmpty(spl) && ToolUtil.isNotEmpty(sp) && sp.equals(spl)){ b = false; break; } } if(b && ToolUtil.isNotEmpty(sp)){ seatNumber += (sp + ","); } } lineShiftDriver.setLaveSeatNumber(ToolUtil.isNotEmpty(seatNumber) ? seatNumber.substring(0, seatNumber.length() - 1) : ""); } else { // 用户未选座的情况,自动分配剩余座位的前peopleNumber个 StringBuilder assignedSeats = new StringBuilder(); StringBuilder remainingSeats = new StringBuilder(); for(int i = 0; i < split1.length; i++){ if(ToolUtil.isEmpty(split1[i])){ continue; } if(i < orderCrossCity.getPeopleNumber()){ // 分配给当前订单的座位 if(assignedSeats.length() > 0){ assignedSeats.append(","); } assignedSeats.append(split1[i]); } else { // 剩余的座位 if(remainingSeats.length() > 0){ remainingSeats.append(","); } remainingSeats.append(split1[i]); } } // 设置订单的座位号 orderCrossCity.setSeatNumber(assignedSeats.toString()); this.updateById(orderCrossCity); // 更新班次的剩余座位号 lineShiftDriver.setLaveSeatNumber(remainingSeats.toString()); } } lineShiftDriverMapper.updateById(lineShiftDriver); //添加消息 systemNoticeService.addSystemNotice(1, "您的跨城订单已下单成功!", orderCrossCity.getUserId(), 1); BaseWarpper baseWarpper = new BaseWarpper(); baseWarpper.setId(orderCrossCity.getId()); baseWarpper.setContent(""); //生成小程序二维码,用于司机展示让用户跳转到小程序完成订单支付 // String appletPath = "pages/home/home"; // InputStream inputStream = weChatUtil.getwxacodeunlimit(appletPath, "driver_places", "release"); // if (inputStream != null) { // File file = FileUtil.writeFromStream(inputStream, new File(filePath + "/" + UUID.randomUUID().toString() + ".png")); // HttpRequest post = HttpUtil.createPost(adminUrl + "/upload/image"); // post.form("file", file); // HttpResponse execute = post.execute(); // int status = execute.getStatus(); // if(200 != status){ // throw new RuntimeException("上传图片异常"); // } // JSONObject jsonObject = JSON.parseObject(execute.body()); // Integer code = jsonObject.getInteger("code"); // if(200 == code){ // baseWarpper.setContent(jsonObject.getString("data")); // System.err.println(jsonObject.getString("data")); // } // } //创建定时任务,取消订单30分钟 TimerTask timerTask = new TimerTask() { @Override public void run() { OrderCrossCity orderCrossCity1 = orderCrossCityMapper.selectById(orderCrossCity.getId()); if(orderCrossCity1.getState() == 7 && orderCrossCity1.getPayMoney() == null){ orderCrossCity1.setState(10); orderCrossCityMapper.updateById(orderCrossCity1); OrderCancel orderCancel = new OrderCancel(); orderCancel.setOrderId(orderCrossCity.getId()); orderCancel.setOrderType(3); orderCancel.setReason("用户未及时付款,系统自动取消订单"); orderCancel.setRemark("用户未及时付款,系统自动取消订单"); orderCancel.setState(2); orderCancel.setInsertTime(new Date()); orderCancel.setUserType(2); orderCancelService.insert(orderCancel); //修改司机座位 LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId()); lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() + orderCrossCity.getPeopleNumber()); lineShiftDriver.setLaveSeatNumber(lineShiftDriver.getLaveSeatNumber() + (orderCrossCity.getTravelMode() == 1 ? "," : "") + orderCrossCity.getSeatNumber()); lineShiftDriverMapper.updateById(lineShiftDriver); //修改司机为空闲 List orderCrossCities = orderCrossCityMapper.queryByDriverId(orderCrossCity.getDriverId(), 2, 3, 4, 5, 11); if(orderCrossCities.size() == 0){ Driver driver = driverService.selectById(orderCrossCity.getDriverId()); driver.setState(2); driverService.updateById(driver); } } } }; Timer timer = new Timer(); timer.schedule(timerTask, 30 * 60 * 1000); return ResultUtil.success(baseWarpper); } /** * 扫码支付回调处理 * @param orderId 订单id * @param order_id 工行订单号 * @throws Exception */ @Override public void generatePayCallback(Integer orderId, String order_id) throws Exception { OrderCrossCity orderCrossCity = orderCrossCityMapper.selectById(orderId); orderCrossCity.setPayManner(1); orderCrossCity.setPayMoney(orderCrossCity.getOrderMoney()); orderCrossCity.setState(2); orderCrossCity.setPayTime(new Date()); orderCrossCityMapper.updateById(orderCrossCity); paymentRecordService.saveData(1, orderCrossCity.getDriverId(), orderCrossCity.getPayType(), orderId, 3, 2, orderCrossCity.getPayMoney(), order_id, 2);//添加预支付数据 //添加交易明细 transactionDetailsService.saveData(orderCrossCity.getUserId(), "订单完成支付", orderCrossCity.getOrderMoney(), 2, 1, 1, 3, orderId); //添加已收入明细 // Line line = lineService.selectById(orderCrossCity.getLineId()); // Double speMoney = Double.valueOf(line.getRakeRate()); // BigDecimal d = new BigDecimal(orderCrossCity.getOrderMoney()).multiply(new BigDecimal(speMoney).divide(new BigDecimal(100)), new MathContext(2, RoundingMode.HALF_EVEN));//企业收入 // BigDecimal c = new BigDecimal(orderCrossCity.getOrderMoney()).subtract(d).setScale(2, BigDecimal.ROUND_HALF_EVEN);//司机收入 // incomeService.saveData(1, orderCrossCity.getCompanyId(), 2, orderCrossCity.getId(), 1, d.doubleValue()); // incomeService.saveData(2, orderCrossCity.getDriverId(), 2, orderCrossCity.getId(), 1, c.doubleValue()); // Driver driver = driverService.selectById(orderCrossCity.getDriverId()); // driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); // driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); // driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); // driverService.updateById(driver); // TODO: 2020/5/24 这里需要给司机和用户推送订单状态 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderCrossCity.getUserId(), orderCrossCity.getId(), 3, orderCrossCity.getState()); pushUtil.pushOrderState(2, orderCrossCity.getDriverId(), orderCrossCity.getId(), 3, orderCrossCity.getState()); pushUtil.pushDriverPosition(orderCrossCity.getId(), 3); } }).start(); systemNoticeService.addSystemNotice(1, "您已成功完成出行订单支付,谢谢使用!", orderCrossCity.getUserId(), 1); } /** * 计算支付金额 * @param startLonLat * @param endLonLat * @param peopleNumber * @param travelMode * @param lineId * @param serverCarModelId * @return * @throws Exception */ @Override public ResultUtil queryOrderMoney(String startLonLat, String endLonLat, Integer peopleNumber, Integer travelMode, Integer lineId, Integer serverCarModelId, Integer totalSeat, String seatNumber) throws Exception { Double endLon = null; Double endLat = null; if (ToolUtil.isNotEmpty(endLonLat) && endLonLat.contains(",")) { String[] endArr = endLonLat.split(","); if (endArr.length == 2) { endLon = Double.valueOf(endArr[0]); endLat = Double.valueOf(endArr[1]); } } ResultUtil> result = this.getPriceV2(lineId, null, totalSeat, peopleNumber, endLon, endLat, null); if (result.getCode() != 200) { return result; } Double price = Double.valueOf(String.valueOf(result.getData().get("price"))); if (price < 0) { return ResultUtil.error("计算行程距离出错啦!"); } return result; } /** * 订单支付 * @param payType * @param orderId * @param couponId * @param type * @return * @throws Exception */ @Override public ResultUtil payCrossCityOrder(Integer payType, Integer orderId, Integer couponId, Integer type) throws Exception { OrderCrossCity orderCrossCity = this.selectById(orderId); if(orderCrossCity.getState() != 7){ return ResultUtil.error("订单已被支付,不允许重复支付"); } Integer uid = orderCrossCity.getUserId(); Double orderMoney = orderCrossCity.getOrderMoney(); ResultUtil resultUtil = ResultUtil.success(""); orderCrossCity.setCouponMoney(0D);//初始化历史数据 orderCrossCity.setCouponId(null); if(payType == 1){//微信支付 String out_trade_no = buildCbyzxCrossCityOutTradeNo(orderId); Driver driver = driverService.selectById(orderCrossCity.getDriverId()); if(null == driver || ToolUtil.isEmpty(driver.getAppletsOpenId())){ return ResultUtil.errorOpenId("司机未绑定微信小程序openid,无法发起微信支付"); } JSONObject response = cbyzxOrderPayHelper.createOrder(orderCrossCity.getDriverId(), driver.getAppletsOpenId(), out_trade_no, orderMoney); if(!cbyzxOrderPayHelper.isCreateSuccess(response)){ return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response); } resultUtil = ResultUtil.success(response); paymentRecordService.saveData(1, orderCrossCity.getDriverId(), 2, orderId, 3, 1, orderMoney, out_trade_no, 1);//添加预支付数据 } if(payType == 2){//支付宝支付 String out_trade_no = orderId + "_3_" + UUIDUtil.getRandomCode(5); resultUtil = payMoneyUtil.alipay("完成订单", "完成订单", "", out_trade_no, orderMoney.toString(), "/base/aliPayCrossCity"); paymentRecordService.saveData(1, orderCrossCity.getDriverId(), 2, orderId, 3, 2, orderMoney, "", 1);//添加预支付数据 } if(payType == 4){ // TODO 司机云闪付 跨城下单调起云闪付 Double payMoney = orderCrossCity.getOrderMoney(); paymentRecordService.saveData(1, orderCrossCity.getDriverId(), 2, orderId, 3, 4, orderMoney, "", 1);//添加预支付数据 resultUtil = placeAnOrder(new BigDecimal(payMoney), 4,3,orderId); } this.updateAllColumnById(orderCrossCity); return resultUtil; } /** * 创博优完成订单支付回调单号,增加业务前缀避免与改派支付共用回调地址时串单。 */ private String buildCbyzxCrossCityOutTradeNo(Integer orderId) throws Exception { return "crossCity_" + orderId + "_3_" + UUIDUtil.getRandomCode(5); } private ResultUtil placeAnOrder(BigDecimal amount, Integer type, Integer orderType, Integer orderId) throws Exception { JSONObject json = new JSONObject(); json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")); // 报文请求时间 json.put("merOrderId", Util.getMerOrderId(qrCodeConfiguration.getMsgSrcId())); // 商户订单号 json.put("mid", qrCodeConfiguration.getMid()); // 商户号 json.put("tid", qrCodeConfiguration.getTid()); // 终端号 json.put("instMid", qrCodeConfiguration.getInstMid()); // 业务类型 json.put("totalAmount", amount.multiply(new BigDecimal("100")).intValue()); // 支付总金额 json.put("orderDesc", "APP下单"); // 订单描述 json.put("srcReserve", orderId+"-"+orderType+"-"+type); // 预留字段 json.put("subAppId", "wxasdasdasdasdads"); json.put("notifyUrl", "https://zhentonggongsi.com:443/driver/api/placeOrder/notifyUrl"); json.put("tradeType", "APP"); // 交易类型,微信必传 // json.put("divisionFlag", true); // 分账标记 // json.put("platformAmount", 0); // 平台商户分账金额 // ArrayList subOrders = new ArrayList<>(); // JSONObject jsonObject = new JSONObject(); // jsonObject.put("mid", "988460101800201"); // jsonObject.put("totalAmount", 1); // subOrders.add(jsonObject); // json.put("subOrders", subOrders); System.err.println("请求报文json:\n" + json); String url; if(1 == type){ // url = "https://test-api-open.chinaums.com/v1/netpay/wx/app-pre-order";// 测试 url = "https://api-mop.chinaums.com/v1/netpay/wx/app-pre-order"; }else if (2 == type){ // url = "https://test-api-open.chinaums.com/v1/netpay/trade/precreate";// 测试 url = "https://api-mop.chinaums.com/v1/netpay/trade/precreate"; }else { // url = "https://test-api-open.chinaums.com/v1/netpay/uac/app-order";// 测试 url = "https://api-mop.chinaums.com/v1/netpay/uac/app-order"; } //OPEN-BODY-SIG 方式 String result = GetOpenBodySig.sendOpenBodySig(qrCodeConfiguration.getAppId(),qrCodeConfiguration.getAppKey(),url, json.toString()); System.err.println("响应报文json:\n" + result); JSONObject jsonObject = JSONObject.parseObject(result); Object appPayRequest = jsonObject.get("appPayRequest"); System.out.println(appPayRequest); return ResultUtil.success(appPayRequest); } /** * 支付成功后的回调操作 * @param id 订单=id * @param order_id 工行支付单号 * @param type 1=微信,2=支付宝 3=扫码支付 4=云闪付 * @throws Exception */ @Override public void payOrderCrossCityCallback(Integer id, String order_id, Integer type) throws Exception { OrderCrossCity orderCrossCity = this.selectById(id); System.out.println("跨城订单========================"+orderCrossCity); PaymentRecord query = paymentRecordService.query(1, orderCrossCity.getDriverId(), 2, id, 3, type, 1); System.out.println("================================="+query); if(null != query && query.getState() == 1){ System.out.println("================================="+query); try { //添加交易明细 transactionDetailsService.saveData(orderCrossCity.getUserId(), "跨城出行订单", query.getAmount(), 2, 1, 1, 3, query.getOrderId()); orderCrossCity.setState(2);//先支付再服务 orderCrossCity.setPayType(type); orderCrossCity.setPayMoney(query.getAmount()); this.updateById(orderCrossCity); System.out.println("==============orderCrossCity修改完毕==================="+orderCrossCity); UserInfo userInfo = userInfoMapper.selectById(orderCrossCity.getUserId()); OpenCity openCity = openCityService.openCity1(orderCrossCity.getStartLon().toString(), orderCrossCity.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); userInfo.setIntegral(userInfo.getIntegral() + (query.getAmount().intValue() * query1.getIntegral()));//积分 userInfoMapper.updateById(userInfo); System.out.println("==============userInfo修改完毕==================="+userInfo); query.setState(2); query.setCode(order_id); paymentRecordService.updateById(query); System.out.println("==============PaymentRecord修改完毕==================="+query); //添加已收入明细 // TODO: 2022/3/19 抽成按照订单金额计算,优先保证司机的收入,用户支付金额不够,则在平台收入中补贴司机收入 //例如:订单金额10元,优惠3元,司机收入比例80%,平台收入比例20%。 //司机收入:10 * 0.8 = 8 //平台收入:7 - 8 = -1 // Line line = lineService.selectById(orderCrossCity.getLineId()); // Double speMoney = Double.valueOf(line.getRakeRate()); // BigDecimal c = new BigDecimal(orderCrossCity.getOrderMoney()).multiply(new BigDecimal(1 - (speMoney / 100))).setScale(2, BigDecimal.ROUND_HALF_EVEN);//司机收入 // BigDecimal d = new BigDecimal(orderCrossCity.getPayMoney()).subtract(c).setScale(2, BigDecimal.ROUND_HALF_EVEN);//企业收入 // incomeService.saveData(1, orderCrossCity.getCompanyId(), 2, orderCrossCity.getId(), 3, d.doubleValue()); // incomeService.saveData(2, orderCrossCity.getDriverId(), 2, orderCrossCity.getId(), 3, c.doubleValue()); // System.out.println("==============incomeService修改完毕==================="); // Driver driver = driverService.selectById(orderCrossCity.getDriverId()); // driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); // driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); // driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(c).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); // driverService.updateById(driver); // System.out.println("==============driver修改完毕==================="+driver); // TODO: 2020/5/24 这里需要给司机和用户推送订单状态 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderCrossCity.getUserId(), orderCrossCity.getId(), 3, orderCrossCity.getState()); pushUtil.pushOrderState(2, orderCrossCity.getDriverId(), orderCrossCity.getId(), 3, orderCrossCity.getState()); pushUtil.pushDriverPosition(orderCrossCity.getId(), 3); } }).start(); systemNoticeService.addSystemNotice(1, "您已使用" + (type == 1 ? "微信" :(type == 2) ?"支付宝":(type == 3)?"扫码支付":"云闪付") + "成功完成出行订单支付,谢谢使用!", orderCrossCity.getUserId(), 1); System.out.println("==============跨城订单修改完毕==================="); }catch (Exception e){ System.out.println("报错信息==============="+e.getMessage()); e.printStackTrace(); } }else{ System.err.println("预支付数据异常(orderId = " + id + ")"); } } @Override public boolean calculateMileage(OrderPosition orderPosition) throws Exception { Integer orderId = orderPosition.getOrderId(); String lon = orderPosition.getLon(); String lat = orderPosition.getLat(); OrderCrossCity order = this.selectById(orderId); if(null == order){ System.err.println("跨城订单数据异常:" + orderId); return false; } //跨城记录所有服务完成之前的订单服务距离 List orderCrossCities = this.selectList(new EntityWrapper().eq("orderNum", order.getOrderNum()).eq("isDelete", 1).in("state", Arrays.asList(2, 3, 4, 5))); for(OrderCrossCity orderCrossCity : orderCrossCities){ boolean b = false; OrderPosition orderPosition1 = orderPositionService.queryNew(orderCrossCity.getId(), 3); if(null != orderPosition1){ String now = lon + "," + lat; String old = orderPosition1.getLon() + "," + orderPosition1.getLat(); Map distance = geodesyUtil.getDistance(now, old); if(null != distance){ Double distance1 = distance.get("WGS84"); if(Double.valueOf(distance1) > 50 && orderCrossCity.getState() == 5){//大于50米表示在移动 orderCrossCity.setMileage(new BigDecimal(orderCrossCity.getMileage()).add(new BigDecimal(distance1)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); this.updateById(orderCrossCity); b = true; } }else{ System.err.println("调用高德计算距离出错"); } }else{ orderCrossCity.setMileage(0D); this.updateById(orderCrossCity); b = true;//第一条数据不作处理,直接存储 } if(b){ //先计算里程,在存储最新位置 orderPosition.setInsertTime(new Date()); mongoTemplate.save(orderPosition); } } return false;//上层不需要处理 } @Override public List queryListOrder(Integer driverId, Integer lineShiftId, List state, String day) throws Exception { return orderCrossCityMapper.queryListOrder(driverId, lineShiftId, state, day); } /** * 获取所有快到期的预约单(出行时间在30分钟内) * @return * @throws Exception */ @Override public List queryMaturity() throws Exception { return orderCrossCityMapper.queryMaturity(); } /** * 计算价格 * @param distance * @param peopleNumber * @param travelMode * @param lineId * @param serverCarModelId * @param totalSeat * @param seatNumber * @return */ public ResultUtil> getPrice(Double distance, Integer peopleNumber, Integer travelMode, Integer lineId, Integer serverCarModelId, Integer totalSeat, String seatNumber){ if(0 >= peopleNumber && peopleNumber > 6){ return ResultUtil.error("请输入正确的乘车人数"); } Map map = new HashMap<>(); double distance1 = distance.doubleValue() / 1000;//公里 map.put("distance", distance); /** * 1.固定价格的包车是整车价格 * 2.五座车和七座车的优惠系数是中间特殊位置的优惠折扣 * 3.包车的情况不享受中间特殊位置的优惠折扣 * 4.浮动计费拼车如果选中中间特殊位置既享受优惠系数又享受中间特殊位置的优惠折扣 */ Map query = linePriceMapper.query(lineId, serverCarModelId); if(null == query){ map.put("distance", 0); map.put("price", 0); return ResultUtil.success(map); } String content = query.get("content").toString(); JSONObject jsonObject = JSON.parseObject(content); if(Integer.valueOf(query.get("type").toString()) == 1){//固定金额 double num1 = Double.valueOf(jsonObject.getString("num1")).doubleValue(); double num2 = Double.valueOf(jsonObject.getString("num2")).doubleValue(); double num3 = Double.valueOf(jsonObject.getString("num3")).doubleValue(); double num4 = Double.valueOf(jsonObject.getString("num4")).doubleValue(); if(travelMode == 1){//拼车 String[] split = seatNumber.split(","); boolean b = false; for(String s : split){ if((totalSeat == 4 && s.equals("3")) || (totalSeat == 6 && s.equals("5"))){ b = true; break; } } double price1 = 0D; if(b){ price1 = num1 * (totalSeat == 4 ? num3 : num4); peopleNumber -= 1; } double price = (num1 * peopleNumber) + price1; map.put("price", new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); }else{ map.put("price", num2);//包车价 } }else{//浮动计费 //计算公式:实际历程 * 基础单价 * (参考费用 / (参考里程 * 基础单价)) + (实际历程 - 参考里程) * 基础单价 * 优惠系数 double num1 = Double.valueOf(jsonObject.getString("num1")).doubleValue();//参考价格 double num2 = Double.valueOf(jsonObject.getString("num2")).doubleValue();//参考里程 double num3 = Double.valueOf(jsonObject.getString("num3")).doubleValue();//保底价 double num4 = Double.valueOf(jsonObject.getString("num4")).doubleValue();//超出参考里程优惠系数 double num5 = Double.valueOf(jsonObject.getString("num5")).doubleValue();//低于参考里程优惠系数 double num6 = Double.valueOf(jsonObject.getString("num6")).doubleValue();//包车系数 double num7 = Double.valueOf(jsonObject.getString("num7")).doubleValue();//五座系数 double num8 = Double.valueOf(jsonObject.getString("num8")).doubleValue();//七座系数 /** * 1、实际里程>=参考里程 * 参考价+((实际里程-参考里程)*(参考价/参考里程)*超出参考里程优惠系数) * * 2、实际里程<参考里程 * 参考价-(参考里程-实际路程)*(参考价/参考里程)*低于参考里程优惠系数 */ double unitPrice = 0d; if(distance1 > num2){//1 unitPrice = num1 + ((distance1 - num2) * (num1 / num2) * num4); } if(distance1 < num2){//2 unitPrice = num1 - ((num2 - distance1) * (num1 / num2) * num5); } if(distance1 == num2){ unitPrice = num1; } if(travelMode == 1){//拼车 String[] split = seatNumber.split(","); boolean b = false; for(String s : split){ if((totalSeat == 4 && s.equals("3")) || (totalSeat == 6 && s.equals("5"))){ b = true; break; } } double price1 = 0D; if(b){ price1 = unitPrice * (totalSeat == 4 ? num7 : num8); peopleNumber -= 1; } double price = (unitPrice * peopleNumber) + price1; map.put("price", new BigDecimal(num3 > price ? num3 : price).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); }else{ double price = unitPrice * totalSeat * num6; map.put("price", new BigDecimal(num3 > price ? num3 : price).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); } } return ResultUtil.success(map); } public ResultUtil> getPriceV2(Integer lineId, LineShiftDriver lineShiftDriver, Double endLon, Double endLat, Integer peopleNumber) { Map map = new HashMap<>(); map.put("distance", 0); if (lineShiftDriver == null || endLon == null || endLat == null || peopleNumber == null || peopleNumber <= 0) { map.put("price", -1); return ResultUtil.success(map); } if (lineId != null && lineId <= -1) { BigDecimal price = querySelfTripNearestPrice(lineShiftDriver, endLon, endLat); map.put("price", price == null ? -1 : multiplyPeopleNumber(price, peopleNumber).doubleValue()); return ResultUtil.success(map); } BigDecimal price = queryLineDestinationPrice(lineId, lineShiftDriver, endLon, endLat); map.put("price", price == null ? -1 : multiplyPeopleNumber(price, peopleNumber).doubleValue()); return ResultUtil.success(map); } public ResultUtil> getPriceV2(Integer lineId, Integer lineDestinationId, Integer totalSeat, Integer peopleNumber, Double endLon, Double endLat, Integer lineShiftDriverId) { Map map = new HashMap<>(); map.put("distance", 0); if (peopleNumber == null || peopleNumber <= 0 || endLon == null || endLat == null) { map.put("price", -1); return ResultUtil.success(map); } if (lineDestinationId != null) { Map destination = lineMapper.queryLineDestinationById(lineDestinationId, lineId); BigDecimal unitPrice = null; if (destination != null) { unitPrice = totalSeat != null && totalSeat == 6 ? getBigDecimal(destination.get("price7")) : getBigDecimal(destination.get("price5")); if (unitPrice == null) { unitPrice = getBigDecimal(destination.get("price5")); } } map.put("price", unitPrice == null ? -1 : multiplyPeopleNumber(unitPrice, peopleNumber).doubleValue()); return ResultUtil.success(map); } if (lineId != null && lineId <= -1) { if (lineShiftDriverId == null) { map.put("price", -1); return ResultUtil.success(map); } LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(lineShiftDriverId); if (lineShiftDriver == null) { map.put("price", -1); return ResultUtil.success(map); } return getPriceV2(lineId, lineShiftDriver, endLon, endLat, peopleNumber); } List> destinations = lineMapper.queryLineDestinations(lineId); if (destinations == null || destinations.size() == 0) { map.put("price", -1); return ResultUtil.success(map); } BigDecimal defaultPrice5 = getBigDecimal(destinations.get(0).get("price5")); BigDecimal matchedPrice = null; for (Map destination : destinations) { if (isPointInDestinationFence(destination, endLon, endLat)) { matchedPrice = totalSeat != null && totalSeat == 6 ? getBigDecimal(destination.get("price7")) : getBigDecimal(destination.get("price5")); if (matchedPrice == null) { matchedPrice = getBigDecimal(destination.get("price5")); } break; } } BigDecimal finalPrice = matchedPrice == null ? defaultPrice5 : matchedPrice; map.put("price", finalPrice == null ? -1 : multiplyPeopleNumber(finalPrice, peopleNumber).doubleValue()); return ResultUtil.success(map); } private BigDecimal querySelfTripNearestPrice(LineShiftDriver lineShiftDriver, Double endLon, Double endLat) { Integer customerId = lineShiftDriverMapper.queryCustomerIdByLineShiftDriverId(lineShiftDriver.getId()); if (customerId == null) { return null; } DriverSelfTrip selfTrip = driverSelfTripMapper.selectById(customerId); if (selfTrip == null || ToolUtil.isEmpty(selfTrip.getDestJson())) { return null; } JSONArray destArray = JSON.parseArray(selfTrip.getDestJson()); if (destArray == null || destArray.size() == 0) { return null; } BigDecimal bestPrice = null; Double minDistance = null; String target = endLon + "," + endLat; for (int i = 0; i < destArray.size(); i++) { JSONObject dest = destArray.getJSONObject(i); if (dest == null || dest.getDouble("endLon") == null || dest.getDouble("endLat") == null || dest.getBigDecimal("price") == null) { continue; } String source = dest.getDouble("endLon") + "," + dest.getDouble("endLat"); Map distanceMap = geodesyUtil.getDistance(source, target); Double currentDistance = distanceMap == null ? null : distanceMap.get("WGS84"); if (currentDistance == null) { continue; } if (minDistance == null || currentDistance < minDistance) { minDistance = currentDistance; bestPrice = dest.getBigDecimal("price"); } } return bestPrice; } private BigDecimal queryLineDestinationPrice(Integer lineId, LineShiftDriver lineShiftDriver, Double endLon, Double endLat) { List> destinations = lineMapper.queryLineDestinations(lineId); if (destinations == null || destinations.size() == 0) { return null; } BigDecimal defaultPrice5 = getBigDecimal(destinations.get(0).get("price5")); for (Map destination : destinations) { if (isPointInDestinationFence(destination, endLon, endLat)) { if (lineShiftDriver.getTotalSeat() != null && lineShiftDriver.getTotalSeat() == 6) { BigDecimal price7 = getBigDecimal(destination.get("price7")); return price7 == null ? defaultPrice5 : price7; } BigDecimal price5 = getBigDecimal(destination.get("price5")); return price5 == null ? defaultPrice5 : price5; } } return defaultPrice5; } private boolean isPointInDestinationFence(Map destination, Double lon, Double lat) { if (destination == null || lon == null || lat == null) { return false; } Integer fenceType = destination.get("fenceType") == null ? null : Integer.valueOf(String.valueOf(destination.get("fenceType"))); String coordinate = destination.get("coordinate") == null ? null : String.valueOf(destination.get("coordinate")); if (fenceType == null || ToolUtil.isEmpty(coordinate)) { return false; } if (fenceType == 1) { String[] arr = coordinate.split(";"); if (arr.length != 2) { return false; } String[] center = arr[0].split(","); if (center.length != 2) { return false; } Map distanceMap = geodesyUtil.getDistance(center[0] + "," + center[1], lon + "," + lat); Double currentDistance = distanceMap == null ? null : distanceMap.get("WGS84"); return currentDistance != null && currentDistance <= Double.valueOf(arr[1]); } return isPointInPolygon(coordinate, lon, lat); } private boolean isPointInPolygon(String coordinate, Double lon, Double lat) { String[] points = coordinate.split(";"); if (points.length < 3) { return false; } boolean inside = false; for (int i = 0, j = points.length - 1; i < points.length; j = i++) { String[] current = points[i].split(","); String[] previous = points[j].split(","); if (current.length != 2 || previous.length != 2) { continue; } double xi = Double.parseDouble(current[0]); double yi = Double.parseDouble(current[1]); double xj = Double.parseDouble(previous[0]); double yj = Double.parseDouble(previous[1]); boolean intersect = ((yi > lat) != (yj > lat)) && (lon < (xj - xi) * (lat - yi) / ((yj - yi) == 0 ? 0.0000001D : (yj - yi)) + xi); if (intersect) { inside = !inside; } } return inside; } private BigDecimal getBigDecimal(Object value) { if (value == null || ToolUtil.isEmpty(String.valueOf(value))) { return null; } try { return new BigDecimal(String.valueOf(value)); } catch (Exception e) { return null; } } private BigDecimal multiplyPeopleNumber(BigDecimal price, Integer peopleNumber) { if (price == null || peopleNumber == null || peopleNumber <= 0) { return null; } return price.multiply(new BigDecimal(peopleNumber)).setScale(2, BigDecimal.ROUND_HALF_UP); } @Override public List taskMidAxbUnBindSend() throws Exception { return this.baseMapper.taskMidAxbUnBindSend(); } /** * 获取订单编号 * @return * @throws Exception */ public synchronized String getOrderNum(Integer driverId, Integer lineShiftDriverId) throws Exception{ List orderCrossCities = orderCrossCityMapper.queryOrders(driverId, lineShiftDriverId, Arrays.asList(2, 3, 4, 5, 6, 7)); if(orderCrossCities.size() > 0){ return orderCrossCities.get(0).getOrderNum(); } int size = this.selectCount(null); while (true){ String orderNum = "CR" + String.valueOf(1000000 + size + 1).substring(1); List orderNum1 = this.selectList(new EntityWrapper().eq("orderNum", orderNum)); if(orderNum1.size() == 0){ return orderNum; } size++; } } @Override public ResultUtil cancleOrder(Integer orderId) throws Exception { OrderCrossCity orderCrossCity = orderCrossCityMapper.selectById(orderId); if(orderCrossCity.getState() == 7 && orderCrossCity.getPayMoney() == null){ orderCrossCity.setState(10); orderCrossCityMapper.updateById(orderCrossCity); OrderCancel orderCancel = new OrderCancel(); orderCancel.setOrderId(orderId); orderCancel.setOrderType(3); orderCancel.setReason("用户未及时付款,系统自动取消订单"); orderCancel.setRemark("用户未及时付款,系统自动取消订单"); orderCancel.setState(2); orderCancel.setInsertTime(new Date()); orderCancel.setUserType(2); orderCancelService.insert(orderCancel); //修改司机座位 LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(orderCrossCity.getLineShiftDriverId()); lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() + orderCrossCity.getPeopleNumber()); lineShiftDriver.setLaveSeatNumber(lineShiftDriver.getLaveSeatNumber() + (orderCrossCity.getTravelMode() == 1 ? "," : "") + orderCrossCity.getSeatNumber()); lineShiftDriverMapper.updateById(lineShiftDriver); //修改司机为空闲 List orderCrossCities = orderCrossCityMapper.queryByDriverId(orderCrossCity.getDriverId(), 2, 3, 4, 5, 11); if(orderCrossCities.size() == 0){ Driver driver = driverService.selectById(orderCrossCity.getDriverId()); driver.setState(2); driverService.updateById(driver); } } return ResultUtil.success(); } /** * 跨城代客下单操作 * @param warpper 代客下单参数 * @param driverId 司机ID * @return 订单ID * @throws Exception */ @Override public synchronized ResultUtil orderCrossCityOnBehalf(OrderCrossCityOnBehalfWarpper warpper, Integer driverId) throws Exception { // 1. 参数校验 if (warpper.getLineShiftDriverId() == null) { return ResultUtil.error("班次ID不能为空"); } if (warpper.getPeopleNumber() == null || warpper.getPeopleNumber() < 1 || warpper.getPeopleNumber() > 7) { return ResultUtil.error("乘车人数必须在1-7之间"); } if (ToolUtil.isEmpty(warpper.getPassengersPhone())) { return ResultUtil.error("乘客手机号不能为空"); } if (warpper.getPlacementLat() == null || warpper.getPlacementLon() == null || ToolUtil.isEmpty(warpper.getPlacementAddress())) { return ResultUtil.error("下单地点点信息不完整"); } if (warpper.getStartLon() == null || warpper.getStartLat() == null || ToolUtil.isEmpty(warpper.getStartAddress())) { return ResultUtil.error("上车点信息不完整"); } if (warpper.getEndLon() == null || warpper.getEndLat() == null || ToolUtil.isEmpty(warpper.getEndAddress())) { return ResultUtil.error("下车点信息不完整"); } if (warpper.getOtherFee() != null && warpper.getOtherFee().compareTo(BigDecimal.ZERO) < 0) { return ResultUtil.error("其他费用不能为负数"); } if (warpper.getChangePrice() != null && warpper.getChangePrice().compareTo(BigDecimal.ZERO) < 0) { return ResultUtil.error("改价费用不能为负数"); } // 2. 校验班次信息 LineShiftDriver lineShiftDriver = lineShiftDriverMapper.selectById(warpper.getLineShiftDriverId()); if (lineShiftDriver == null) { return ResultUtil.error("班次信息不存在"); } if (!driverId.equals(lineShiftDriver.getDriverId())) { return ResultUtil.error("无权操作此班次"); } // 3. 校验剩余座位数 if (lineShiftDriver.getLaveSeat() < warpper.getPeopleNumber()) { return ResultUtil.error("座位不足,无法下单"); } // 4. 自动分配座位号 String laveSeatNumber = lineShiftDriver.getLaveSeatNumber(); if (ToolUtil.isEmpty(laveSeatNumber)) { return ResultUtil.error("无可用座位"); } String[] availableSeats = laveSeatNumber.split(","); if (availableSeats.length < warpper.getPeopleNumber()) { return ResultUtil.error("座位不足,无法下单"); } // 取前 peopleNumber 个座位 StringBuilder seatNumberBuilder = new StringBuilder(); for (int i = 0; i < warpper.getPeopleNumber(); i++) { if (i > 0) { seatNumberBuilder.append(","); } seatNumberBuilder.append(availableSeats[i]); } String seatNumber = seatNumberBuilder.toString(); // 5. 获取司机信息 Driver driver = driverService.selectById(driverId); if (driver == null) { return ResultUtil.error("司机信息不存在"); } if (driver.getState() == 1) { return ResultUtil.error("司机处于离线状态"); } // 6. 获取线路班次信息 LineSite lineSite; if (lineShiftDriver.getLineShiftId() <= -1) { lineSite = new LineSite(); lineSite.setLineId(-1); if (lineShiftDriver.getCustomerId() != null) { DriverSelfTrip selfTrip = driverSelfTripMapper.selectById(lineShiftDriver.getCustomerId()); if (selfTrip != null) { lineSite.setStartTime(selfTrip.getStartTime()); } } } else { lineSite = lineSiteService.selectById(lineShiftDriver.getLineShiftId()); if (lineSite == null) { return ResultUtil.error("线路班次信息不存在"); } Line line = lineService.selectById(lineSite.getLineId()); if (line == null) { return ResultUtil.error("线路信息不存在"); } } // 7. 处理用户信息 String phone = warpper.getPassengersPhone(); UserInfo userInfo = userInfoMapper.queryByPhone(phone); if (userInfo == null) { Integer integer = userInfoMapper.selectCount(null) + 1000001; String nickName = "GRJY" + String.valueOf(integer).substring(1); // 自动创建用户 userInfo = new UserInfo(); userInfo.setNickName(nickName); userInfo.setPhone(warpper.getPassengersPhone()); userInfo.setState(1); userInfo.setFlag(1); userInfo.setInsertTime(new Date()); userInfo.setInsertUser(driverId); userInfoMapper.insert(userInfo); } // 8. 检查用户是否有未完成订单 List orderPrivateCars = orderPrivateCarMapper.queryByState(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12); if (orderPrivateCars.size() > 0) { return ResultUtil.error("该乘客有未完成的订单"); } List orderTaxis = orderTaxiMapper.queryByState_(userInfo.getId(), 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12); if (orderTaxis.size() > 0) { return ResultUtil.error("该乘客有未完成的订单"); } List orderCrossCities1 = orderCrossCityMapper.queryByState(userInfo.getId(), 1, 2, 3, 4, 5, 6, 7, 11, 12); if (orderCrossCities1.size() > 0) { return ResultUtil.error("该乘客有未完成的订单"); } // // 9. 检查司机是否正在服务中 // List orderCrossCities2 = orderCrossCityMapper.queryOrders(driverId, warpper.getLineShiftDriverId(), Arrays.asList(5)); // if (orderCrossCities2.size() > 0) { // return ResultUtil.error("司机正在服务中"); // } // // 10. 计算价格 // Map distanceMap = gdMapElectricFenceUtil.getDistance( // warpper.getStartLon() + "," + warpper.getStartLat(), // warpper.getEndLon() + "," + warpper.getEndLat(), 1); // if (distanceMap == null) { // return ResultUtil.error("计算行程距离出错"); // } // Double distance = Double.valueOf(distanceMap.get("distance")); // 获取车辆信息 Car car = carServiceImpl.selectById(driver.getCarId()); if (car == null) { return ResultUtil.error("车辆信息不存在"); } CarModel carModel = carModelMapper.selectById(car.getCarModelId()); if (carModel == null) { return ResultUtil.error("车型信息不存在"); } CarService carService = carServiceMapper.query(3, driver.getCarId()); if(null == carService){ return ResultUtil.error("车辆未开通该服务"); } ResultUtil> priceResult = this.getPriceV2(lineSite.getLineId(), lineShiftDriver, warpper.getEndLon(), warpper.getEndLat(), warpper.getPeopleNumber()); if (priceResult.getCode() != 200) { return ResultUtil.error("计算价格失败"); } Double ticketPrice = Double.valueOf(priceResult.getData().get("price").toString()); if (ticketPrice < 0) { return ResultUtil.error("计算价格失败"); } // 计算合计费用 Double otherFee = warpper.getOtherFee() != null ? warpper.getOtherFee().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() : 0D; Double totalMoney = new BigDecimal(ticketPrice).add(new BigDecimal(otherFee)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); // 11. 创建订单 OrderCrossCity orderCrossCity = new OrderCrossCity(); orderCrossCity.setUserId(userInfo.getId()); orderCrossCity.setPassengers(userInfo.getName()); orderCrossCity.setPassengersPhone(warpper.getPassengersPhone()); orderCrossCity.setServerCarModelId(carService.getServerCarModelId()); orderCrossCity.setDriverId(driverId); orderCrossCity.setLineId(lineSite.getLineId()); orderCrossCity.setCarId(driver.getCarId()); orderCrossCity.setOrderNum(this.getOrderNum(driverId, warpper.getLineShiftDriverId())); // 下单地点 orderCrossCity.setPlacementLat(warpper.getPlacementLat()); orderCrossCity.setPlacementLon(warpper.getPlacementLon()); String placementAddress = warpper.getPlacementAddress(); placementAddress = placementAddress.replaceAll("& #40;", "("); placementAddress = placementAddress.replaceAll("& #41;", ")"); orderCrossCity.setPlacementAddress(placementAddress); // 上车点 orderCrossCity.setStartLon(warpper.getStartLon()); orderCrossCity.setStartLat(warpper.getStartLat()); String startAddress = warpper.getStartAddress(); startAddress = startAddress.replaceAll("& #40;", "("); startAddress = startAddress.replaceAll("& #41;", ")"); orderCrossCity.setStartAddress(startAddress); // 下车点 orderCrossCity.setEndLon(warpper.getEndLon()); orderCrossCity.setEndLat(warpper.getEndLat()); String endAddress = warpper.getEndAddress(); endAddress = endAddress.replaceAll("& #40;", "("); endAddress = endAddress.replaceAll("& #41;", ")"); orderCrossCity.setEndAddress(endAddress); orderCrossCity.setMileage(0D); if (warpper.getChangePrice() != null) { orderCrossCity.setOrderMoney(warpper.getChangePrice().doubleValue()); orderCrossCity.setHasChangePrice(1); } else { orderCrossCity.setOrderMoney(totalMoney); } orderCrossCity.setCompanyId(driver.getCompanyId()); orderCrossCity.setPeopleNumber(warpper.getPeopleNumber()); orderCrossCity.setSeatNumber(seatNumber); List orderCrossCities = this.selectList(new EntityWrapper().eq("orderNum", orderCrossCity.getOrderNum()).eq("isDelete", 1)); orderCrossCity.setSort(orderCrossCities.size() + 1); orderCrossCity.setState(7); // 待支付 orderCrossCity.setInsertTime(new Date()); // 设置出行时间为班次日期+开始时间 Calendar calendar = Calendar.getInstance(); calendar.setTime(lineShiftDriver.getDay()); String[] startTimeParts = lineSite.getStartTime().split(":"); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(startTimeParts[0])); calendar.set(Calendar.MINUTE, Integer.parseInt(startTimeParts[1])); calendar.set(Calendar.SECOND, 0); orderCrossCity.setTravelTime(calendar.getTime()); orderCrossCity.setSnatchOrderTime(new Date()); orderCrossCity.setTravelMode(1); // 固定拼车 orderCrossCity.setIsDelete(1); orderCrossCity.setIsReassign(1); orderCrossCity.setLineShiftDriverId(warpper.getLineShiftDriverId()); orderCrossCity.setOrderSource(4); // 司机下单 orderCrossCity.setOtherFee(warpper.getOtherFee()); this.insert(orderCrossCity); // 13. 更新司机状态 if (driver.getState() == 2) { driver.setState(3); driverService.updateById(driver); } // 14. 更新班次座位信息 lineShiftDriver.setLaveSeat(lineShiftDriver.getLaveSeat() - warpper.getPeopleNumber()); // 更新剩余座位号 StringBuilder newLaveSeatNumber = new StringBuilder(); for (int i = warpper.getPeopleNumber(); i < availableSeats.length; i++) { if (newLaveSeatNumber.length() > 0) { newLaveSeatNumber.append(","); } newLaveSeatNumber.append(availableSeats[i]); } lineShiftDriver.setLaveSeatNumber(newLaveSeatNumber.toString()); lineShiftDriverMapper.updateById(lineShiftDriver); // 15. 添加系统消息 systemNoticeService.addSystemNotice(1, "您的跨城订单已下单成功,请尽快完成支付!", orderCrossCity.getUserId(), 1); // 16. 创建定时任务,30分钟未支付自动取消 Integer orderId = orderCrossCity.getId(); TimerTask timerTask = new TimerTask() { @Override public void run() { OrderCrossCity order = orderCrossCityMapper.selectById(orderId); if (order.getState() == 7 && order.getPayMoney() == null) { order.setState(10); orderCrossCityMapper.updateById(order); OrderCancel orderCancel = new OrderCancel(); orderCancel.setOrderId(orderId); orderCancel.setOrderType(3); orderCancel.setReason("用户未及时付款,系统自动取消订单"); orderCancel.setRemark("用户未及时付款,系统自动取消订单"); orderCancel.setState(2); orderCancel.setInsertTime(new Date()); orderCancel.setUserType(2); orderCancelService.insert(orderCancel); // 恢复座位 LineShiftDriver lsd = lineShiftDriverMapper.selectById(order.getLineShiftDriverId()); lsd.setLaveSeat(lsd.getLaveSeat() + order.getPeopleNumber()); lsd.setLaveSeatNumber( (ToolUtil.isNotEmpty(lsd.getLaveSeatNumber()) ? lsd.getLaveSeatNumber() + "," : "") + order.getSeatNumber() ); lineShiftDriverMapper.updateById(lsd); // 修改司机为空闲 List orders = orderCrossCityMapper.queryByDriverId(order.getDriverId(), 2, 3, 4, 5, 11); if (orders.size() == 0) { Driver d = driverService.selectById(order.getDriverId()); d.setState(2); driverService.updateById(d); } } } }; Timer timer = new Timer(); timer.schedule(timerTask, 30 * 60 * 1000); // 17. 返回结果 BaseWarpper baseWarpper = new BaseWarpper(); baseWarpper.setId(orderCrossCity.getId()); return ResultUtil.success(baseWarpper); } @Override public ResultUtil orderOnBehalfPay(int crossCityOrderId, int type, Integer driverId) throws Exception { OrderCrossCity order = orderCrossCityMapper.selectById(crossCityOrderId); if (order == null) { return ResultUtil.error("订单不存在"); } if (!order.getDriverId().equals(driverId)) { return ResultUtil.error("您没有权限支付此订单"); } if (order.getState() != 7) { return ResultUtil.error("订单不在待支付,无法完成订单"); } if (type == 1) { // UserInfo userInfo = userInfoMapper.selectById(order.getUserId()); Driver driver = driverService.selectById(driverId); if (driver == null) { return ResultUtil.error("司机不存在"); } if (ToolUtil.isEmpty(driver.getAppletsOpenId())) { return ResultUtil.errorOpenId("司机未绑定微信小程序openid,无法发起微信支付"); } String outTradeNo = buildCbyzxOnBehalfOutTradeNo(crossCityOrderId); JSONObject response = cbyzxOrderPayHelper.createOrder( order.getUserId(), driver.getAppletsOpenId(), outTradeNo, order.getOrderMoney() ); if (!cbyzxOrderPayHelper.isCreateSuccess(response)) { return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response); } paymentRecordService.saveData(1, order.getDriverId(), 2, crossCityOrderId, 3, 1, order.getOrderMoney(), outTradeNo, 1); return ResultUtil.success(response); } else if (type == 3) { order.setState(2); order.setPayMoney(order.getOrderMoney()); orderCrossCityMapper.updateById(order); //添加交易明细 transactionDetailsService.saveData(driverId, "跨城出行订单", order.getOrderMoney(), 2, 1, 2, 3, order.getId()); return ResultUtil.success(); } else if (type == 2) { String path = "pages/home/home"; String unlimitQrcode = weChatUtil.getUnlimitQrcode(path, "default"); return ResultUtil.success(unlimitQrcode); } return ResultUtil.error("支付失败"); } /** * 创博优代客支付单号,增加业务前缀便于统一回调路由。 */ private String buildCbyzxOnBehalfOutTradeNo(Integer orderId) throws Exception { return "onBehalf_" + orderId + "_3_" + UUIDUtil.getRandomCode(5); } }