package com.stylefeng.guns.modular.taxi.service.impl; import cn.hutool.core.util.StrUtil; 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.controller.AppOrderController; import com.stylefeng.guns.modular.crossCity.dao.OrderCrossCityMapper; import com.stylefeng.guns.modular.crossCity.model.OrderCrossCity; import com.stylefeng.guns.modular.crossCity.server.IOrderCrossCityService; import com.stylefeng.guns.modular.crossCity.server.impl.OrderCrossCityServiceImpl; import com.stylefeng.guns.modular.smallLogistics.server.IOrderLogisticsService; import com.stylefeng.guns.modular.specialTrain.dao.OrderPrivateCarMapper; import com.stylefeng.guns.modular.specialTrain.model.OrderPrivateCar; import com.stylefeng.guns.modular.specialTrain.server.IOrderPrivateCarService; import com.stylefeng.guns.modular.system.dao.*; import com.stylefeng.guns.modular.system.model.*; import com.stylefeng.guns.modular.system.model.vo.UnPayOrderVO; import com.stylefeng.guns.modular.system.service.*; import com.stylefeng.guns.modular.system.service.impl.ServerCarModelServiceImpl; import com.stylefeng.guns.modular.system.util.*; import com.stylefeng.guns.modular.system.warpper.*; import com.stylefeng.guns.modular.taxi.dao.OrderTaxiMapper; import com.stylefeng.guns.modular.taxi.model.OrderTaxi; import com.stylefeng.guns.modular.taxi.model.PaymentRecord; import com.stylefeng.guns.modular.taxi.service.IOrderTaxiService; import com.stylefeng.guns.modular.taxi.service.IPaymentRecordService; import com.stylefeng.guns.modular.taxi.service.ITransactionDetailsService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; @Service @Transactional(isolation = Isolation.READ_UNCOMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public class OrderTaxiServiceImpl extends ServiceImpl implements IOrderTaxiService { @Resource private OrderTaxiMapper orderTaxiMapper; @Resource private SensitiveWordsMapper sensitiveWordsMapper; @Resource private SysIntegralMapper sysIntegralMapper; @Resource private UserActivityDiscount1Mapper userActivityDiscount1Mapper; @Resource private OrderPrivateCarMapper orderPrivateCarMapper; @Resource private RegionMapper regionMapper; @Autowired private IOrderCancelService orderCancelService; @Autowired private GDMapElectricFenceUtil gdMapElectricFenceUtil; @Autowired private IDriverService driverService; @Autowired private DateUtil dateUtil; @Autowired private IUserInfoService userInfoService; @Autowired private IPushOrderService pushOrderService; @Autowired private ICancleOrderService cancleOrderService; @Autowired private PayMoneyUtil payMoneyUtil; @Autowired private CbyzxOrderPayHelper cbyzxOrderPayHelper; @Autowired private ITransactionDetailsService transactionDetailsService; @Autowired private IPaymentRecordService paymentRecordService; @Autowired private IUserCouponRecordService userCouponRecordService; @Autowired private IUserRedPacketRecordService userRedPacketRecordService; @Autowired private GDMapGeocodingUtil gdMapGeocodingUtil; @Autowired private ICompanyCityService companyCityService; @Autowired private PushUtil pushUtil; @Resource private RedisTemplate redisTemplate; @Autowired private RestTemplate internalRestTemplate; @Autowired private IUserActivityRedenvelopeService userActivityRedenvelopeService; @Autowired private IDriverOrdersService driverOrdersService; @Autowired private IIncomeService incomeService; @Autowired private ICompanyService companyService; @Autowired private ISystemNoticeService systemNoticeService; @Autowired private IOrderPositionService orderPositionService; @Autowired private ChinaMobileUtil chinaMobileUtil; @Autowired private IDriverServiceService driverServiceService; @Autowired private TAbnormalPayOrderMapper abnormalPayOrderMapper; @Autowired private IOrderPrivateCarService orderPrivateCarService; @Autowired private IOrderCrossCityService orderCrossCityService; @Resource private OrderCrossCityMapper orderCrossCityMapper; @Autowired private IOrderLogisticsService orderLogisticsService; @Autowired private IOpenCityService openCityService; @Autowired private ITaxiCardService taxiCardService; @Autowired private IUserUserService userUserService; @Autowired private IUserTaxiCardService userTaxiCardService; @Autowired private IRegionService regionService; @Autowired private ITSysPushTypeService tSysPushTypeService; @Autowired private ITSysPaymentModeService tSysPaymentModeService; @Autowired private ServerCarModelServiceImpl serverCarModelService; public static List orderIds = new ArrayList<>(); @Value("${callbackPath}") private String callbackPath; @Autowired private TDriverPromotionActivityService driverPromotionActivityService; /** * 出租车下单操作 * * @param orderTaxi * @param uid * @return * @throws Exception */ @Override public synchronized ResultUtil taxiOrder(OrderTaxi orderTaxi, Integer uid) throws Exception { BaseWarpper baseWarpper = new BaseWarpper(); // 获取出发点所属公司 UserInfo userInfo1 = userInfoService.selectById(uid); if (null == userInfo1 || userInfo1.getFlag() == 3) { return ResultUtil.error("无效的账户"); } if (2 == userInfo1.getState()) { return ResultUtil.error("账号已被冻结,请联系管理员"); } Company query = companyCityService.query(String.valueOf(orderTaxi.getStartLon()), String.valueOf(orderTaxi.getStartLat())); if (null == query) { return ResultUtil.error("出发点暂未开通"); } if (null != userInfo1.getCompanyId() && 0 != userInfo1.getCompanyId()) { userInfo1.setCompanyId(query.getId()); userInfoService.updateById(userInfo1); } if (orderTaxi.getTravelTime().getTime() > (System.currentTimeMillis() + 600000)) { orderTaxi.setOrderType(2); } /** * 1.出租车、专车、跨城有待支付的订单不能叫车 * 2.小件物流有未完成的订单可以下跨城、专车、出租车 * 3.出租车、专车、跨城有预约单可以下即时单 */ List orderPrivateCars = orderPrivateCarMapper.queryByState(uid, null, 1, 7, 12); if (orderPrivateCars.size() > 0) { return ResultUtil.error("有未完成的订单"); } List list = orderTaxiMapper.queryByState_(uid, null, 1, 7, 12); if (list.size() > 0) { return ResultUtil.error("有未完成的订单"); } List orderCrossCities1 = orderCrossCityMapper.queryByState(uid, 7, 12); if (orderCrossCities1.size() > 0) { return ResultUtil.error("有未完成的订单"); } if (orderTaxi.getOrderType() == 1) { orderPrivateCars = orderPrivateCarMapper.queryByState(uid, 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12); if (orderPrivateCars.size() > 0) { return ResultUtil.error("有未完成的订单"); } list = orderTaxiMapper.queryByState_(uid, 1, 1, 1, 2, 3, 4, 5, 6, 7, 11, 12); if (list.size() > 0) { return ResultUtil.error("有未完成的订单"); } } List orderPrivateCars1 = orderPrivateCarMapper.queryByState(uid, null, 3, 7, 12); if (orderPrivateCars1.size() > 0) { return ResultUtil.error("有未完成的订单"); } List list1 = orderTaxiMapper.queryByState_(uid, null, 3, 7, 12); if (list1.size() > 0) { return ResultUtil.error("有未完成的订单"); } List orderCrossCities11 = orderCrossCityMapper.queryByState(uid, 7, 12); if (orderCrossCities11.size() > 0) { return ResultUtil.error("有未完成的订单"); } if (orderTaxi.getOrderType() == 1) { orderPrivateCars1 = orderPrivateCarMapper.queryByState(uid, 1, 3, 1, 2, 3, 4, 5, 6, 7, 11, 12); if (orderPrivateCars1.size() > 0) { return ResultUtil.error("有未完成的订单"); } list1 = orderTaxiMapper.queryByState_(uid, 1, 3, 1, 2, 3, 4, 5, 6, 7, 11, 12); if (list1.size() > 0) { return ResultUtil.error("有未完成的订单"); } } orderTaxi.setOrderNum(this.getOrderNum()); if (ToolUtil.isEmpty(orderTaxi.getPlacementLon()) || ToolUtil.isEmpty(orderTaxi.getPlacementLat())) { return ResultUtil.error("未开启定位"); } Map geocode = gdMapGeocodingUtil.geocode(String.valueOf(orderTaxi.getPlacementLon()), String.valueOf(orderTaxi.getPlacementLat())); orderTaxi.setPlacementAddress(geocode.get("address")); orderTaxi.setStartAddress(orderTaxi.getStartAddress().replaceAll("& #40;", "\\("));//特殊字符转义 orderTaxi.setStartAddress(orderTaxi.getStartAddress().replaceAll("& #41;", "\\)")); orderTaxi.setEndAddress(orderTaxi.getEndAddress().replaceAll("& #40;", "\\(")); orderTaxi.setEndAddress(orderTaxi.getEndAddress().replaceAll("& #41;", "\\)")); orderTaxi.setUserId(uid); orderTaxi.setMileage(0D); orderTaxi.setOrderMoney(0D); orderTaxi.setTravelMoney(0D); orderTaxi.setParkMoney(0D); orderTaxi.setRoadTollMoney(0D); orderTaxi.setRedPacketMoney(0D); orderTaxi.setCouponMoney(0D); orderTaxi.setInsertTime(new Date()); orderTaxi.setIsReassign(1); if (orderTaxi.getSubstitute() == 0) {//不是代下单 UserInfo userInfo = userInfoService.selectById(uid); if (ToolUtil.isEmpty(userInfo.getPhone())) { return ResultUtil.error("请先绑定手机号"); } orderTaxi.setPassengers(userInfo.getName()); orderTaxi.setPassengersPhone(userInfo.getPhone()); } orderTaxi.setState(1);//待接单 if (orderTaxi.getOrderSource() != 2) { TSysPaymentMode paymentMode = tSysPaymentModeService.selectOne(new EntityWrapper().last("LIMIT 1")); baseWarpper.setPaymentMode(paymentMode.getTaxiType()); if (paymentMode != null && Integer.valueOf(1).equals(paymentMode.getTaxiType())) { try { Map startGeocode = gdMapGeocodingUtil.geocode(String.valueOf(orderTaxi.getStartLon()), String.valueOf(orderTaxi.getStartLat())); if (orderTaxi.getEndLon() != null && orderTaxi.getEndLat() != null && startGeocode != null) { Map distance = gdMapElectricFenceUtil.getDistance( orderTaxi.getStartLon() + "," + orderTaxi.getStartLat(), orderTaxi.getEndLon() + "," + orderTaxi.getEndLat(), 1 ); if (distance != null) { double distanceMeters = Double.parseDouble(distance.get("distance")); long durationSeconds = Long.parseLong(distance.get("duration")); ServerCarModelWarpper textPrice = serverCarModelService.getTextPrice(query.getId(), distanceMeters, durationSeconds, 0, 2, startGeocode); if (textPrice != null && textPrice.getAmount() != null && textPrice.getAmount().get("zongfeiyong") != null) { Double estimateAmount = Double.valueOf(textPrice.getAmount().get("zongfeiyong").toString()); orderTaxi.setEstimateAmount(estimateAmount); orderTaxi.setOrderMoney(estimateAmount); orderTaxi.setPaymentMode(1); orderTaxi.setState(7); baseWarpper.setEstimateAmount(estimateAmount); } else { orderTaxi.setPaymentMode(2); } } else { orderTaxi.setPaymentMode(2); } } else { orderTaxi.setPaymentMode(2); } } catch (Exception e) { e.printStackTrace(); orderTaxi.setPaymentMode(2); orderTaxi.setState(1); } } else { orderTaxi.setPaymentMode(paymentMode != null && paymentMode.getTaxiType() != null ? paymentMode.getTaxiType() : 2); } } if (orderTaxi.getOrderSource() == 2 && null != orderTaxi.getDriverId()) {//扫码下单 Driver driver = driverService.selectById(orderTaxi.getDriverId()); if (null == driver) { return ResultUtil.error("扫码下单失败,司机信息有误"); } if (driver.getAuthState() == 1) { return ResultUtil.error("司机信息还未完成审核,无法完成下单"); } if (driver.getAuthState() == 3) { return ResultUtil.error("司机账户已被冻结,无法提供服务"); } if (driver.getAuthState() == 4) { return ResultUtil.error("司机信息未通过审核,无法提供服务"); } if (driver.getState() == 1) { return ResultUtil.error("司机还未上线,无法提供服务"); } if (driver.getState() == 3) { return ResultUtil.error("司机正在服务中,无法提供服务"); } List driverServices = driverServiceService.query(orderTaxi.getDriverId(), 2); if (driverServices.size() == 0) { return ResultUtil.error("该司机不能服务此业务"); } orderTaxi.setCompanyId(driver.getFranchiseeId() != null && driver.getFranchiseeId() != 0 ? driver.getFranchiseeId() : ( driver.getCompanyId() != null && driver.getCompanyId() != 0 ? driver.getCompanyId() : 1)); orderTaxi.setCarId(driver.getCarId()); orderTaxi.setState(2);//待出发 orderTaxi.setSnatchOrderTime(new Date()); // //调用高德创建轨迹 // String s = gdFalconUtil.selectTerminal(driver.getPhone()); // String track = gdFalconUtil.createTrack(s); // orderTaxi.setTrackId(track); // // 调用移动的小号接口 // Map map = chinaMobileUtil.midAxbBindSend(orderTaxi.getPassengersPhone(), driver.getPhone(), (System.currentTimeMillis() + 86400000)); // if (String.valueOf(map.get("code")).equals("200")) { // orderTaxi.setTelX(map.get("telX")); // orderTaxi.setBindId(map.get("bindId")); // } driver.setState(3); driverService.updateById(driver); } orderTaxi.setPrepayStage(Integer.valueOf(1).equals(orderTaxi.getPaymentMode()) ? 1 : 0); this.insert(orderTaxi); new Thread(new Runnable() { @Override public void run() { if (orderTaxi.getState() == 2) { // 推送司机订单状态 pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); pushUtil.pushDriverPosition(orderTaxi.getId(), 2); } } }).start(); if (orderTaxi.getState() == 1) { //推送司机抢单 this.pushOrder(orderTaxi, 1); } // 添加消息 if (orderTaxi.getState() == 7) { systemNoticeService.addSystemNotice(1, "您的出租车订单已生成,请先完成支付。", orderTaxi.getUserId(), 1); } else { systemNoticeService.addSystemNotice(1, "您的出租车订单已下单成功,我们正在为您指派司机,请稍后!", orderTaxi.getUserId(), 1); } baseWarpper.setId(orderTaxi.getId()); return ResultUtil.success(baseWarpper); } /** * 继续执行推单等待操作 * * @param id * @throws Exception */ @Override public ResultUtil pushOrderTaxi(Integer id) throws Exception { OrderTaxi orderTaxi = this.selectById(id); if (null == orderTaxi) { return ResultUtil.error("推送订单失败,订单信息有误"); } if (orderTaxi.getState() != 1) { return ResultUtil.error("订单已被司机接单,不能重复推送"); } //处理摆渡订单的继续推单逻辑 if (orderTaxi.getType() == 2) { OrderCrossCityServiceImpl.pushEndMap.put(orderTaxi.getCrossCityOrderId(), false);//还原标识数据 List list = orderPrivateCarService.selectList(new EntityWrapper().eq("type", 2).eq("crossCityOrderId", orderTaxi.getCrossCityOrderId()).eq("place", orderTaxi.getPlace())); List> orders = new ArrayList<>(); for (OrderPrivateCar orderPrivateCar1 : list) { if (orderPrivateCar1.getState() != 1) { return ResultUtil.error("订单已被司机接单,推单取消"); } Map map = new HashMap<>(); map.put("orderType", 1); map.put("orderId", orderPrivateCar1.getId()); orders.add(map); } List list1 = this.selectList(new EntityWrapper().eq("type", 2).eq("crossCityOrderId", orderTaxi.getCrossCityOrderId()).eq("place", orderTaxi.getPlace())); for (OrderTaxi orderTaxi1 : list1) { if (orderTaxi1.getState() != 1) { return ResultUtil.error("订单已被司机接单,推单取消"); } Map map = new HashMap<>(); map.put("orderType", 2); map.put("orderId", orderTaxi1.getId()); orders.add(map); } //开始推送跨城订单 orderCrossCityService.pushOrder(orders); } else { this.pushOrder(orderTaxi, 1); } return ResultUtil.success(); } /** * 获取取消订单需要支付的金额(包含小费) * * @param id * @return * @throws Exception */ @Override public ResultUtil queryCancleAmount(Integer id) throws Exception { OrderTaxi orderTaxi = this.selectById(id); if (null == orderTaxi) { return ResultUtil.error("获取数据失败,订单信息有误"); } if (orderTaxi.getState() == 5) { return ResultUtil.error("订单已开始服务,不能取消订单"); } if (orderTaxi.getState() == 6 || orderTaxi.getState() == 7 || orderTaxi.getState() == 8 || orderTaxi.getState() == 9) { return ResultUtil.error("订单已完成,不能取消订单"); } if (orderTaxi.getState() == 10) { return ResultUtil.error("订单已被取消,不能重复操作"); } double amount = 0; OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); CancleOrder query = cancleOrderService.query(orderTaxi.getOrderType(), 2, openCity.getId()); if (null == query) { return ResultUtil.error("请先完善取消规则"); } if (null != orderTaxi.getDriverId() && (orderTaxi.getSnatchOrderTime().getTime() + query.getMinuteNum() * 60 * 1000) < new Date().getTime()) {//收费的情况 if (null != query) { amount += query.getMoney(); } } BaseWarpper baseWarpper = new BaseWarpper(); baseWarpper.setAmount(amount); return ResultUtil.success(baseWarpper); } /** * 添加订单取消 * * @param id * @param reason * @param remark * @param uid * @throws Exception */ @Override public ResultUtil addCancle(Integer id, String reason, String remark, Integer uid) throws Exception { if (ToolUtil.isNotEmpty(remark)) { if (ToolUtil.isNotEmpty(remark)) { List sensitiveWords = sensitiveWordsMapper.selectList(null); for (SensitiveWords s : sensitiveWords) { remark = remark.replaceAll(s.getContent(), "***"); } } } OrderTaxi orderTaxi = this.selectById(id); Integer integer = null; if (null == orderTaxi) { return ResultUtil.error("取消订单失败,订单信息有误"); } // if(orderTaxi.getState() == 4){ // return ResultUtil.error("司机已到达预约点,取消会产生一定的费用"); // } if (orderTaxi.getState() >= 5 && orderTaxi.getState() != 11 && orderTaxi.getCancelType() ==2) { return ResultUtil.error("订单已取消,请刷新页面"); } System.out.println("出租车退款111!!!!"); if (!Integer.valueOf(2).equals(orderTaxi.getPaymentMode()) && StrUtil.isNotEmpty(orderTaxi.getPrepaySecondPayNo())) { System.out.println("出租车退款2222!!!!"); ResultUtil refundResult = handleTaxiPrepayCancelRefund(orderTaxi, reason, remark, uid); if (refundResult != null) { System.out.println("出租车退款3333!!!!"+refundResult.getCode()); if (!ResultUtil.SUCCESS.equals(refundResult.getCode())) { return refundResult; } Map map = new HashMap<>(); map.put("id", null); return ResultUtil.success(map); } }else if(!Integer.valueOf(2).equals(orderTaxi.getPaymentMode()) && StrUtil.isEmpty(orderTaxi.getPrepaySecondPayNo())){ UserInfo userInfo = userInfoService.selectById(orderTaxi.getUserId()); userInfo.setBalance(userInfo.getBalance() + orderTaxi.getPayMoney()); userInfoService.updateById(userInfo); } if (null == orderTaxi.getDriverId()) {//没有接单的情况 if (orderTaxi.getType() == 2) {//摆渡车 OrderCrossCityServiceImpl.pushEndMap.remove(orderTaxi.getCrossCityOrderId());//删除标识数据 List list = orderPrivateCarService.selectList(new EntityWrapper().eq("type", 2).eq("crossCityOrderId", orderTaxi.getCrossCityOrderId()).eq("place", orderTaxi.getPlace())); for (OrderPrivateCar orderPrivateCar1 : list) { orderCancelService.saveData(orderPrivateCar1.getId(), 1, "无司机接单", "无司机接单", null, null, 2, 1, uid); orderPrivateCar1.setState(10); orderPrivateCarService.updateById(orderPrivateCar1); } List list1 = this.selectList(new EntityWrapper().eq("type", 2).eq("crossCityOrderId", orderTaxi.getCrossCityOrderId()).eq("place", orderTaxi.getPlace())); for (OrderTaxi orderTaxi1 : list1) { orderCancelService.saveData(orderTaxi1.getId(), 2, "无司机接单", "无司机接单", null, null, 2, 1, uid); orderTaxi1.setState(10); this.updateById(orderTaxi1); } } else { integer = orderCancelService.saveData(id, 2, "无司机接单", "无司机接单", null, null, 2, 1, uid); orderTaxi.setState(10); this.updateById(orderTaxi); } } else { OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); CancleOrder query = cancleOrderService.query(orderTaxi.getOrderType(), 2, openCity.getId()); if (null != query) { if ((orderTaxi.getSnatchOrderTime().getTime() + query.getMinuteNum() * 60 * 1000) < System.currentTimeMillis() && query.getMoney().compareTo(0D) > 0) {//收费的情况 orderTaxi.setState(12); this.updateById(orderTaxi); integer = orderCancelService.saveData(id, 2, reason, remark, null, query.getMoney(), 1, 1, uid); } else { integer = orderCancelService.saveData(id, 2, reason, remark, null, null, 2, 1, uid); orderTaxi.setState(10); this.updateById(orderTaxi); } this.deleteTask(id);//删除定时任务 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); System.err.println("推送取消操作--------------------"); } }).start(); //修改司机为空闲 Driver driver = driverService.selectById(orderTaxi.getDriverId()); driver.setState(2); driverService.updateById(driver); } else { return ResultUtil.error("请完善后台取消规则设置"); } } //添加消息 systemNoticeService.addSystemNotice(1, "您已成功取消出行订单,谢谢使用!", orderTaxi.getUserId(), 1); Map map = new HashMap<>(); map.put("id", integer); return ResultUtil.success(map); } /** * 取消订单操作 * * @param id * @return * @throws Exception */ @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public ResultUtil cancleOrderTaxi(Integer id, Integer payType, Integer cancleId, Integer type) throws Exception { OrderTaxi orderTaxi = this.selectById(id); Integer uid = orderTaxi.getUserId(); UserInfo userInfo = userInfoService.selectById(uid); ResultUtil resultUtil = ResultUtil.success(new Object()); if (null == orderTaxi) { return ResultUtil.error("取消订单失败,订单信息有误", ""); } if (orderTaxi.getState() != 12) { return ResultUtil.error("订单已取消,请刷新页面", ""); } OrderCancel orderCancel = null; if (null == cancleId) { orderCancel = orderCancelService.query(id, 2, null, null, 1); } else { orderCancel = orderCancelService.selectById(cancleId); } OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); CancleOrder query = cancleOrderService.query(orderTaxi.getOrderType(), 2, openCity.getId()); System.out.println("取消订单:" + query); if (null != query) { if (payType == 1) {//微信支付 orderCancel.setPayType(1); orderCancelService.updateById(orderCancel); String outTradeNo = "CANCEL_" + id + "_2_" + UUIDUtil.getRandomCode(5); JSONObject response = cbyzxOrderPayHelper.createOrder(orderTaxi.getUserId(), userInfo.getAppletsOpenId(), outTradeNo, query.getMoney()); if (!cbyzxOrderPayHelper.isCreateSuccess(response)) { return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response); } String paymentCode = ToolUtil.isNotEmpty(cbyzxOrderPayHelper.extractRecordCode(response)) ? cbyzxOrderPayHelper.extractRecordCode(response) : outTradeNo; resultUtil = ResultUtil.success(response); paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, id, 2, 1, query.getMoney(), paymentCode, 1);//添加预支付数据 // Map map = icbcPayUtil.placeAnOrder(id + ",2", 9, 5, uid.toString(), "订单取消", query.getMoney(), callbackPath + "/base/wxCancelOrderTaxi", "", type, appletsOpenId); // if(map.get("code").equals("200")){ // paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, id, 2, 1, query.getMoney(), map.get("order_id"), 1);//添加预支付数据 // resultUtil = ResultUtil.success(map.get("data")); // }else{ // resultUtil = ResultUtil.error(map.get("msg"), ""); // } } if (payType == 2) {//支付宝支付 orderCancel.setPayType(2); orderCancelService.updateById(orderCancel); resultUtil = payMoneyUtil.alipay("订单取消", "订单取消", "", id + "_2_" + UUIDUtil.getRandomCode(5), query.getMoney().toString(), "/base/aliCancelOrderTaxi"); paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, id, 2, 2, query.getMoney(), "", 1);//添加预支付数据 // Map map = icbcPayUtil.placeAnOrder(id + ",2", 10, 5, uid.toString(), "订单取消", query.getMoney(), callbackPath + "/base/aliCancelOrderTaxi", "", type, null); // if(map.get("code").equals("200")){ // paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, id, 2, 2, query.getMoney(), map.get("order_id"), 1);//添加预支付数据 // resultUtil = ResultUtil.success(map.get("data")); // }else{ // resultUtil = ResultUtil.error(map.get("msg"), ""); // } } if (payType == 3) {//余额支付 if (userInfo.getBalance() != null && userInfo.getBalance() < query.getMoney()) { return ResultUtil.error("余额不足,无法完成支付"); } // resultUtil= appOrderController.moneyPay(id,userInfo.getId(),query.getMoney()); // if(resultUtil.getCode()==500){ // return ResultUtil.error("电子余额不足,无法完成支付"); // } userInfo.setBalance(new BigDecimal(userInfo.getBalance()).subtract(new BigDecimal(query.getMoney())).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); //添加交易明细 transactionDetailsService.saveData(uid, "出租车取消订单", query.getMoney(), 2, 1, 1, 2, id); userInfoService.updateById(userInfo); //解除小号绑定 if (orderTaxi.getBindId() != null) { chinaMobileUtil.midAxbUnBindSend(orderTaxi.getBindId(), orderTaxi.getTelX(), (System.currentTimeMillis() + 600000)); } orderTaxi.setState(10); orderTaxi.setTelX(""); orderTaxi.setBindId(""); this.updateById(orderTaxi); orderCancel.setState(2); orderCancel.setPayType(3); orderCancelService.updateById(orderCancel); //添加已收入明细 incomeService.saveData(1, orderTaxi.getCompanyId(), 3, orderTaxi.getId(), 2, query.getMoney()); this.deleteTask(id);//删除定时任务 // new Thread(new Runnable() { // @Override // public void run() { // pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); // } // }).start(); //添加消息 systemNoticeService.addSystemNotice(1, "您已使用余额成功支付取消订单费用,谢谢使用!", orderTaxi.getUserId(), 1); } if (payType == 4) { Double payMoney = orderTaxi.getOrderMoney(); Integer integer = paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, id, 2, 4, query.getMoney(), "", 1); resultUtil = appOrderController.placeAnOrder(new BigDecimal(query.getMoney()), 4, id, 8, integer); } } return resultUtil; } /** * 删除定时任务 * * @param orderId */ @Override public void deleteTask(Integer orderId) { //发送验证码短信 HttpHeaders headers = new HttpHeaders(); // 浠ヨ〃鍗曠殑鏂瑰紡鎻愪氦 headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //将请求头和参数组装成一个请求 MultiValueMap params = new LinkedMultiValueMap<>(); params.add("orderId", orderId + ""); params.add("orderType", "2"); HttpEntity> requestEntity = new HttpEntity<>(params, headers); String s = internalRestTemplate.postForObject("http://driver-server/base/netty/deleteTask", requestEntity, String.class); JSONObject jsonObject = JSON.parseObject(s, JSONObject.class); if (jsonObject.getIntValue("code") != 200) { System.err.println("调用driver-server出错了"); } } /** * 获取用户余额和可用优惠券数量 * * @param uid * @return * @throws Exception */ @Override public Map queryBalance(Integer orderId, Integer uid) throws Exception { Map map = new HashMap<>(); UserInfo userInfo = userInfoService.selectById(uid); map.put("balance", userInfo.getBalance()); OrderTaxi orderTaxi = this.selectById(orderId); int i = userCouponRecordService.queryAvailable(uid, orderTaxi.getCompanyId(), 1, 2, orderTaxi.getOrderMoney()); i = i + userCouponRecordService.queryAvailable(uid, orderTaxi.getCompanyId(), 1, 0, orderTaxi.getOrderMoney()); map.put("coupon", i); return map; } @Override public PreferentialDataVo queryBalance1(Integer orderId, Integer uid) throws Exception { UserInfo userInfo = userInfoService.selectById(uid); PreferentialDataVo preferentialDataVo = new PreferentialDataVo(); preferentialDataVo.setBalance(userInfo.getBalance()); OrderTaxi orderTaxi = this.selectById(orderId); Integer ids = userInfoService.getDiscount(); if (ids != null) { List userActivityId = userActivityDiscount1Mapper.selectList(new EntityWrapper().eq("userActivityId", ids)); if (userActivityId.size() > 0) { preferentialDataVo.setDiscount(userActivityId.get(0).getTaxi()); } } // 查出当前用户的红包,并将订单进行修改 List userRedPacketRecords = userRedPacketRecordService.selectList(new EntityWrapper().eq("userId", uid).eq("state", 1).le("money", orderTaxi.getOrderMoney()).gt("expirationTime", new Date()).gt("endTime", new Date())); if (userRedPacketRecords.size() > 0) { preferentialDataVo.setRedPacket(userRedPacketRecords.get(0).getMoney()); orderTaxi.setRedPacketId(userRedPacketRecords.get(0).getId()); orderTaxi.setRedPacketMoney(userRedPacketRecords.get(0).getMoney()); this.updateById(orderTaxi); } //获取优惠券中最优数据 List list = userCouponRecordService.selectList(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("state", 1).le("money", orderTaxi.getOrderMoney()).in("couponUseType", Arrays.asList(0, 2)).eq("userId", uid).where("now() < expirationTime")); Integer id = null; Double price = 0d; Integer type = 0; for (UserCouponRecord userCouponRecord : list) { if (userCouponRecord.getCouponType() == 1) {//抵扣券 if (price.compareTo(userCouponRecord.getMoney()) < 0) { price = userCouponRecord.getMoney(); id = userCouponRecord.getId(); type = 1; } } else {//满减券 if (orderTaxi.getOrderMoney().compareTo(userCouponRecord.getFullMoney()) >= 0 && price.compareTo(userCouponRecord.getMoney()) < 0) { price = userCouponRecord.getMoney(); id = userCouponRecord.getId(); type = 1; } } } //获取打车卡中最优数 Map geocode = gdMapGeocodingUtil.geocode(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); CompanyCity companyCity = companyCityService.selectOne(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("areaCode", geocode.get("districtCode")).eq("state", 1)); if (null == companyCity) { companyCity = companyCityService.selectOne(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("cityCode", geocode.get("cityCode")).eq("state", 1)); } if (null == companyCity) { companyCity = companyCityService.selectOne(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("provinceCode", geocode.get("provinceCode")).eq("state", 1)); } List userTaxiCards; if (null != companyCity) { userTaxiCards = userTaxiCardService.selectList(new EntityWrapper().like("companyCityId", "%" + companyCity.getId() + "%") .in("type", Arrays.asList(1, 2, 3, 4)).eq("userId", uid).where("now() between startTime and endTime")); } else { userTaxiCards = new ArrayList<>(); } //全国卡 List taxiCards = taxiCardService.selectList(new EntityWrapper().eq("taxiCardType", 2).in("type", Arrays.asList(1, 2, 3, 4)).eq("state", 1)); if (taxiCards.size() > 0) { List userTaxiCards2 = userTaxiCardService.selectList(new EntityWrapper().eq("userId", uid) .in("type", Arrays.asList(1, 2, 3, 4)).in("taxiCardId", taxiCards.stream().map(TaxiCard::getId).collect(Collectors.toList())).where("now() between startTime and endTime")); userTaxiCards.addAll(userTaxiCards2); } Map map = getOptimalTaxiCards(orderTaxi, price, id, type, userTaxiCards); price = Double.valueOf(map.get("price").toString()); id = null != map.get("id") ? Integer.valueOf(map.get("id").toString()) : null; type = Integer.valueOf(map.get("type").toString()); //亲密账户 List userTaxiCards_ = new ArrayList<>(); List bindUserId = userUserService.selectList(new EntityWrapper().eq("bindUserId", uid)); CompanyCity finalCompanyCity = companyCity; bindUserId.forEach(userUser -> { if (finalCompanyCity != null) { List userTaxiCards1 = userTaxiCardService.selectList(new EntityWrapper().in("type", Arrays.asList(1, 2, 3, 4)) .like("companyCityId", "%" + finalCompanyCity.getId() + "%").eq("userId", userUser.getUserId()).where("now() between startTime and endTime")); userTaxiCards_.addAll(userTaxiCards1); } //全国卡 if (taxiCards.size() > 0) { List userTaxiCards2 = userTaxiCardService.selectList(new EntityWrapper().eq("userId", userUser.getUserId()) .in("type", Arrays.asList(1, 2, 3, 4)).in("taxiCardId", taxiCards.stream().map(TaxiCard::getId).collect(Collectors.toList())).where("now() between startTime and endTime")); userTaxiCards_.addAll(userTaxiCards2); } }); map = getOptimalTaxiCards(orderTaxi, price, id, type, userTaxiCards_); price = Double.valueOf(map.get("price").toString()); id = null != map.get("id") ? Integer.valueOf(map.get("id").toString()) : null; type = Integer.valueOf(map.get("type").toString()); if (price <= orderTaxi.getOrderMoney() || type == 2) { preferentialDataVo.setObjectId(id); preferentialDataVo.setDiscountAmount(price); preferentialDataVo.setType(type); } return preferentialDataVo; } /** * 获取最优打车卡数据 * * @param orderTaxi * @param price * @param id * @param type * @param userTaxiCards * @return */ public Map getOptimalTaxiCards(OrderTaxi orderTaxi, Double price, Integer id, Integer type, List userTaxiCards) throws Exception { Map map = new HashMap<>(); for (UserTaxiCard t : userTaxiCards) { JSONObject jsonObject = JSON.parseObject(t.getContent()); List integers = jsonObject.getJSONArray("businessTypes").toJavaList(Integer.class); if (!integers.contains(2)) { continue; } if (t.getType() == 1) {//打折次数卡{"businessTypes":[1,2,3],"time":5,"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"],"discount":5} Integer time = jsonObject.getInteger("time"); if (time == 0) { continue; } JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); Double discount = jsonObject.getDouble("discount"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { double v = new BigDecimal(orderTaxi.getOrderMoney()).multiply(new BigDecimal((10 - discount) / 10)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); if (price.compareTo(v) < 0) { price = v; id = t.getId(); type = 2; } } } } if (t.getType() == 2) {//优惠卡{"businessTypes":[1,2,3],"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"],"fullReduction":[[50,3],[100,5],[150,10]]} JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); JSONArray fullReduction = jsonObject.getJSONArray("fullReduction"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { for (int j = fullReduction.size() - 1; j >= 0; j--) { JSONArray jsonArray = fullReduction.getJSONArray(j); Double p = jsonArray.getDouble(0);//满金额 Double y = jsonArray.getDouble(1);//优惠金额 if (orderTaxi.getOrderMoney().compareTo(p) >= 0 && price.compareTo(y) < 0) { price = y; id = t.getId(); type = 2; } } } } } if (t.getType() == 3) {//次数卡{"businessTypes":[1,2,3],"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"],"time":1,"discountAmount":10} Integer time = jsonObject.getInteger("time"); if (time == 0) { continue; } JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); Double discountAmount = jsonObject.getDouble("discountAmount"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { if (price.compareTo(discountAmount) < 0) { price = discountAmount; id = t.getId(); type = 2; } } } } if (t.getType() == 4) {//打折天数卡{"businessTypes":[1,2,3],"discount":5,"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"]} Double discount = jsonObject.getDouble("discount");//鎶樻墸 JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum");//使用时间段 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { double v = new BigDecimal(orderTaxi.getOrderMoney()).multiply(new BigDecimal((10 - discount) / 10)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); if (price.compareTo(v) < 0) { price = v; id = t.getId(); type = 2; } } } } } map.put("price", price); map.put("id", id); map.put("type", type); return map; } /** * 获取优惠券列表 * * @param orderId * @return * @throws Exception */ @Override public List> queryCoupon(Integer orderId, Integer uid, Integer pageNum, Integer size) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); List> list = userCouponRecordService.queryCoupon(uid, orderTaxi.getCompanyId(), 1, 2, orderTaxi.getOrderMoney(), pageNum, size); List> list1 = userCouponRecordService.queryCoupon(uid, orderTaxi.getCompanyId(), 1, 0, orderTaxi.getOrderMoney(), pageNum, size); list.addAll(list1); return list; } @Override public List queryCouponList(Integer orderId, Integer uid, Integer pageNum, Integer size) throws Exception { pageNum = (pageNum - 1) * size; OrderTaxi orderTaxi = this.selectById(orderId); List rows = new ArrayList<>(); List list = userCouponRecordService.selectList(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()) .eq("state", 1).in("couponUseType", Arrays.asList(0, 2)).eq("userId", uid).where("expirationTime >= now()")); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (UserCouponRecord userCouponRecord : list) { if (userCouponRecord.getCouponType() == 2) {//满减券 if (orderTaxi.getOrderMoney().compareTo(userCouponRecord.getFullMoney()) < 0) { continue; } } CouponsListVo couponsListVo = new CouponsListVo(); couponsListVo.setId(userCouponRecord.getId()); couponsListVo.setDataType(1); couponsListVo.setMoney(userCouponRecord.getMoney()); couponsListVo.setUserType(userCouponRecord.getCouponUseType()); couponsListVo.setTime(sdf.format(userCouponRecord.getExpirationTime())); couponsListVo.setType(userCouponRecord.getCouponType()); couponsListVo.setFullMoney(userCouponRecord.getFullMoney()); couponsListVo.setState(userCouponRecord.getState()); Company company = companyService.selectById(userCouponRecord.getCompanyId()); couponsListVo.setCompany(company.getName()); rows.add(couponsListVo); } Map geocode = gdMapGeocodingUtil.geocode(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); System.out.println(geocode); CompanyCity companyCity = companyCityService.selectOne(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("areaCode", geocode.get("districtCode")).eq("state", 1)); if (null == companyCity) { companyCity = companyCityService.selectOne(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("cityCode", geocode.get("cityCode")).eq("state", 1)); } if (null == companyCity) { companyCity = companyCityService.selectOne(new EntityWrapper().eq("companyId", orderTaxi.getCompanyId()).eq("provinceCode", geocode.get("provinceCode")).eq("state", 1)); } List userTaxiCards = new ArrayList<>(); if (null != companyCity) { userTaxiCards = userTaxiCardService.selectList(new EntityWrapper().eq("userId", uid) .in("type", Arrays.asList(1, 2, 3, 4)).like("companyCityId", "%" + companyCity.getId() + "%").where("now() between startTime and endTime")); } //全国卡 List taxiCards = taxiCardService.selectList(new EntityWrapper().eq("taxiCardType", 2).in("type", Arrays.asList(1, 2, 3, 4)).eq("state", 1)); if (taxiCards.size() > 0) { List userTaxiCards1 = userTaxiCardService.selectList(new EntityWrapper().eq("userId", uid) .in("type", Arrays.asList(1, 2, 3, 4)).in("taxiCardId", taxiCards.stream().map(TaxiCard::getId).collect(Collectors.toList())).where("now() between startTime and endTime")); userTaxiCards.addAll(userTaxiCards1); } //亲密账户 List bindUserId = userUserService.selectList(new EntityWrapper().eq("bindUserId", uid)); CompanyCity finalCompanyCity = companyCity; List finalUserTaxiCards = userTaxiCards; bindUserId.forEach(userUser -> { if (finalCompanyCity != null) { List taxiCardPayments1 = userTaxiCardService.selectList(new EntityWrapper().in("type", Arrays.asList(1, 2, 3, 4)) .like("companyCityId", "%" + finalCompanyCity.getId() + "%").eq("userId", userUser.getUserId()).where("now() between startTime and endTime")); finalUserTaxiCards.addAll(taxiCardPayments1); } //全国卡 if (taxiCards.size() > 0) { List userTaxiCards1 = userTaxiCardService.selectList(new EntityWrapper().eq("userId", userUser.getUserId()) .in("type", Arrays.asList(1, 2, 3, 4)).in("taxiCardId", taxiCards.stream().map(TaxiCard::getId).collect(Collectors.toList())).where("now() between startTime and endTime")); finalUserTaxiCards.addAll(userTaxiCards1); } }); for (UserTaxiCard t : finalUserTaxiCards) { try { CouponsListVo couponsListVo = new CouponsListVo(); couponsListVo.setId(t.getId()); couponsListVo.setDataType(2); couponsListVo.setUserType(1); couponsListVo.setTaxiCardType(t.getType()); couponsListVo.setTime(sdf.format(t.getEndTime())); couponsListVo.setState(1); Company company = companyService.selectById(t.getCompanyId()); couponsListVo.setCompany(company.getName()); couponsListVo.setName(taxiCardService.selectById(t.getTaxiCardId()).getName()); JSONObject jsonObject = JSON.parseObject(t.getContent()); JSONArray businessTypes = jsonObject.getJSONArray("businessTypes"); if (!businessTypes.toJavaList(Integer.class).contains(2)) { continue; } if (t.getType() == 1) {//{"businessTypes":[1,2,3],"time":5,"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"],"discount":5} Integer time = jsonObject.getInteger("time"); if (time == 0) { continue; } JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); boolean b = true; for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf.parse(sdf1.format(new Date()) + " " + split[0]); Date e = sdf.parse(sdf1.format(new Date()) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { b = false; break; } } if (b) { continue; } couponsListVo.setMoney(jsonObject.getDouble("discount")); couponsListVo.setType(1); } if (t.getType() == 2) {//{"businessTypes":[1,2,3],"fullReduction":[[50,3],[100,5],[150,10]]} JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); boolean b = true; for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf.parse(sdf1.format(new Date()) + " " + split[0]); Date e = sdf.parse(sdf1.format(new Date()) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { b = false; break; } } if (b) { continue; } JSONArray fullReduction = jsonObject.getJSONArray("fullReduction"); b = true; for (int i = fullReduction.size() - 1; i >= 0; i--) { JSONArray jsonArray = fullReduction.getJSONArray(i); Double m = jsonArray.getDouble(0); Double j = jsonArray.getDouble(1); if (orderTaxi.getOrderMoney().compareTo(m) >= 0) { couponsListVo.setMoney(j); couponsListVo.setFullMoney(m); b = false; break; } } if (b) { continue; } couponsListVo.setType(2); } if (t.getType() == 3) {//{"businessTypes":[1,2,3],"time":1,"discountAmount":10} Integer time = jsonObject.getInteger("time"); if (time == 0) { continue; } JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); boolean b = true; for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf.parse(sdf1.format(new Date()) + " " + split[0]); Date e = sdf.parse(sdf1.format(new Date()) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { b = false; break; } } if (b) { continue; } couponsListVo.setMoney(jsonObject.getDouble("discountAmount")); couponsListVo.setType(2); } if (t.getType() == 4) {//{"businessTypes":[1,2,3],"discount":5,"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"]} JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); boolean b = true; for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf.parse(sdf1.format(new Date()) + " " + split[0]); Date e = sdf.parse(sdf1.format(new Date()) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { b = false; break; } } if (b) { continue; } couponsListVo.setMoney(jsonObject.getDouble("discount")); couponsListVo.setType(1); } String str = ""; TaxiCard taxiCard = taxiCardService.selectById(t.getTaxiCardId()); if (taxiCard.getTaxiCardType() == 1) { String[] split = taxiCard.getCompanyCityId().split(";"); for (String c : split) { CompanyCity companyCity1 = companyCityService.selectById(c); if (ToolUtil.isNotEmpty(companyCity1.getAreaCode())) { Region region = regionService.selectOne(new EntityWrapper().eq("code", companyCity1.getAreaCode())); str += region.getName() + ";"; continue; } if (ToolUtil.isNotEmpty(companyCity1.getCityCode())) { Region region = regionService.selectOne(new EntityWrapper().eq("code", companyCity1.getCityCode())); str += region.getName() + ";"; continue; } if (ToolUtil.isNotEmpty(companyCity1.getProvinceCode())) { Region region = regionService.selectOne(new EntityWrapper().eq("code", companyCity1.getProvinceCode())); str += region.getName() + ";"; continue; } } } else { str = "鍏ㄥ浗;"; } couponsListVo.setCity(str.substring(0, str.length() - 1)); rows.add(couponsListVo); } catch (Exception e) { e.printStackTrace(); } } Collections.sort(rows, new Comparator() { public int compare(CouponsListVo s1, CouponsListVo s2) { return Integer.compare(s1.getId(), s2.getId()); } }); if (rows.size() >= (pageNum + 1) * size) { rows = rows.subList(pageNum, pageNum + size); } else if (pageNum < rows.size() && rows.size() < (pageNum + 1) * size) { rows = rows.subList(pageNum, rows.size()); } else { rows = new ArrayList<>(); } rows = rows.stream().filter(e -> e.getMoney() <= orderTaxi.getOrderMoney() || e.getDataType() == 2).collect(Collectors.toList()); return rows; } /** * 订单完成支付操作 * * @param payType 1=微信,2=支付宝,3=余额 * @param orderId * @return * @throws Exception */ @Override public ResultUtil payTaxiOrder(Integer payType, Integer orderId, Integer couponId, Integer type) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); if (orderTaxi.getState() == 8 || orderTaxi.getState() == 9) { return ResultUtil.error("订单已完成支付,不允许重复支付", ""); } if (orderTaxi.getState() != 7) { return ResultUtil.error("订单不在待支付状态,不允许支付", ""); } if (Integer.valueOf(1).equals(orderTaxi.getPaymentMode()) && Integer.valueOf(4).equals(orderTaxi.getPrepayStage())) { return ResultUtil.error("订单退款处理中,请等待退款完成", ""); } Integer uid = orderTaxi.getUserId(); Double orderMoney = (2 == orderTaxi.getAbnormal() && 2 == orderTaxi.getAbnormalStatus() ? orderTaxi.getResponsibilityMoney().doubleValue() : orderTaxi.getOrderMoney()); UserInfo userInfo = userInfoService.selectById(uid); ResultUtil resultUtil = ResultUtil.success(new Object()); orderTaxi.setCouponMoney(0D);//初始化历史数据 orderTaxi.setCouponId(null); //计算优惠券 UserCouponRecord userCouponRecord = null; if (null != couponId) { userCouponRecord = userCouponRecordService.selectById(couponId); if (userCouponRecord.getCompanyId() != orderTaxi.getCompanyId()) { return ResultUtil.error("优惠券不能用于此订单", ""); } if (userCouponRecord.getState() == 2) { return ResultUtil.error("优惠券已使用", ""); } if (userCouponRecord.getState() == 3) { return ResultUtil.error("优惠券已过期", ""); } if (userCouponRecord.getCouponUseType() != 0 && userCouponRecord.getCouponUseType() != 2) { return ResultUtil.error("优惠券不能用于此类型订单", ""); } if (userCouponRecord.getCouponType() == 2 && orderMoney.compareTo(userCouponRecord.getFullMoney()) < 0) { return ResultUtil.error("优惠券不能用于此订单", ""); } orderMoney = orderMoney - userCouponRecord.getMoney(); orderTaxi.setCouponMoney(userCouponRecord.getMoney()); orderTaxi.setCouponId(couponId); } //计算红包 UserRedPacketRecord query = userRedPacketRecordService.query(uid, orderTaxi.getCompanyId(), 1, 2, orderMoney); if (null != query && orderMoney.compareTo(query.getMoney()) > 0) { orderMoney = orderMoney - query.getMoney(); orderTaxi.setRedPacketMoney(query.getMoney()); orderTaxi.setRedPacketId(query.getId()); } //计算折扣 UserActivityDiscount1 query2 = userActivityDiscount1Mapper.query(orderTaxi.getCompanyId()); if (null != query2) { Double taxi = query2.getTaxi(); orderTaxi.setDiscount(taxi); double v = new BigDecimal(orderMoney).multiply(new BigDecimal(taxi / 10)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue(); if (orderMoney.compareTo(v) > 0) { orderTaxi.setDiscountMoney(orderMoney - v); orderTaxi.setActivityId(query2.getId()); orderMoney = v; } } ResultUtil prepaySettleResult = settleTaxiPrepayIfNoSecondPay(orderTaxi, userInfo, orderMoney); if (prepaySettleResult != null) { return prepaySettleResult; } orderMoney = getTaxiPrepayFinalPayAmount(orderTaxi, orderMoney); if (payType == 1) {//微信支付 String outTradeNo = orderId + "_2_" + UUIDUtil.getRandomCode(5); JSONObject response = cbyzxOrderPayHelper.createOrder(orderTaxi.getUserId(), userInfo.getAppletsOpenId(), outTradeNo, orderMoney); if (!cbyzxOrderPayHelper.isCreateSuccess(response)) { return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response); } String paymentCode = ToolUtil.isNotEmpty(cbyzxOrderPayHelper.extractRecordCode(response)) ? cbyzxOrderPayHelper.extractRecordCode(response) : outTradeNo; resultUtil = ResultUtil.success(response); paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, orderId, 2, 1, orderMoney, paymentCode, 1);//添加预支付数据 } if (payType == 2) {//支付宝支付 String outTradeNo = orderId + "_2_" + UUIDUtil.getRandomCode(5); resultUtil = payMoneyUtil.alipay("完成订单", "完成订单", "", outTradeNo, orderMoney.toString(), "/base/aliPayOrderTaxi"); paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, orderId, 2, 2, orderMoney, outTradeNo, 1);//添加预支付数据 } if (payType == 3) {//余额支付 if (userInfo.getBalance() == null || userInfo.getBalance() < orderMoney) { return ResultUtil.error("余额不足,无法完成支付", ""); } userInfo.setBalance(new BigDecimal(userInfo.getBalance()).subtract(new BigDecimal(orderMoney)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); boolean isPrepayFirstStage = isTaxiPrepayFirstStage(orderTaxi); boolean isPrepaySpreadStage = isTaxiPrepaySpreadStage(orderTaxi); if (isPrepayFirstStage) { handleTaxiPrepayFirstPaid(orderTaxi, userInfo, orderMoney, 3); return resultUtil; } OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); userInfo.setIntegral(userInfo.getIntegral() + (orderMoney.intValue() * query1.getIntegral()));//积分 //添加交易明细 transactionDetailsService.saveData(uid, "出租车", orderMoney, 2, 1, 1, 2, orderId); userInfoService.updateById(userInfo); orderTaxi.setState(8); orderTaxi.setPayType(3); orderTaxi.setPayMoney(isPrepaySpreadStage ? appendPayMoney(orderTaxi.getPayMoney(), orderMoney) : orderMoney); orderTaxi.setPayTime(new Date()); if (isPrepaySpreadStage) { orderTaxi.setPrepayStage(5); orderTaxi.setPrepaySecondPayNo(buildBalancePayNo(2, orderId)); } if (!isPrepaySpreadStage) { consumeTaxiBenefits(orderTaxi); } if (Integer.valueOf(2).equals(orderTaxi.getPaymentMode()) || isPrepaySpreadStage) { //添加收入 Map map = incomeService.saveIncome(orderTaxi.getId(), 2, orderTaxi.getOrderMoney()); orderTaxi.setSplitAllocation(JSON.toJSONString(map)); } // TODO: 2020/5/24 这里需要给司机和用户推送订单状态 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); } }).start(); //用户付款后,删除限制司机6分钟不能接单的标识 String vehicle = (String) redisTemplate.opsForValue().get("VEHICLE"); if (ToolUtil.isNotEmpty(vehicle)) { JSONArray jsonArray = JSON.parseArray(vehicle); for (int i = 0; i < jsonArray.size(); i++) { if (jsonArray.getInteger(i).compareTo(orderTaxi.getDriverId()) == 0) { jsonArray.remove(i); break; } } redisTemplate.opsForValue().set("VEHICLE", jsonArray.toJSONString()); } systemNoticeService.addSystemNotice(1, "您已使用余额成功完成出行订单支付,谢谢使用!", uid, 1); } this.updateAllColumnById(orderTaxi); return resultUtil; } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public ResultUtil payTaxiOrder1(Integer payType, Integer orderId, Integer objectId, Integer objectType, Integer type, String path, String ip) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); if (orderTaxi.getState() == 8 || orderTaxi.getState() == 9) { return ResultUtil.error("订单已完成支付,不允许重复支付", ""); } if (orderTaxi.getState() != 7) { return ResultUtil.error("订单不在待支付状态,不允许支付", ""); } if (Integer.valueOf(1).equals(orderTaxi.getPaymentMode()) && Integer.valueOf(4).equals(orderTaxi.getPrepayStage())) { return ResultUtil.error("订单退款处理中,请等待退款完成", ""); } Integer uid = orderTaxi.getUserId(); Double orderMoney = (2 == orderTaxi.getAbnormal() && 2 == orderTaxi.getAbnormalStatus() ? orderTaxi.getResponsibilityMoney().doubleValue() : orderTaxi.getOrderMoney()); UserInfo userInfo = userInfoService.selectById(uid); ResultUtil resultUtil = ResultUtil.success(new Object()); orderTaxi.setCouponMoney(0D);//初始化历史数据 orderTaxi.setCouponId(null); //计算优惠券 UserCouponRecord userCouponRecord = null; if (null != objectId && 1 == objectType) { userCouponRecord = userCouponRecordService.selectById(objectId); if (userCouponRecord.getCompanyId() != orderTaxi.getCompanyId()) { return ResultUtil.error("优惠券不能用于此订单", ""); } if (userCouponRecord.getState() == 2) { return ResultUtil.error("优惠券已使用", ""); } if (userCouponRecord.getState() == 3) { return ResultUtil.error("优惠券已过期", ""); } if (userCouponRecord.getCouponUseType() != 0 && userCouponRecord.getCouponUseType() != 2) { return ResultUtil.error("优惠券不能用于此类型订单", ""); } if (userCouponRecord.getCouponType() == 2 && orderMoney.compareTo(userCouponRecord.getFullMoney()) < 0) { return ResultUtil.error("优惠券不能用于此订单", ""); } orderMoney = orderMoney - userCouponRecord.getMoney(); orderTaxi.setCouponMoney(userCouponRecord.getMoney()); orderTaxi.setCouponId(objectId); } //计算打车卡 UserTaxiCard userTaxiCard = null; if (null != objectId && objectType == 2) { userTaxiCard = userTaxiCardService.selectById(objectId); TaxiCard taxiCard = taxiCardService.selectById(userTaxiCard.getTaxiCardId()); if (taxiCard.getTaxiCardType() == 1 && userTaxiCard.getCompanyId() != orderTaxi.getCompanyId()) { return ResultUtil.error("打车卡不能用于此订单", ""); } if (System.currentTimeMillis() > userTaxiCard.getEndTime().getTime()) { return ResultUtil.error("打车卡已过期", ""); } if (userTaxiCard.getType() == 1 || userTaxiCard.getType() == 3) { Integer time = JSON.parseObject(userTaxiCard.getContent()).getInteger("time"); if (0 == time) { return ResultUtil.error("打车卡已使用完", ""); } } List integers = JSON.parseObject(userTaxiCard.getContent()).getJSONArray("businessTypes").toJavaList(Integer.class); if (!integers.contains(2)) { return ResultUtil.error("打车卡不能用于此类型订单", ""); } Double yh = 0D; JSONObject jsonObject = JSON.parseObject(userTaxiCard.getContent()); if (userTaxiCard.getType() == 1) {//打折次数卡{"businessTypes":[1,2,3],"time":5,"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"],"discount":5} JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); Double discount = jsonObject.getDouble("discount"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { yh = new BigDecimal(orderTaxi.getOrderMoney()).multiply(new BigDecimal((10 - discount) / 10)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); jsonObject.put("time", jsonObject.getInteger("time") - 1); userTaxiCard.setContent(jsonObject.toJSONString()); break; } } } if (userTaxiCard.getType() == 2) {//优惠卡{"businessTypes":[1,2,3],"fullReduction":[[50,3],[100,5],[150,10]]} JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); JSONArray fullReduction = jsonObject.getJSONArray("fullReduction"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { for (int j = fullReduction.size() - 1; j >= 0; j--) { JSONArray jsonArray = fullReduction.getJSONArray(j); Double p = jsonArray.getDouble(0);//满金额 if (orderTaxi.getOrderMoney().compareTo(p) >= 0) { yh = jsonArray.getDouble(1);//优惠金额 break; } } } } } if (userTaxiCard.getType() == 3) {//次数卡{"businessTypes":[1,2,3],"time":1,"discountAmount":10} JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { yh = jsonObject.getDouble("discountAmount"); jsonObject.put("time", jsonObject.getInteger("time") - 1); userTaxiCard.setContent(jsonObject.toJSONString()); } } } if (userTaxiCard.getType() == 4) {//打折天数卡{"businessTypes":[1,2,3],"discount":5,"timeQuantum":["08:00:00 - 09:00:00","17:00:00 - 18:00:00"]} Double discount = jsonObject.getDouble("discount");//折扣 JSONArray timeQuantum = jsonObject.getJSONArray("timeQuantum");//使用时间段 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); for (int i = 0; i < timeQuantum.size(); i++) { String[] split = timeQuantum.getString(i).split(" - "); Date s = sdf1.parse(sdf.format(date) + " " + split[0]); Date e = sdf1.parse(sdf.format(date) + " " + split[1]); if (s.getTime() <= System.currentTimeMillis() && System.currentTimeMillis() < e.getTime()) { yh = new BigDecimal(orderTaxi.getOrderMoney()).multiply(new BigDecimal((10 - discount) / 10)).setScale(2, RoundingMode.HALF_EVEN).doubleValue(); break; } } } orderMoney = orderMoney - yh; orderTaxi.setTaxiCardId(userTaxiCard.getTaxiCardId()); orderTaxi.setUserTaxiCardId(objectId); orderTaxi.setDiscountAmount(yh); } //计算红包 UserRedPacketRecord query = userRedPacketRecordService.query(uid, orderTaxi.getCompanyId(), 1, 2, orderMoney); if (null != query && orderMoney.compareTo(query.getMoney()) > 0) { orderMoney = orderMoney - query.getMoney(); orderTaxi.setRedPacketMoney(query.getMoney()); orderTaxi.setRedPacketId(query.getId()); } //计算折扣 UserActivityDiscount1 query2 = userActivityDiscount1Mapper.query(orderTaxi.getCompanyId()); if (null != query2) { Double taxi = query2.getTaxi(); orderTaxi.setDiscount(taxi); double v = new BigDecimal(orderMoney).multiply(new BigDecimal(taxi / 10)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue(); if (orderMoney.compareTo(v) > 0) { orderTaxi.setDiscountMoney(orderMoney - v); orderTaxi.setActivityId(query2.getId()); orderMoney = v; } } orderMoney = orderMoney < 0 ? 0 : orderMoney; orderMoney = new BigDecimal(orderMoney).setScale(2, RoundingMode.HALF_UP).doubleValue(); ResultUtil prepaySettleResult = settleTaxiPrepayIfNoSecondPay(orderTaxi, userInfo, orderMoney); if (prepaySettleResult != null) { return prepaySettleResult; } orderMoney = getTaxiPrepayFinalPayAmount(orderTaxi, orderMoney); System.out.println("!!!" + orderMoney + "!!!!"); if (payType == 1) {//微信支付 if (orderMoney == 0) { return ResultUtil.error("请使用余额支付"); } String outTradeNo = orderId + "_2_" + UUIDUtil.getRandomCode(5); JSONObject response = cbyzxOrderPayHelper.createOrder(orderTaxi.getUserId(), userInfo.getAppletsOpenId(), outTradeNo, orderMoney); if (!cbyzxOrderPayHelper.isCreateSuccess(response)) { return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response); } String paymentCode = ToolUtil.isNotEmpty(cbyzxOrderPayHelper.extractRecordCode(response)) ? cbyzxOrderPayHelper.extractRecordCode(response) : outTradeNo; resultUtil = ResultUtil.success(response); paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, orderId, 2, 1, orderMoney, paymentCode, 1);//添加预支付数据 } if (payType == 2) {//支付宝支付 if (orderMoney == 0) { return ResultUtil.error("请使用余额支付"); } String outTradeNo = orderId + "_2_" + UUIDUtil.getRandomCode(5); resultUtil = payMoneyUtil.alipay("完成订单", "完成订单", "", outTradeNo, orderMoney.toString(), "/base/aliPayOrderTaxi"); paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, orderId, 2, 2, orderMoney, outTradeNo, 1);//添加预支付数据 } if (payType == 3) {//余额支付 if (userInfo.getBalance() == null || userInfo.getBalance() < orderMoney) { return ResultUtil.error("余额不足,无法完成支付"); } // if(orderMoney>0) { // resultUtil = appOrderController.moneyPay(orderId, userInfo.getId(), orderMoney); // if (resultUtil.getCode() == 500) { // return ResultUtil.error("电子余额不足,无法完成支付"); // } // } userInfo.setBalance(new BigDecimal(userInfo.getBalance()).subtract(new BigDecimal(orderMoney)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); boolean isPrepayFirstStage = isTaxiPrepayFirstStage(orderTaxi); boolean isPrepaySpreadStage = isTaxiPrepaySpreadStage(orderTaxi); if (isPrepayFirstStage) { handleTaxiPrepayFirstPaid(orderTaxi, userInfo, orderMoney, 3); return resultUtil; } OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); if (null != query1) { userInfo.setIntegral(userInfo.getIntegral() + (orderMoney.intValue() * query1.getIntegral()));//积分 } //添加交易明细 transactionDetailsService.saveData(uid, "出租车", orderMoney, 2, 1, 1, 2, orderId); userInfoService.updateById(userInfo); orderTaxi.setState(8); orderTaxi.setPayType(3); orderTaxi.setPayMoney(isPrepaySpreadStage ? appendPayMoney(orderTaxi.getPayMoney(), orderMoney) : orderMoney); orderTaxi.setPayTime(new Date()); if (isPrepaySpreadStage) { orderTaxi.setPrepayStage(5); orderTaxi.setPrepaySecondPayNo(buildBalancePayNo(2, orderId)); } if (!isPrepaySpreadStage) { consumeTaxiBenefits(orderTaxi); } //非追缴单才添加收入记录 if(0 == orderTaxi.getRecoveryOrder() && (Integer.valueOf(2).equals(orderTaxi.getPaymentMode()) || isPrepaySpreadStage)){ //添加收入 Double orderMoney1 = (2 == orderTaxi.getAbnormal() && 2 == orderTaxi.getAbnormalStatus() ? orderTaxi.getResponsibilityMoney().doubleValue() : orderTaxi.getOrderMoney()); Map map = incomeService.saveIncome(orderTaxi.getId(), 2, orderTaxi.getOrderMoney()); orderTaxi.setSplitAllocation(JSON.toJSONString(map)); } //待审核的异常单修改状态为已关闭 if(2 == orderTaxi.getAbnormal() && 1 == orderTaxi.getAbnormalStatus()){ orderTaxi.setAbnormalStatus(3); orderTaxi.setResponsibilityMoney(new BigDecimal(orderTaxi.getOrderMoney())); orderTaxi.setResponsibilityType(3); orderTaxi.setAbnormalRemark("乘客已支付订单,申诉已自动关闭"); } this.updateAllColumnById(orderTaxi); promotion(orderTaxi.getId()); // TODO: 2020/5/24 这里需要给司机和用户推送订单状态 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); } }).start(); //用户付款后,删除限制司机6分钟不能接单的标识 String vehicle = (String) redisTemplate.opsForValue().get("VEHICLE"); if (ToolUtil.isNotEmpty(vehicle)) { JSONArray jsonArray = JSON.parseArray(vehicle); for (int i = 0; i < jsonArray.size(); i++) { if (jsonArray.getInteger(i).compareTo(orderTaxi.getDriverId()) == 0) { jsonArray.remove(i); break; } } redisTemplate.opsForValue().set("VEHICLE", jsonArray.toJSONString()); } systemNoticeService.addSystemNotice(1, "您已使用余额成功完成出行订单支付,谢谢使用!", uid, 1); } else if (payType == 4) { if (orderMoney == 0) { return ResultUtil.error("请使用余额支付"); } orderTaxi.setPayTime(new Date()); Double payMoney = orderTaxi.getOrderMoney(); Integer integer = paymentRecordService.saveData(1, orderTaxi.getUserId(), 1, orderId, 2, 4, orderMoney, "", 1); resultUtil = appOrderController.placeAnOrder(new BigDecimal(orderMoney), 4, orderId, 9, integer); } if(payType!=3){ this.updateAllColumnById(orderTaxi); } return resultUtil; } @Autowired private AppOrderController appOrderController; /** * 手动完成订单操作 * * @param orderId * @param orderType * @return * @throws Exception */ @Override public ResultUtil completeOrder(Integer orderId, Integer orderType) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); if (orderTaxi.getState() != 7) { return ResultUtil.error("订单不在待支付中,无法完成订单"); } orderTaxi.setPayManner(2);//其他方式支付 UserInfo userInfo = userInfoService.selectById(orderTaxi.getUserId()); ResultUtil prepaySettleResult = settleTaxiPrepayIfNoSecondPay(orderTaxi, userInfo, orderTaxi.getOrderMoney()); if (prepaySettleResult != null) { return prepaySettleResult; } // orderTaxi.setOrderMoney(0D); // orderTaxi.setTravelMoney(0D); // orderTaxi.setParkMoney(0D); // orderTaxi.setRoadTollMoney(0D); orderTaxi.setRedPacketMoney(0D); orderTaxi.setCouponMoney(0D); orderTaxi.setDiscount(0D); orderTaxi.setDiscountMoney(0D); orderTaxi.setPayMoney(orderTaxi.getOrderMoney()); orderTaxi.setState(8); orderTaxi.setPayTime(new Date()); this.updateById(orderTaxi); new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); } }).start(); return ResultUtil.success(); } /** * 获取用户的订单列表 * * @param uid * @param pageNum * @param size * @return * @throws Exception */ @Override public List> queryMyOrderList(Integer uid, Integer pageNum, Integer size) throws Exception { pageNum = (pageNum - 1) * size; List> maps = orderTaxiMapper.queryMyOrderList(uid, pageNum, size); for (Map map : maps) { if (Integer.valueOf(String.valueOf(map.get("state"))) == 11) { map.put("state", map.get("oldState")); } } return maps; } /** * 获取历史消费记录 * * @param uid * @return * @throws Exception */ @Override public List> queryMyTravelRecord(Integer uid) throws Exception { return orderTaxiMapper.queryMyTravelRecord(uid); } /** * 获取红包使用记录 * * @param uid * @return * @throws Exception */ @Override public List> queryRedEnvelope(Integer uid) throws Exception { return orderTaxiMapper.queryRedEnvelope(uid); } /** * 获取用户开发票页面的订单列表 * * @param type 开票类型 1=未开票 2=已开票 * @param startTime 订单开始时间 * @param endTime 订单结束时间 * @param startMoney 订单金额范围 * @param endMoney * @param uid * @return * @throws Exception */ @Override public List> queryInvoiceOrder(Integer type, Date startTime, Date endTime, Double startMoney, Double endMoney, Integer uid) throws Exception { startTime = dateUtil.getStartOrEndDate(startTime, "start"); endTime = dateUtil.getStartOrEndDate(endTime, "end"); return orderTaxiMapper.queryInvoiceOrder(type, startTime, endTime, startMoney, endMoney, uid); } /** * 获取订单详情 * * @param orderId * @return */ @Override public Map queryOrderInfo(Integer orderId) throws Exception { Map map = orderTaxiMapper.queryOrderInfo(orderId); if (null != map && null != map.get("reassignNotice") && Integer.valueOf(String.valueOf(map.get("reassignNotice"))) == 2) {//如果订单有改派提醒,则查询后重置为未提醒 OrderTaxi orderTaxi = this.selectById(orderId); orderTaxi.setReassignNotice(0); this.updateById(orderTaxi); } if (Integer.valueOf(String.valueOf(map.get("state"))) == 11) { map.put("state", map.get("oldState")); } //接口数据初始化为0 map.put("appealStatus", 0); String driverId = (String) redisTemplate.opsForValue().get("DEVICE_" + map.get("driverId")); map.put("device", ToolUtil.isNotEmpty(driverId) ? 2 : 1); map.put("orderType", 2); return map; } /** * 获取下单推送完成后没有司机下单的提醒 * * @return * @throws Exception */ @Override public EndPushWarpper queryEndPush(Integer uid) throws Exception { List list = orderTaxiMapper.queryByState(uid, 1); EndPushWarpper endPushWarpper = new EndPushWarpper(); if (list.size() > 0) { OrderTaxi orderTaxi = list.get(0); if (!orderIds.contains(orderTaxi.getId())) { endPushWarpper.setOrderId(orderTaxi.getId()); endPushWarpper.setOrderType(2); endPushWarpper.setState(1); OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); List querys = pushOrderService.querys(null, 2, openCity.getId());//查询推单配置 int time = 0; for (int i = 1; i <= querys.size() + 15; i++) { int finalI = i; PushOrder pushOrder = querys.stream().filter(s -> s.getType() == (finalI <= 3 ? finalI : 3)).findFirst().orElse(null); time += pushOrder.getPushTime() * 1000; } //当前时间减去推单总时间大于下单时间 if ((System.currentTimeMillis() - time) > orderTaxi.getInsertTime().getTime()) { endPushWarpper.setState(2); } } } return endPushWarpper; } /** * 获取服务中的订单数据 * * @param uid * @return * @throws Exception */ @Override public OrderServerWarpper queryOrderServer(Integer orderId, Integer uid) throws Exception { OrderServerWarpper orderServerWarpper = new OrderServerWarpper(); OrderTaxi orderTaxi = this.selectById(orderId); if (null == orderTaxi) { return orderServerWarpper; } //计算预计距离和剩余时间 String value = null; if (null != orderTaxi.getDriverId()) { value = (String) redisTemplate.opsForValue().get("dache:DRIVER" + orderTaxi.getDriverId()); if (null == value || "".equals(value)) { System.err.println("司机没有上传位置信息"); //调用获取轨迹中的数据 List> list = orderPositionService.queryTrack(orderId, 2); if (list.size() > 0) { Map map = list.get(list.size() - 1); value = map.get("lon") + "," + map.get("lat"); } } } orderServerWarpper.setOrderId(orderTaxi.getId()); orderServerWarpper.setOrderType(2); orderServerWarpper.setState(orderTaxi.getState()); orderServerWarpper.setLon(null != value ? value.split(",")[0] : "0.0"); orderServerWarpper.setLat(null != value ? value.split(",")[1] : "0.0"); orderServerWarpper.setReassignNotice(orderTaxi.getReassignNotice()); if (orderTaxi.getState() == 2 || orderTaxi.getState() == 3) {//已接单或已出发 // TODO: 2023/11/4 无法修改 Map distance = gdMapElectricFenceUtil.getDistance(value, orderTaxi.getStartLon() + "," + orderTaxi.getStartLat(), 1); String d = "0"; String t = "0"; if (null == distance) { System.err.println("查询距离出错了"); } else { d = new BigDecimal(distance.get("distance")).divide(new BigDecimal(1000), new MathContext(2, RoundingMode.HALF_EVEN)).toString(); t = new BigDecimal(distance.get("duration")).divide(new BigDecimal(60), new MathContext(2, RoundingMode.HALF_EVEN)).intValue() + ""; } orderServerWarpper.setReservationMileage(d); orderServerWarpper.setReservationTime(t); orderServerWarpper.setServedMileage("0"); orderServerWarpper.setServedTime("0"); orderServerWarpper.setLaveMileage("0"); orderServerWarpper.setLaveTime("0"); } if (orderTaxi.getState() == 5 || orderTaxi.getState() == 6) {//服务中或已到达 // TODO: 2023/11/4 无法修改 Map distance = gdMapElectricFenceUtil.getDistance(value, orderTaxi.getEndLon() + "," + orderTaxi.getEndLat(), 1); String d = "0"; String t = "0"; if (null == distance) { System.err.println("查询距离出错了"); } else { d = new BigDecimal(distance.get("distance")).divide(new BigDecimal(1000), new MathContext(2, RoundingMode.HALF_EVEN)).toString(); t = new BigDecimal(distance.get("duration")).divide(new BigDecimal(60), new MathContext(2, RoundingMode.HALF_EVEN)).intValue() + ""; } orderServerWarpper.setReservationMileage("0"); orderServerWarpper.setReservationTime("0"); orderServerWarpper.setServedMileage(String.valueOf(orderTaxi.getMileage() / 1000)); orderServerWarpper.setServedTime(Long.valueOf((new Date().getTime() - orderTaxi.getStartServiceTime().getTime()) / 60000).intValue() + ""); orderServerWarpper.setLaveMileage(d); orderServerWarpper.setLaveTime(t); } return orderServerWarpper; } /** * 评论成功后获取红包金额 * * @param orderId * @return * @throws Exception */ @Override public synchronized ResultUtil queryRedMoney(Integer orderId) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); Integer companyId = orderTaxi.getCompanyId(); Map query = userActivityRedenvelopeService.query(companyId, orderTaxi.getTravelTime()); Double money = 0D; BaseWarpper baseWarpper = new BaseWarpper(); if (null != query) { Integer type = Integer.valueOf(String.valueOf(query.get("type"))); if (type == 1) {//固定金额 money = Double.valueOf(String.valueOf(query.get("money"))); } else {//随机金额 Double startMoney = Double.valueOf(String.valueOf(query.get("startMoney"))); Double endMoney = Double.valueOf(String.valueOf(query.get("endMoney"))); int i = new BigDecimal(endMoney).subtract(new BigDecimal(startMoney)).intValue(); Random random = new Random(); int num = random.nextInt(i); money = new BigDecimal(startMoney).add(new BigDecimal(num)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue(); } //判断当前红包是否大于剩余可领取总金额 if (money.compareTo(Double.valueOf(query.get("lavePrice").toString())) > 0) { baseWarpper.setAmount(0D); return ResultUtil.success(baseWarpper); } } baseWarpper.setAmount(money); if (money > 0) { //添加临时红包数据 UserRedPacketRecord userRedPacketRecord = new UserRedPacketRecord(); userRedPacketRecord.setMoney(money); Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + Integer.valueOf(String.valueOf(query.get("effective")))); userRedPacketRecord.setExpirationTime(calendar.getTime()); userRedPacketRecord.setInsertTime(new Date()); userRedPacketRecord.setCompanyId(Integer.valueOf(String.valueOf(query.get("companyId")))); userRedPacketRecord.setState(0); userRedPacketRecord.setOrderId(orderTaxi.getId()); userRedPacketRecord.setOrderType(2); userRedPacketRecord.setUserId(orderTaxi.getUserId()); userRedPacketRecordService.insert(userRedPacketRecord); } // appOrderController.moneyPay(orderTaxi.getId(),orderTaxi.getUserId(),money); return ResultUtil.success(baseWarpper); } /** * 分享红包活动 * * @param orderId * @return * @throws Exception */ @Override public synchronized ResultUtil shareRedEnvelope(Integer orderId) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); UserRedPacketRecord query = userRedPacketRecordService.query_(orderTaxi.getUserId(), orderTaxi.getCompanyId(), 0, 2, null); if (null != query) { Double money = query.getMoney(); Map map = userActivityRedenvelopeService.query(orderTaxi.getCompanyId(), orderTaxi.getTravelTime()); Double laveMoney = Double.valueOf(String.valueOf(map.get("laveMoney"))); if (money.compareTo(laveMoney) > 0) { return ResultUtil.error("手速太慢了,红包已派发完啦!"); } //判断当前红包是否大于剩余可领取总金额 if (money.compareTo(Double.valueOf(map.get("lavePrice").toString())) > 0) { return ResultUtil.error("手速太慢了,红包已派发完啦!"); } double v = new BigDecimal(laveMoney).subtract(new BigDecimal(money)).doubleValue(); UserActivityRedenvelope id = userActivityRedenvelopeService.selectById(String.valueOf(map.get("id"))); id.setLaveMoney(v); id.setLavePrice(new BigDecimal(id.getLavePrice() - money).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); userActivityRedenvelopeService.updateById(id); query.setState(1); query.setRedPacketActivityId(id.getId()); userRedPacketRecordService.updateById(query); } return ResultUtil.success(); } private boolean isTaxiPrepayFirstStage(OrderTaxi orderTaxi) { return orderTaxi != null && Integer.valueOf(1).equals(orderTaxi.getPaymentMode()) && Integer.valueOf(1).equals(orderTaxi.getPrepayStage()); } private boolean isTaxiPrepaySpreadStage(OrderTaxi orderTaxi) { return orderTaxi != null && Integer.valueOf(1).equals(orderTaxi.getPaymentMode()) && Integer.valueOf(3).equals(orderTaxi.getPrepayStage()); } private String buildBalancePayNo(Integer orderType, Integer orderId) { return "BAL_" + orderType + "_" + orderId + "_" + System.currentTimeMillis(); } private Double appendPayMoney(Double source, Double amount) { return new BigDecimal(source == null ? 0D : source) .add(new BigDecimal(amount == null ? 0D : amount)) .setScale(2, BigDecimal.ROUND_HALF_EVEN) .doubleValue(); } private boolean isTaxiPrepayFinalStage(OrderTaxi orderTaxi) { return orderTaxi != null && Integer.valueOf(1).equals(orderTaxi.getPaymentMode()) && !Integer.valueOf(5).equals(orderTaxi.getPrepayStage()) && orderTaxi.getPayMoney() != null && orderTaxi.getPayMoney() > 0; } private BigDecimal toMoney(Double amount) { return new BigDecimal(String.valueOf(amount == null ? 0D : amount)).setScale(2, RoundingMode.HALF_UP); } private Double getTaxiPrepayFinalPayAmount(OrderTaxi orderTaxi, Double finalAmount) { if (!isTaxiPrepayFinalStage(orderTaxi)) { return toMoney(finalAmount).doubleValue(); } BigDecimal spreadAmount = toMoney(finalAmount).subtract(toMoney(orderTaxi.getPayMoney())).setScale(2, RoundingMode.HALF_UP); if (spreadAmount.compareTo(BigDecimal.ZERO) > 0) { orderTaxi.setPrepayStage(3); return spreadAmount.doubleValue(); } return 0D; } private ResultUtil settleTaxiPrepayIfNoSecondPay(OrderTaxi orderTaxi, UserInfo userInfo, Double finalAmount) throws Exception { if (!isTaxiPrepayFinalStage(orderTaxi)) { return null; } BigDecimal paidAmount = toMoney(orderTaxi.getPayMoney()); BigDecimal settleAmount = toMoney(finalAmount); BigDecimal refundAmount = paidAmount.subtract(settleAmount).setScale(2, RoundingMode.HALF_UP); if (refundAmount.compareTo(BigDecimal.ZERO) < 0) { return null; } if (refundAmount.compareTo(BigDecimal.ZERO) > 0) { ResultUtil refundResult = refundTaxiPrepayDifference(orderTaxi, userInfo, refundAmount.doubleValue()); if (!ResultUtil.SUCCESS.equals(refundResult.getCode())) { return refundResult; } } finishTaxiPrepayOrder(orderTaxi, settleAmount.doubleValue()); return ResultUtil.success(); } private ResultUtil refundTaxiPrepayDifference(OrderTaxi orderTaxi, UserInfo userInfo, Double refundAmount) throws Exception { if (Integer.valueOf(3).equals(orderTaxi.getPayType())) { userInfo.setBalance(new BigDecimal(null != userInfo.getBalance() ? userInfo.getBalance() : 0D) .add(toMoney(refundAmount)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); userInfoService.updateById(userInfo); orderTaxi.setPrepayRefundNo("BALANCE_REFUND_2_" + orderTaxi.getId() + "_" + ToolUtil.getRandomString(5)); orderTaxi.setPrepayRefundAmount(refundAmount); orderTaxi.setPrepayRefundTime(new Date()); transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车先付订单退款", refundAmount, 1, 1, 1, 2, orderTaxi.getId()); return ResultUtil.success(); } PaymentRecord paymentRecord = paymentRecordService.query(1, orderTaxi.getUserId(), 1, orderTaxi.getId(), 2, orderTaxi.getPayType(), 2); if (paymentRecord == null) { return ResultUtil.error("先付订单缺少已支付流水,无法退款"); } if (Integer.valueOf(1).equals(orderTaxi.getPayType())) { CbyzxPayUtil.ClosePayOrderRequest request = new CbyzxPayUtil.ClosePayOrderRequest(); request.setOutRequestNo(ToolUtil.isNotEmpty(orderTaxi.getPrepaySecondPayNo()) ? orderTaxi.getPrepaySecondPayNo() : paymentRecord.getCode()); request.setRefundOutRequestNo("PREPAY_DIFF_REFUND_2_" + orderTaxi.getId() + ToolUtil.getRandomString(5)); request.setRefundAmount(toFen(refundAmount)); request.setRefundDesc("出租车先付订单多退少补退款"); JSONObject response = CbyzxPayUtil.closePayOrder(request); if (!isTaxiPrepayRefundSuccess(response)) { return ResultUtil.error(extractTaxiRefundMessage(response), response); } orderTaxi.setPrepayRefundNo(extractTaxiRefundNo(response)); orderTaxi.setPrepayRefundAmount(refundAmount); orderTaxi.setPrepayRefundTime(new Date()); transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车先付订单退款", refundAmount, 1, 1, 1, 2, orderTaxi.getId()); return ResultUtil.success(response); } if (Integer.valueOf(2).equals(orderTaxi.getPayType())) { Map map = payMoneyUtil.aliRefund(paymentRecord.getCode(), refundAmount.toString()); if (!"10000".equals(map.get("code"))) { return ResultUtil.error(map.get("msg")); } orderTaxi.setPrepayRefundNo(map.get("trade_no")); orderTaxi.setPrepayRefundAmount(refundAmount); orderTaxi.setPrepayRefundTime(new Date()); transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车先付订单退款", refundAmount, 1, 1, 1, 2, orderTaxi.getId()); return ResultUtil.success(map); } return ResultUtil.error("先付订单支付方式不支持退款"); } private void finishTaxiPrepayOrder(OrderTaxi orderTaxi, Double settleAmount) throws Exception { orderTaxi.setState(8); orderTaxi.setPayMoney(settleAmount); orderTaxi.setPayTime(new Date()); orderTaxi.setPrepayStage(5); if (0 == orderTaxi.getRecoveryOrder()) { Double incomeAmount = (2 == orderTaxi.getAbnormal() && 2 == orderTaxi.getAbnormalStatus() ? orderTaxi.getResponsibilityMoney().doubleValue() : orderTaxi.getOrderMoney()); Map map = incomeService.saveIncome(orderTaxi.getId(), 2, incomeAmount); orderTaxi.setSplitAllocation(JSON.toJSONString(map)); } this.updateAllColumnById(orderTaxi); promotion(orderTaxi.getId()); new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); } }).start(); systemNoticeService.addSystemNotice(1, "您的出租车先付订单已完成结算,请注意查收。", orderTaxi.getUserId(), 1); } private void consumeTaxiBenefits(OrderTaxi orderTaxi) throws Exception { if (null != orderTaxi.getCouponId()) { UserCouponRecord userCouponRecord = userCouponRecordService.selectById(orderTaxi.getCouponId()); if (userCouponRecord != null) { userCouponRecord.setState(2); userCouponRecord.setEndTime(new Date()); userCouponRecordService.updateById(userCouponRecord); } } if (null != orderTaxi.getUserTaxiCardId()) { UserTaxiCard userTaxiCard = userTaxiCardService.selectById(orderTaxi.getUserTaxiCardId()); if (userTaxiCard != null && (userTaxiCard.getType() == 1 || userTaxiCard.getType() == 3)) { JSONObject jsonObject = JSON.parseObject(userTaxiCard.getContent()); jsonObject.put("time", jsonObject.getInteger("time") - 1); userTaxiCard.setContent(jsonObject.toJSONString()); userTaxiCardService.updateById(userTaxiCard); } } if (null != orderTaxi.getRedPacketId()) { UserRedPacketRecord userRedPacketRecord = userRedPacketRecordService.selectById(orderTaxi.getRedPacketId()); if (userRedPacketRecord != null) { userRedPacketRecord.setState(2); userRedPacketRecord.setEndTime(new Date()); userRedPacketRecordService.updateById(userRedPacketRecord); } } } private void restoreTaxiBenefits(OrderTaxi orderTaxi) throws Exception { if (null != orderTaxi.getCouponId()) { UserCouponRecord userCouponRecord = userCouponRecordService.selectById(orderTaxi.getCouponId()); if (userCouponRecord != null) { userCouponRecord.setState(1); userCouponRecord.setEndTime(null); userCouponRecordService.updateById(userCouponRecord); } } if (null != orderTaxi.getUserTaxiCardId()) { UserTaxiCard userTaxiCard = userTaxiCardService.selectById(orderTaxi.getUserTaxiCardId()); if (userTaxiCard != null && (userTaxiCard.getType() == 1 || userTaxiCard.getType() == 3)) { JSONObject jsonObject = JSON.parseObject(userTaxiCard.getContent()); Integer time = jsonObject.getInteger("time"); jsonObject.put("time", (time == null ? 0 : time) + 1); userTaxiCard.setContent(jsonObject.toJSONString()); userTaxiCardService.updateById(userTaxiCard); } } if (null != orderTaxi.getRedPacketId()) { UserRedPacketRecord userRedPacketRecord = userRedPacketRecordService.selectById(orderTaxi.getRedPacketId()); if (userRedPacketRecord != null) { userRedPacketRecord.setState(1); userRedPacketRecord.setEndTime(null); userRedPacketRecordService.updateById(userRedPacketRecord); } } } private boolean isTaxiPrepayRefundSuccess(JSONObject response) { if (response == null) { return false; } Object code = response.get("code"); if (code == null || !"0".equals(String.valueOf(code))) { return false; } JSONObject data = response.getJSONObject("data"); return data != null && Boolean.TRUE.equals(data.getBoolean("isSuccess")); } private String extractTaxiRefundNo(JSONObject response) { if (response == null) { return null; } JSONObject data = response.getJSONObject("data"); if (data == null) { return null; } String refundNo = data.getString("merchantRefundSerialNo"); if (ToolUtil.isNotEmpty(refundNo)) { return refundNo; } refundNo = data.getString("refundId"); if (ToolUtil.isNotEmpty(refundNo)) { return refundNo; } return data.getString("gatewaySerialNo"); } private String extractTaxiRefundMessage(JSONObject response) { if (response == null) { return "\u5fae\u4fe1\u5148\u4ed8\u9000\u6b3e\u5931\u8d25"; } JSONObject data = response.getJSONObject("data"); if (data != null && ToolUtil.isNotEmpty(data.getString("failReason"))) { return data.getString("failReason"); } String msg = response.getString("msg"); return ToolUtil.isNotEmpty(msg) ? msg : "\u5fae\u4fe1\u5148\u4ed8\u9000\u6b3e\u5931\u8d25"; } private Integer toFen(Double amount) { return new BigDecimal(String.valueOf(amount)).multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).intValue(); } private String buildPrepayRefundOutNo(Integer orderId) { return "PREPAY_REFUND_2_" + orderId+ ToolUtil.getRandomString(5); } private ResultUtil handleTaxiPrepayCancelRefund(OrderTaxi orderTaxi, String reason, String remark, Integer uid) throws Exception { System.out.println("出租车退款!!!!"); if (orderTaxi == null || !Integer.valueOf(1).equals(orderTaxi.getPaymentMode())) { return null; } if (Integer.valueOf(3).equals(orderTaxi.getPayType())) { Double refundAmount = orderTaxi.getPayMoney(); if (refundAmount == null || refundAmount <= 0) { return ResultUtil.error("余额先付订单退款金额异常"); } UserInfo userInfo = userInfoService.selectById(orderTaxi.getUserId()); if (userInfo == null) { return ResultUtil.error("用户信息不存在,无法退款"); } userInfo.setBalance(new BigDecimal(null != userInfo.getBalance() ? userInfo.getBalance() : 0) .add(new BigDecimal(refundAmount)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); userInfoService.updateById(userInfo); restoreTaxiBenefits(orderTaxi); transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车取消订单退款", refundAmount, 1, 1, 1, 2, orderTaxi.getId()); orderCancelService.saveData(orderTaxi.getId(), 2, ToolUtil.isNotEmpty(reason) ? reason : "无司机接单", ToolUtil.isNotEmpty(remark) ? remark : (ToolUtil.isNotEmpty(reason) ? reason : "无司机接单"), 1, refundAmount, 2, 1, uid); orderTaxi.setState(10); orderTaxi.setPrepayStage(5); orderTaxi.setPrepayRefundNo("BALANCE_REFUND_2_" + orderTaxi.getId() + "_" + ToolUtil.getRandomString(5)); orderTaxi.setPrepayRefundAmount(refundAmount); orderTaxi.setPrepayRefundTime(new Date()); this.updateById(orderTaxi); if (orderTaxi.getDriverId() != null) { this.deleteTask(orderTaxi.getId()); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); Driver driver = driverService.selectById(orderTaxi.getDriverId()); if (driver != null) { driver.setState(2); driverService.updateById(driver); } if (orderTaxi.getBindId() != null) { chinaMobileUtil.midAxbUnBindSend(orderTaxi.getBindId(), orderTaxi.getTelX(), (System.currentTimeMillis() + 600000)); } } systemNoticeService.addSystemNotice(1, "您的出租车余额先付订单已取消,退款已退回账户余额,请注意查收。", orderTaxi.getUserId(), 1); return ResultUtil.success(); } String outRequestNo = orderTaxi.getPrepaySecondPayNo(); if (ToolUtil.isEmpty(outRequestNo)) { return ResultUtil.error("微信先付订单缺少支付单号,无法关闭支付单"); } Double refundAmount = orderTaxi.getPayMoney(); if (refundAmount == null || refundAmount <= 0) { return ResultUtil.error("微信先付订单退款金额异常"); } CbyzxPayUtil.ClosePayOrderRequest request = new CbyzxPayUtil.ClosePayOrderRequest(); request.setOutRequestNo(outRequestNo); request.setRefundOutRequestNo(buildPrepayRefundOutNo(orderTaxi.getId())); request.setRefundAmount(toFen(refundAmount)); request.setRefundDesc(ToolUtil.isNotEmpty(reason) ? reason : "出租车订单取消退款"); JSONObject response = CbyzxPayUtil.closePayOrder(request); System.out.println("微信先付订单退款结果:" + response.toJSONString()); if (!isTaxiPrepayRefundSuccess(response)) { return ResultUtil.error(extractTaxiRefundMessage(response), response); } restoreTaxiBenefits(orderTaxi); transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车取消订单退款", refundAmount, 1, 1, 1, 2, orderTaxi.getId()); orderCancelService.saveData(orderTaxi.getId(), 2, ToolUtil.isNotEmpty(reason) ? reason : "无司机接单", ToolUtil.isNotEmpty(remark) ? remark : (ToolUtil.isNotEmpty(reason) ? reason : "无司机接单"), 1, refundAmount, 2, 1, uid); orderTaxi.setState(10); orderTaxi.setPrepayStage(5); orderTaxi.setPrepayRefundNo(extractTaxiRefundNo(response)); orderTaxi.setPrepayRefundAmount(refundAmount); orderTaxi.setPrepayRefundTime(new Date()); this.updateById(orderTaxi); if (orderTaxi.getDriverId() != null) { this.deleteTask(orderTaxi.getId()); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); Driver driver = driverService.selectById(orderTaxi.getDriverId()); if (driver != null) { driver.setState(2); driverService.updateById(driver); } if (orderTaxi.getBindId() != null) { chinaMobileUtil.midAxbUnBindSend(orderTaxi.getBindId(), orderTaxi.getTelX(), (System.currentTimeMillis() + 600000)); } } systemNoticeService.addSystemNotice(1, "您的出租车微信先付订单已取消,退款已原路退回,请注意查收。", orderTaxi.getUserId(), 1); return ResultUtil.success(response); } private void handleTaxiPrepayFirstPaid(OrderTaxi orderTaxi, UserInfo userInfo, Double payAmount, Integer payType) throws Exception { OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); if (null != query1) { userInfo.setIntegral(userInfo.getIntegral() + (payAmount.intValue() * query1.getIntegral())); } userInfoService.updateById(userInfo); consumeTaxiBenefits(orderTaxi); transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车", payAmount, 2, 1, 1, 2, orderTaxi.getId()); orderTaxi.setState(1); orderTaxi.setPayType(payType); orderTaxi.setPayMoney(payAmount); orderTaxi.setPayTime(new Date()); orderTaxi.setPrepayStage(2); this.updateAllColumnById(orderTaxi); pushUtil.pushOrderState(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); systemNoticeService.addSystemNotice(1, "您的出租车订单已支付成功,我们正在为您指派司机,请稍后!", orderTaxi.getUserId(), 1); this.pushOrder(orderTaxi, 1); } /** * 获取订单数据 * * @param uid * @param state * @return * @throws Exception */ @Override public List queryOrder(Integer uid, Integer... state) throws Exception { List list = orderTaxiMapper.queryByState(uid, state); return list; } /** * 订单支付完成后的处理 * * @param id 订单id * @param order_id 支付订单号 * @param type 1=微信,2=支付宝 * @throws Exception */ @Override public void payOrderTaxiCallback(Integer id, String order_id, Integer type, Integer paymentId, String outTradeNo) throws Exception { OrderTaxi orderTaxi = this.selectById(id); PaymentRecord query = ToolUtil.isNotEmpty(outTradeNo) ? paymentRecordService.queryByCode(outTradeNo, 1) : null; if (query == null) { query = paymentRecordService.query(1, orderTaxi.getUserId(), 1, Integer.valueOf(id), 2, type, 1); } if (null != query && query.getState() == 1) { UserInfo userInfo = userInfoService.selectById(orderTaxi.getUserId()); query.setState(2); query.setCode(order_id); paymentRecordService.updateById(query); if (isTaxiPrepayFirstStage(orderTaxi)) { orderTaxi.setPrepaySecondPayNo(outTradeNo); handleTaxiPrepayFirstPaid(orderTaxi, userInfo, query.getAmount(), type); return; } //添加交易明细 transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车", query.getAmount(), 2, 1, 1, 2, query.getOrderId()); orderTaxi.setState(8); orderTaxi.setPayType(type); boolean isPrepaySpreadStage = isTaxiPrepaySpreadStage(orderTaxi); orderTaxi.setPayMoney(isPrepaySpreadStage ? appendPayMoney(orderTaxi.getPayMoney(), query.getAmount()) : query.getAmount()); orderTaxi.setPayTime(new Date()); if (isPrepaySpreadStage) { orderTaxi.setPrepayStage(5); orderTaxi.setPrepaySecondPayNo(order_id); } OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); if(null != query1){ userInfo.setIntegral(userInfo.getIntegral() + (query.getAmount().intValue() * query1.getIntegral()));//绉垎 userInfoService.updateById(userInfo); } if (!isPrepaySpreadStage) { consumeTaxiBenefits(orderTaxi); } //非追缴单才添加收入记录 if(0 == orderTaxi.getRecoveryOrder() && (Integer.valueOf(2).equals(orderTaxi.getPaymentMode()) || Integer.valueOf(5).equals(orderTaxi.getPrepayStage()))){ //添加收入 Double orderMoney1 = (2 == orderTaxi.getAbnormal() && 2 == orderTaxi.getAbnormalStatus() ? orderTaxi.getResponsibilityMoney().doubleValue() : orderTaxi.getOrderMoney()); Map map = incomeService.saveIncome(orderTaxi.getId(), 2, orderMoney1); orderTaxi.setSplitAllocation(JSON.toJSONString(map)); } //待审核的异常单修改状态为已关闭 if(2 == orderTaxi.getAbnormal() && 1 == orderTaxi.getAbnormalStatus()){ orderTaxi.setAbnormalStatus(3); orderTaxi.setResponsibilityMoney(new BigDecimal(orderTaxi.getOrderMoney())); orderTaxi.setResponsibilityType(3); orderTaxi.setAbnormalRemark("乘客已支付订单,申诉已自动关闭"); } this.updateById(orderTaxi); // TODO: 2020/5/24 这里需要给司机和用户推送订单状态 new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); } }).start(); //用户付款后,删除限制司机6分钟不能接单的标识 String vehicle = (String) redisTemplate.opsForValue().get("VEHICLE"); if (ToolUtil.isNotEmpty(vehicle)) { JSONArray jsonArray = JSON.parseArray(vehicle); for (int i = 0; i < jsonArray.size(); i++) { if (jsonArray.getInteger(i).compareTo(orderTaxi.getDriverId()) == 0) { jsonArray.remove(i); break; } } redisTemplate.opsForValue().set("VEHICLE", jsonArray.toJSONString()); } systemNoticeService.addSystemNotice(1, "您已使用" + (type == 1 ? "微信" : (type == 2 ? "支付宝" : "云闪付")) + "成功完成出行订单支付,谢谢使用!", orderTaxi.getUserId(), 1); } else { System.err.println("预支付数据异常(orderId = " + id + ")"); } } /** * 取消订单支付后的处理 * * @param id 订单id * @param order_id 支付订单号 * @param type 1=微信,2=支付宝 * @throws Exception */ @Override public void payCancelOrderTaxi(Integer id, String order_id, Integer type) throws Exception { OrderTaxi orderTaxi = this.selectById(id); PaymentRecord query = paymentRecordService.query(1, orderTaxi.getUserId(), 1, Integer.valueOf(id), 2, type, 1); if (null != query) { //添加交易明细 transactionDetailsService.saveData(orderTaxi.getUserId(), "出租车取消订单", query.getAmount(), 2, 1, 1, 2, query.getOrderId()); orderTaxi.setState(10); //解除小号绑定 if (orderTaxi.getBindId() != null) { chinaMobileUtil.midAxbUnBindSend(orderTaxi.getBindId(), orderTaxi.getTelX(), (System.currentTimeMillis() + 600000)); } orderTaxi.setBindId(""); orderTaxi.setTelX(""); this.updateById(orderTaxi); query.setState(2); query.setCode(order_id); paymentRecordService.updateById(query); OrderCancel query1 = orderCancelService.query(query.getOrderId(), query.getOrderType(), query.getAmount(), query.getPayType(), 1); if (null != query1) { query1.setState(2); orderCancelService.updateById(query1); } //添加已收入明细 incomeService.saveData(1, orderTaxi.getCompanyId(), 3, orderTaxi.getId(), 2, query.getAmount()); this.deleteTask(orderTaxi.getId());//删除定时任务 // TODO: 2020/5/24 这里需要给司机和用户推送订单状态 // new Thread(new Runnable() { // @Override // public void run() { // pushUtil.pushOrderState(2, orderTaxi.getDriverId(), orderTaxi.getId(), 2, orderTaxi.getState(), 0); // } // }).start(); //添加消息 systemNoticeService.addSystemNotice(1, "您已使用" + (type == 1 ? "微信" : (type == 2 ? "支付宝" : "云闪付")) + "成功支付取消订单费用,谢谢使用!", orderTaxi.getUserId(), 1); } else { System.err.println("预支付数据异常(orderId = " + id + ")"); } } /** * 推送订单给司机抢单 * * @param orderTaxi * @throws Exception */ @Override public void pushOrder(OrderTaxi orderTaxi, Integer type) throws Exception { new Thread(new Runnable() { @Override public void run() { try { orderIds.add(orderTaxi.getId());//记录当前订单,避免重复推送 String vehicle = (String) redisTemplate.opsForValue().get("VEHICLE"); List integers = new ArrayList<>(); if (ToolUtil.isNotEmpty(vehicle)) { integers = JSON.parseArray(vehicle).toJavaList(Integer.class); } OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); // 判断是否为智能派单 TSysPushType sysPushType = tSysPushTypeService.selectOne(new EntityWrapper().eq("openCityId", openCity.getId())); if(sysPushType!=null && sysPushType.getPushType()==2){ OrderTaxi orderTaxi1 = orderTaxiMapper.selectById(orderTaxi.getId()); if (null == orderTaxi1 && orderTaxi1.getState() == 1) { // 获取5公里内司机抢单 List listDriver = driverService.queryIdleDriver(2, orderTaxi1.getStartLon(), orderTaxi1.getStartLat(), 5.0, null);//查询5公里内空闲司机 if (listDriver.size() > 0) { Driver driver1 = listDriver.stream().sorted(Comparator.comparingDouble(Driver::getDistance).reversed()).findFirst().get(); orderTaxi1.setDriverId(driver1.getId()); orderTaxi1.setCarId(driver1.getCarId()); orderTaxi1.setCompanyId(driver1.getFranchiseeId() != null && driver1.getFranchiseeId() != 0 ? driver1.getFranchiseeId() : ( driver1.getCompanyId() != null && driver1.getCompanyId() != 0 ? driver1.getCompanyId() : 1)); orderTaxi1.setState(2); orderTaxi1.setSnatchOrderTime(new Date()); // 是否推广订单 Integer promotion = isPromotion(orderTaxi1.getUserId(), driver1.getPlaceOfEmployment()); if(promotion!=null){ orderTaxi1.setPromotion(2); orderTaxi1.setPromotionUser(driver1.getName()); orderTaxi1.setPromotionPhone(driver1.getPhone()); orderTaxi1.setPromotionDriverId(promotion); }else{ orderTaxi1.setPromotion(1); } orderTaxiMapper.updateById(orderTaxi1); if(orderTaxi.getType() == 2){ List list = orderTaxiMapper.selectList( new EntityWrapper() .eq("type", 2) .eq("userId", orderTaxi.getUserId()) .ne("state", 1) .eq("crossCityOrderId", orderTaxi.getCrossCityOrderId()) .eq("place", orderTaxi.getPlace()).ne("id", orderTaxi.getId()) ); List list1 = orderPrivateCarService.selectList( new EntityWrapper() .eq("type", 2) .eq("userId", orderTaxi.getUserId()) .ne("state", 1) .eq("crossCityOrderId", orderTaxi.getCrossCityOrderId()) .eq("place", orderTaxi.getPlace()) ); for(OrderTaxi orderTaxi2 : list){ orderTaxi2.setState(10); orderTaxiMapper.updateById(orderTaxi2); } for(OrderPrivateCar orderPrivateCar : list1){ orderPrivateCar.setState(10); orderPrivateCarService.updateById(orderPrivateCar); } } //如果是预约单,则不修改司机为服务中 if(orderTaxi1.getOrderType() != 2 || (orderTaxi1.getOrderType() == 2 && orderTaxi1.getTravelTime().getTime() < System.currentTimeMillis() + 600000)){ //修改司机为服务中 driver1.setState(3); driverService.updateById(driver1); } //推送相关代码-----------------start---------------- OrderTaxi finalOrderTaxi = orderTaxi1; new Thread(new Runnable() { @Override public void run() { pushUtil.pushOrderState(1, finalOrderTaxi.getUserId(), finalOrderTaxi.getId(), 2, finalOrderTaxi.getState(),0); pushUtil.pushOrderState(2, finalOrderTaxi.getDriverId(), finalOrderTaxi.getId(), 2, finalOrderTaxi.getState(),0); if(finalOrderTaxi.getType() == 2){ pushUtil.pushFerryOrderState(1, finalOrderTaxi.getUserId(), finalOrderTaxi.getId(), 2, 2); System.err.println("----------------------------------推送结束----------------------------"); } } }).start(); new Thread(new Runnable() { @Override public void run() { pushUtil.pushDriverPosition(finalOrderTaxi.getId(), 2); } }).start(); systemNoticeService.addSystemNotice(2, "已为您派得出租车订单,请及时联系乘客!", orderTaxi.getDriverId(), 1); systemNoticeService.addSystemNotice(1, "您的订单已指派给" + driver1.getName().substring(0, 1) + "师傅,请保持电话畅通!", orderTaxi.getUserId(), 1); }else { // 没找到车辆 OrderTaxi orderTaxi2 = orderTaxiMapper.selectById(orderTaxi.getId()); ResultUtil refundResult = handleTaxiPrepayCancelRefund(orderTaxi2, "\u65e0\u53f8\u673a\u63a5\u5355", "\u65e0\u53f8\u673a\u63a5\u5355", orderTaxi2.getUserId()); if (refundResult == null) { orderTaxi2.setState(10); orderTaxiMapper.updateById(orderTaxi2); } pushUtil.pushEndPush(1, orderTaxi2.getUserId(), orderTaxi2.getId(), 2, 1); } } }else { List querys = pushOrderService.querys(null, 2, openCity.getId());//查询推单配置 //整轮派单结束,若无司机接单,系统自动增加派单5轮,若增加5轮后仍无司机接单,则系统结束派单,乘客端显示无司机接单、是否再次打车 int num = 0; for (int j = 0; j < 6; j++) { Boolean push = false; for (int i = 1; i <= querys.size(); i++) { num++; int finalI = i; PushOrder pushOrder = querys.stream().filter(s -> s.getType() == (finalI <= 3 ? finalI : 3)).findFirst().orElse(null); System.out.println("pushOrder:" + pushOrder); //获取空闲司机 List list = driverService.queryIdleDriver(2, orderTaxi.getStartLon(), orderTaxi.getStartLat(), pushOrder.getPushDistance(), null);//查询指定距离内的空闲司机 //随机排序 Collections.shuffle(list); if (list.size() > 0) { double driverProportion = pushOrder.getDriverProportion() / 100;//司机推送比例 int lastIndex = Double.valueOf(list.size() * driverProportion).intValue();//根据比例计算推送司机数量 lastIndex = lastIndex == 0 ? list.size() : lastIndex; list = list.subList(0, lastIndex);//截取本轮需要推送的司机 for (Driver driver : list) {//循环推送司机 // 判断是否已经推送过同一司机 boolean bo = false; for (Integer integer : integers) { if (integer.compareTo(driver.getId()) == 0) { bo = true; break; } } if (bo) { continue; } pushUtil.pushOrderState(2, driver.getId(), orderTaxi.getId(), 2, orderTaxi.getState(), pushOrder.getPushTime()); } } Thread.sleep(pushOrder.getPushTime() * 1000);//等待当前轮推送结束 OrderTaxi orderTaxi1 = orderTaxiMapper.selectById(orderTaxi.getId()); if(null == orderTaxi1){ break; } Integer state = orderTaxi1.getState(); if (state != 1) { push = true; break; } if (num == 18 && state == 1) { ResultUtil refundResult = handleTaxiPrepayCancelRefund(orderTaxi1, "\u65e0\u53f8\u673a\u63a5\u5355", "\u65e0\u53f8\u673a\u63a5\u5355", orderTaxi1.getUserId()); if (refundResult == null) { orderTaxi1.setState(10); orderTaxiMapper.updateById(orderTaxi1); } pushUtil.pushEndPush(1, orderTaxi.getUserId(), orderTaxi.getId(), 2, 1); orderIds.remove(orderTaxi.getId()); } } if(push){ break; } } } } catch (Exception e) { e.printStackTrace(); } } }).start(); } private Integer isPromotion(Integer userId, String code){ UserInfo userInfo = userInfoService.selectById(userId); if(userInfo.getBindDriverId()!=null && userInfo.getBindExpireDate().getTime()>=System.currentTimeMillis()){ TDriverPromotionActivity tDriverPromotionActivity = driverPromotionActivityService.selectOne(new EntityWrapper().eq("districtCode", code) .eq("state",1).le("startTime", new Date()).ge("endTime", new Date()).last("AND FIND_IN_SET(" + 1 + ", bizType) limit 1")); if(tDriverPromotionActivity!=null){ return userInfo.getBindDriverId(); } } return null; } @Override public synchronized String getOrderNum() throws Exception { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return "TA" + sdf.format(new Date()) + UUIDUtil.getRandomCode(5); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public ResultUtil payThankYouFee(Integer uid, Integer orderId, Double money, Integer payType, Integer type) throws Exception { UserInfo userInfo = userInfoService.selectById(uid); OrderTaxi orderTaxi = this.selectById(orderId); ResultUtil resultUtil = ResultUtil.success(); if (payType == 1) {//微信支付 String outTradeNo = "THANK_" + orderId + "_2_" + UUIDUtil.getRandomCode(5); JSONObject response = cbyzxOrderPayHelper.createOrder(orderTaxi.getUserId(), userInfo.getAppletsOpenId(), outTradeNo, money); if (!cbyzxOrderPayHelper.isCreateSuccess(response)) { return ResultUtil.error(cbyzxOrderPayHelper.extractMessage(response), response); } String paymentCode = ToolUtil.isNotEmpty(cbyzxOrderPayHelper.extractRecordCode(response)) ? cbyzxOrderPayHelper.extractRecordCode(response) : outTradeNo; resultUtil = ResultUtil.success(response); paymentRecordService.saveData(3, uid, 1, orderId, 2, 1, money, paymentCode, 1);//添加预支付数据 } if (payType == 2) {//支付宝支付 resultUtil = payMoneyUtil.alipay("感谢费", "感谢费", "", orderId + "_2_" + UUIDUtil.getRandomCode(5), money.toString(), "/base/aliPayThankYouFee"); paymentRecordService.saveData(1, uid, 1, orderId, 2, 2, money, "", 1);//添加预支付数据 } if (payType == 3) {//余额支付 if (userInfo.getBalance() == null || userInfo.getBalance() < money) { return ResultUtil.error("余额不足,无法完成支付"); } // resultUtil= appOrderController.moneyPay(orderId,userInfo.getId(),money); // if(resultUtil.getCode()==500){ // return ResultUtil.error("电子余额不足,无法完成支付"); // } userInfo.setBalance(new BigDecimal(userInfo.getBalance()).subtract(new BigDecimal(money)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); userInfo.setIntegral(userInfo.getIntegral() + (money.intValue() * query1.getIntegral()));//绉垎 //添加交易明细 transactionDetailsService.saveData(uid, "出租车-感谢费", money, 2, 1, 1, 2, orderId); userInfoService.updateById(userInfo); orderTaxi.setThankYouFee(money); this.updateById(orderTaxi); //添加已收入明细 incomeService.saveData(2, orderTaxi.getDriverId(), 6, orderTaxi.getId(), 2, money); Driver driver = driverService.selectById(orderTaxi.getDriverId()); driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(new BigDecimal(money)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(new BigDecimal(money)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(new BigDecimal(money)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); driverService.updateById(driver); systemNoticeService.addSystemNotice(1, "您已使用余额成功完成感谢费支付,谢谢使用!", uid, 1); } if (payType == 4) { Double payMoney = orderTaxi.getThankYouFee(); Integer integer = paymentRecordService.saveData(3, uid, 1, orderId, 2, 4, money, "", 1); resultUtil = appOrderController.placeAnOrder(new BigDecimal(money), 4, orderId, 12, integer); } return resultUtil; } @Override public void payThankYouFeeCallback(Integer orderId, String order_id, Integer payType) throws Exception { OrderTaxi orderTaxi = this.selectById(orderId); UserInfo userInfo = userInfoService.selectById(orderTaxi.getUserId()); PaymentRecord query = paymentRecordService.query(3, userInfo.getId(), 1, orderId, 2, payType, 1); query.setState(2); query.setCode(order_id); paymentRecordService.updateById(query); OpenCity openCity = openCityService.openCity1(orderTaxi.getStartLon().toString(), orderTaxi.getStartLat().toString()); SysIntegral query1 = sysIntegralMapper.query(openCity.getId()); userInfo.setIntegral(userInfo.getIntegral() + (query.getAmount().intValue() * query1.getIntegral()));//绉垎 //添加交易明细 transactionDetailsService.saveData(userInfo.getId(), "出租车-感谢费", query.getAmount(), 2, 1, 1, 2, orderId); userInfoService.updateById(userInfo); orderTaxi.setThankYouFee(query.getAmount()); this.updateById(orderTaxi); //添加已收入明细 incomeService.saveData(2, orderTaxi.getDriverId(), 6, orderTaxi.getId(), 2, query.getAmount()); Driver driver = driverService.selectById(orderTaxi.getDriverId()); driver.setBusinessMoney(new BigDecimal(null != driver.getBusinessMoney() ? driver.getBusinessMoney() : 0).add(new BigDecimal(query.getAmount())).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); driver.setLaveBusinessMoney(new BigDecimal(null != driver.getLaveBusinessMoney() ? driver.getLaveBusinessMoney() : 0).add(new BigDecimal(query.getAmount())).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); driver.setBalance(new BigDecimal(null != driver.getBalance() ? driver.getBalance() : 0).add(new BigDecimal(query.getAmount())).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue()); driverService.updateById(driver); systemNoticeService.addSystemNotice(1, "您已使用" + (payType == 1 ? "微信" : (payType == 2 ? "支付宝" : "云闪付")) + "成功完成感谢费支付,谢谢使用!", userInfo.getId(), 1); } @Override public List getUnpayTaxiOrders(Integer uid) { EntityWrapper wrapper = new EntityWrapper<>(); wrapper.eq("userId", uid); wrapper.eq("state", 7); //查询未支付订单 List orderTaxiList = this.selectList(wrapper); List unPayOrderVOList = new ArrayList<>(); for (OrderTaxi orderTaxi : orderTaxiList) { UnPayOrderVO unPayOrderVO = new UnPayOrderVO(); //添加司机信息 DriverInfoWarpper driverInfoWarpper = new DriverInfoWarpper(); Driver driver = driverService.selectById(orderTaxi.getDriverId()); BeanUtils.copyProperties(driver, driverInfoWarpper); unPayOrderVO.setDriverInfoWarpper(driverInfoWarpper); //鍏朵綑淇℃伅 BeanUtils.copyProperties(orderTaxi, unPayOrderVO); unPayOrderVOList.add(unPayOrderVO); } return unPayOrderVOList; } @Override public void addAppeal(Integer uid, Integer orderId, String abnormalIntro, String abnormalImg) { OrderTaxi orderTaxi = this.selectById(orderId); if (orderTaxi.getState() != 7 || orderTaxi.getAbnormalIntro() != null) { throw new RuntimeException("此订单无法申诉"); } orderTaxi.setAbnormalIntro(abnormalIntro); orderTaxi.setAbnormalImg(abnormalImg); orderTaxi.setAbnormal(2); this.baseMapper.updateById(orderTaxi); } @Override public void promotion(Integer orderId) { OrderTaxi orderTaxi = this.baseMapper.selectById(orderId); UserInfo userInfo = userInfoService.selectById(orderTaxi.getUserId()); if (orderTaxi.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(" + 2 + ", bizType) limit 1")); if (tDriverPromotionActivity != null) { Double payMoney = orderTaxi.getPayMoney(); BigDecimal bigDecimal = tDriverPromotionActivity.getCommissionRatio().divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(payMoney)).setScale(2, RoundingMode.HALF_UP); orderTaxi.setPromotionDriverId(userInfo.getBindDriverId()); orderTaxi.setPromotionMoney(bigDecimal); orderTaxi.setPromotionActivityId(tDriverPromotionActivity.getId()); orderTaxi.setSuccessTime(new Date()); this.baseMapper.updateById(orderTaxi); } } // 是否异常订单 if (orderTaxi.getResponsibilityType() != null && orderTaxi.getResponsibilityType() > 2) { TAbnormalPayOrder tAbnormalPayOrder = abnormalPayOrderMapper.selectList(new EntityWrapper().eq("type", 2).eq("orderNum", orderTaxi.getOrderNum())).stream().findFirst().orElse(null); if (tAbnormalPayOrder != null) { tAbnormalPayOrder.setPayStatus(2); tAbnormalPayOrder.setPayTime(new Date()); abnormalPayOrderMapper.updateById(tAbnormalPayOrder); } } } @Override public List> queryMyTripList(Integer uid, Integer pageNum, Integer size) throws Exception { pageNum = (pageNum - 1) * size; List> maps = orderTaxiMapper.queryMyTripList(uid, pageNum, size); for (Map map : maps) { if (Integer.valueOf(String.valueOf(map.get("state"))) == 11) { map.put("state", map.get("oldState")); } } return maps; } @Override public List> queryMyTripListAll(Integer uid) throws Exception { List> maps = orderTaxiMapper.queryMyTripListAll(uid); for (Map map : maps) { if (Integer.valueOf(String.valueOf(map.get("state"))) == 11) { map.put("state", map.get("oldState")); } } return maps; } }