package com.stylefeng.guns.modular.system.controller.general; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.stylefeng.guns.core.base.controller.BaseController; import com.stylefeng.guns.core.log.LogObjectHolder; import com.stylefeng.guns.core.shiro.ShiroKit; import com.stylefeng.guns.core.util.JwtTokenUtil; import com.stylefeng.guns.core.util.ToolUtil; import com.stylefeng.guns.modular.system.controller.resp.TAppUserDetailOrderResp; import com.stylefeng.guns.modular.system.controller.resp.TOrderResp; import com.stylefeng.guns.modular.system.controller.util.ExcelUtil; import com.stylefeng.guns.modular.system.controller.util.UUIDUtil; import com.stylefeng.guns.modular.system.enums.OrderStateEnum; import com.stylefeng.guns.modular.system.model.*; import com.stylefeng.guns.modular.system.service.*; import com.stylefeng.guns.modular.system.util.*; import com.stylefeng.guns.modular.system.util.GaoDe.model.District; import com.stylefeng.guns.modular.system.util.mongodb.model.Location; import com.stylefeng.guns.modular.system.warpper.PushOrderInfoWarpper; import io.swagger.annotations.ApiOperation; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.bouncycastle.math.raw.Mod; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.geo.Circle; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.geo.GeoJsonPoint; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.*; import java.util.stream.Collectors; /** * 控制器 * * @author fengshuonan * @Date 2023-02-15 11:57:13 */ @Controller @RequestMapping("/tOrder") public class TOrderController extends BaseController { private String PREFIX = "/system/tOrder/"; @Autowired private ITOrderService tOrderService; @Autowired private ITAppUserService tAppUserService; @Autowired private ITCancelOrderService tCancelOrderService; @Autowired private RedisUtil redisUtil; @Autowired private ITDriverService driverService; @Autowired private ITBranchOfficeService branchOfficeService; @Autowired private ITBranchOfficeAreaService branchOfficeAreaService; @Value("${filePath}") private String filePath; /** * 跳转到首页 */ @RequestMapping("") public String index() { return PREFIX + "tOrder.html"; } /** * 跳转到添加 */ @RequestMapping("/tOrder_add") public String tOrderAdd() { return PREFIX + "tOrder_add.html"; } /** * 跳转到修改 */ @RequestMapping("/tOrder_update/{tOrderId}") public String tOrderUpdate(@PathVariable Integer tOrderId, Model model) { TOrder tOrder = tOrderService.selectById(tOrderId); model.addAttribute("item",tOrder); LogObjectHolder.me().set(tOrder); return PREFIX + "tOrder_edit.html"; } /** * 跳转异常页面 * @return */ @RequestMapping("/tOrder-exception") public String tOrderException(Model model) { return PREFIX + "tOrderException.html"; } /** * 跳转到首页 */ @RequestMapping("/cancelOrder") public String cancelOrder() { return PREFIX + "tCancelOrder.html"; } /** * 跳转冻结页面 * @return */ @RequestMapping("/tOrderException_start_and_stop") public String tAppUserStartAndStop( Integer id, Model model) { // 查询订单 TOrder tOrder = tOrderService.selectById(id); TAppUser tAppUser = new TAppUser(); if(Objects.nonNull(tOrder)){ tAppUser = tAppUserService.selectById(tOrder.getUserId()); } model.addAttribute("id",id); if(Objects.nonNull(tAppUser)){ model.addAttribute("status",tAppUser.getStatus()); } return PREFIX + "tOrderStartAndStopException.html"; } /** * 跳转详情页面 */ @RequestMapping("/orderDetail") public String orderDetail(Integer orderId, Model model) { tOrderService.orderDetail(orderId,model); return PREFIX + "tOrderDetail.html"; } public static void main(String[] args) { JSONObject s = GaoDeMapUtil.getLngAndLat("四川省"); String lat= s.getString("latitude"); String lon= s.getString("longitude"); System.err.println(s); } /** * 跳转新建订单页面 */ @RequestMapping("/addOrder") public String addOrder(Model model) { Integer objectId = ShiroKit.getUser().getObjectId(); if(objectId==1){ // 地图默认展示柳州区 model.addAttribute("lon",104.043246); model.addAttribute("lat",30.641849); }else{ TBranchOffice tBranchOffice = branchOfficeService.selectById(objectId); if (tBranchOffice!=null){ List branchOfficeId = branchOfficeAreaService.selectList(new EntityWrapper() .eq("branchOfficeId", tBranchOffice.getId())); if (branchOfficeId.isEmpty()){ // 地图默认展示柳州区 model.addAttribute("lon",119.415953); model.addAttribute("lat",24.325502); }else{ TBranchOfficeArea tBranchOfficeArea = branchOfficeId.get(0); if (StringUtils.hasLength(tBranchOfficeArea.getAreaCode())){ JSONObject s = GaoDeMapUtil.getLngAndLat(tBranchOfficeArea.getProvinceName()+tBranchOfficeArea.getCityName()+tBranchOfficeArea.getAreaName()); String lat= s.getString("latitude"); String lon= s.getString("longitude"); model.addAttribute("lon",lon); model.addAttribute("lat",lat); }else if (StringUtils.hasLength(tBranchOfficeArea.getCityCode())){ JSONObject s = GaoDeMapUtil.getLngAndLat(tBranchOfficeArea.getProvinceName()+tBranchOfficeArea.getCityName()); String lat= s.getString("latitude"); String lon= s.getString("longitude"); model.addAttribute("lon",lon); model.addAttribute("lat",lat); }else if(StringUtils.hasLength(tBranchOfficeArea.getProvinceCode())){ JSONObject s = GaoDeMapUtil.getLngAndLat(tBranchOfficeArea.getProvinceName()); String lat= s.getString("latitude"); String lon= s.getString("longitude"); model.addAttribute("lon",lon); model.addAttribute("lat",lat); }else{ // 地图默认展示柳州区 model.addAttribute("lon",119.415953); model.addAttribute("lat",24.325502); } } }else{ // 地图默认展示柳州区 model.addAttribute("lon",119.415953); model.addAttribute("lat",24.325502); } } return PREFIX + "scope_driver.html"; } /** * 跳转派单页面 */ @RequestMapping("/dispatchOrder/{id}") public String dispatchOrder(Model model,@PathVariable("id") Integer id) { TOrder tOrder = orderService.selectById(id); model.addAttribute("item",tOrder); return PREFIX + "dispatch_order.html"; } /** * 跳转异常详情页面 */ @RequestMapping("/orderExceptionDetail") public String orderExceptionDetail(Integer orderId, Model model) { tOrderService.orderExceptionDetail(orderId,model); return PREFIX + "tOrderExceptionDetail.html"; } /** * 获取列表 */ @ApiOperation(value = "用户获取订单列表") @RequestMapping(value = "/list") @ResponseBody public Object list(Integer userId) { EntityWrapper wrapper = new EntityWrapper<>(); if(Objects.nonNull(userId)){ wrapper.eq("user_id",userId); } wrapper.orderBy("createTime",false); return tOrderService.selectList(wrapper); } @Autowired private ITOrderService orderService; @ApiOperation(value = "查询司机列表") @RequestMapping(value = "/getDriversByScope") @ResponseBody public Object getDriversByScope(String startLng,String startLat,String radiusValue ) { // TSystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper().eq("type", 1)); // if(null == systemConfig){ // redisUtil.unlock(); // return null; // } // JSONObject jsonObject = JSON.parseObject(systemConfig.getContent()); Integer roleType = ShiroKit.getUser().getRoleType(); List tDrivers = new ArrayList<>(); //找到中心点 GeoJsonPoint geoJsonPoint = new GeoJsonPoint(Double.valueOf(startLat), Double.valueOf(startLng)); Double num = Double.valueOf(radiusValue);//范围公里 //构造半径 Distance distanceR = new Distance(num, Metrics.KILOMETERS); //画圆 Circle circle = new Circle(geoJsonPoint, distanceR); // 构造query对象 Query query = Query.query(Criteria.where("location").withinSphere(circle)); List locations = mongoTemplate.find(query, Location.class); List driverIds = locations.stream().map(Location::getDriverId).collect(Collectors.toList()); if (driverIds.isEmpty()){ return new ArrayList(); } List driverId = driverWorkService.selectList(new EntityWrapper().in("driverId", driverIds)); if (roleType==2){ tDrivers = driverService.selectList(new EntityWrapper().in("id", driverIds) .eq("serverStatus",1) .eq("branchOfficeId", ShiroKit.getUser().getObjectId())); }else{ tDrivers = driverService.selectList(new EntityWrapper() .eq("serverStatus",1).in("id", driverIds)); } List> maps = new ArrayList<>(); for (TDriver tDriver : tDrivers) { Location location = locations.stream().filter(e -> e.getDriverId().equals(tDriver.getId())).findFirst().orElse(null); if (location==null){ continue; } long count = driverId.stream().filter(e -> e.getDriverId().equals(tDriver.getId())&&e.getOffWorkTime()==null).count(); if (count==0){ // 下班了 跳过 continue; } Map distance = gdMapElectricFenceUtil.getDistance(startLat + "," + startLng, location.getLocation().getX() + "," + location.getLocation().getY(), 1); String distanceD = distance.get("distance"); Location location1 = locations.stream().filter(e -> e.getDriverId().equals(tDriver.getId())).findFirst().orElse(null); HashMap map = new HashMap<>(); map.put("name",tDriver.getName()); map.put("id",tDriver.getId()); map.put("phone",tDriver.getPhone()); map.put("distance",new BigDecimal(distanceD).divide(new BigDecimal(1000),2,RoundingMode.HALF_UP)); GeoJsonPoint location2 = location1.getLocation(); map.put("longitude",location2.getY()); map.put("latitude",location2.getX()); maps.add(map); } return maps; } @Autowired private GDMapElectricFenceUtil gdMapElectricFenceUtil; @ApiOperation(value = "推单") @RequestMapping(value = "/pushOrder") @ResponseBody public Object pushOrder( String startLng,String startLat,String startAddress, String endLng,String endLat,String endAddress, String phone,String nickName,String driverIds,String remarks) throws Exception { // 根据经纬度和范围查询符合条件的司机 // List list = driverService.queryIdleDriver(2, lng, lat, radius, null);//所有附近空闲司机 // 预创订单 List status = new ArrayList<>(); status.add(107); status.add(108); status.add(301); List tOrders = orderService.selectList(new EntityWrapper() .eq("userPhone", phone) .notIn("state", status)); if (!tOrders.isEmpty()){ return 501; } List list = driverService.selectList(null); TOrder tOrder = new TOrder(); tOrder.setStartLng(startLat); tOrder.setStartLat(startLng); String s = cleanAddress(startAddress); String e = cleanAddress(endAddress); tOrder.setStartAddress(s.replace(" ","")); tOrder.setEndLng(endLat); tOrder.setEndLat(endLng); tOrder.setEndAddress(e.replace(" ","")); // 司机ids tOrder.setUserPhone(phone); tOrder.setUserName(nickName); tOrder.setSource(3); tOrder.setHallOrder(0); tOrder.setStatus(1); tOrder.setCreateTime(new Date()); tOrder.setState( 101); Double d = 0D; if (StringUtils.hasLength(tOrder.getEndLng())){ Map distance = MapUtil.getDistance(tOrder.getStartLng() + "," + tOrder.getStartLat(), tOrder.getEndLng() + "," + tOrder.getEndLat(), 1); if(null == distance){ return ResultUtil.error("获取预估距离出错"); } d = Double.valueOf(distance.get("distance")) / 1000; tOrder.setEstimatedMileage(d); tOrder.setEstimatedTime(Integer.valueOf(distance.get("duration")) / 60); } String city = ""; Integer branchOfficeId = null; District geocode = MapUtil.geocode(tOrder.getStartLng(), tOrder.getStartLat()); if(null != geocode){ String districtCode = geocode.getDistrictCode(); TBranchOffice branchOffice = branchOfficeService.selectOne(new EntityWrapper().eq("status", 1).eq("districtCode", districtCode)); if(null == branchOffice){ String cityCode = geocode.getCityCode(); branchOffice = branchOfficeService.selectOne(new EntityWrapper().eq("status", 1).eq("cityCode", cityCode)); if(null == branchOffice){ String provinceCode = geocode.getProvinceCode(); branchOffice = branchOfficeService.selectOne(new EntityWrapper().eq("status", 1).eq("provinceCode", provinceCode)); } } if(null == branchOffice){ return ResultUtil.error("起点暂无企业服务"); } branchOfficeId = branchOffice.getId(); } tOrder.setCreateTime(new Date()); tOrder = getOrderPrice(1, d, 0, tOrder, city, branchOfficeId); tOrder.setId(null); tOrder.setCode(UUIDUtil.getTimeStr() + UUIDUtil.getNumberRandom(5)); // if (StringUtils.hasLength(driverIds)){ // tOrder.setHallOrder(0); // }else{ // tOrder.setHallOrder(1); // } boolean insert = orderService.insert(tOrder); if (StringUtils.hasLength(driverIds)){ String[] split = driverIds.split(","); int length = split.length; for (Integer i = 0; i < length; i++) { if(insert){ //推送状态 // pushUtil.pushOrderStatus(uid, 1, order.getId(), order.getState()); if(null != tOrder.getDriverId()){ PushOrderInfoWarpper pushOrderInfoWarpper = new PushOrderInfoWarpper(); pushOrderInfoWarpper.setId(Long.valueOf(tOrder.getId())); pushOrderInfoWarpper.setState(tOrder.getState()); pushUtil.pushOrderInfo(tOrder.getDriverId(), 2, pushOrderInfoWarpper); }else{ //推单 pushOrder(Long.valueOf(tOrder.getId()),Arrays.asList(split)); } } } redisUtil.setStrValue("newOrder", "true"); }else if (insert){ // 流入大厅订单 tOrder.setHallOrder(1); // 大厅订单结束时间 Date date = new Date(); LocalDateTime localDateTime = date.toInstant() .atZone(java.time.ZoneId.systemDefault()) .toLocalDateTime(); LocalDateTime newDateTime = localDateTime.plusMinutes(5); Date newDate = java.util.Date.from(newDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant()); tOrder.setEndTime(newDate); orderService.updateById(tOrder); } return list; } public static String cleanAddress(String address) { if (address == null || address.trim().isEmpty()) { return ""; } try { // 1. 先移除HTML实体编码中的空格 String decoded = address.replaceAll("& #", "&#"); // 2. 处理HTML实体编码 StringBuilder result = new StringBuilder(); int i = 0; while (i < decoded.length()) { if (i < decoded.length() - 2 && decoded.substring(i, i + 2).equals("&#")) { // 找到分号的位置 int semicolon = decoded.indexOf(";", i); if (semicolon != -1) { try { // 提取数字部分 String number = decoded.substring(i + 2, semicolon); // 转换为字符 char ch = (char) Integer.parseInt(number); result.append(ch); i = semicolon + 1; continue; } catch (NumberFormatException e) { // 如果解析失败,保留原字符 result.append(decoded.charAt(i)); } } } else { result.append(decoded.charAt(i)); } i++; } // 3. 移除括号和规范化空格 return result.toString() .replaceAll("[\\(\\)()]", "") // 移除中英文括号 .replaceAll("\\s+", " ") // 多个空格替换为单个空格 .trim(); // 移除首尾空格 } catch (Exception e) { // 如果处理失败,返回原始地址 return address; } } @ApiOperation(value = "派单") @RequestMapping(value = "/pushOrderOne") @ResponseBody public Object pushOrderOne(Integer id,String driverId) throws Exception { // 根据经纬度和范围查询符合条件的司机 // List list = driverService.queryIdleDriver(2, lng, lat, radius, null);//所有附近空闲司机 // 预创订单 List list = driverService.selectList(null); TOrder order = orderService.selectById(id); List drivers = new ArrayList<>(); drivers.add(driverId.replace(" ","")); Integer i = Integer.valueOf(driverId.replace(" ", "")); //推送状态 pushUtil.pushOrderStatus(i, 1, Long.valueOf(order.getId()), order.getState()); // if(null != order.getDriverId()){ // PushOrderInfoWarpper pushOrderInfoWarpper = new PushOrderInfoWarpper(); // pushOrderInfoWarpper.setId(Long.valueOf(order.getId())); // pushOrderInfoWarpper.setState(order.getState()); // pushUtil.pushOrderInfo(order.getDriverId(), 2, pushOrderInfoWarpper); // } PushOrderInfoWarpper pushOrderInfoWarpper = new PushOrderInfoWarpper(); pushOrderInfoWarpper.setId(Long.valueOf(order.getId())); pushOrderInfoWarpper.setState(order.getState()); pushUtil.pushOrderInfo(i, 2, pushOrderInfoWarpper); if (order.getDriverId()!=null){ pushUtil.pushOrderStatus(order.getDriverId(), 1, Long.valueOf(order.getId()), order.getState()); // pushUtil.pushOrderStatus(uid, 1, order.getId(), order.getState()); } TDriver driver = driverService.selectById(Integer.valueOf(driverId.replace(" ",""))); order.setDriverId(driver.getId()); order.setAgentId(driver.getAgentId()); order.setBranchOfficeId(driver.getBranchOfficeId()); order.setState(102); order.setOrderTakingTime(new Date()); orderService.updateById(order); return list; } /** * 初始订单费用 * @param order * @return */ public TOrder getOrderInitialPrice(TOrder order){ order.setStartDistance(0D);//起步里程 order.setStartPrice(new BigDecimal("0"));//起步价 order.setOverDriveDistance(0D);//超出起步里程 order.setOverDrivePrice(new BigDecimal("0"));//超出起步里程费 order.setLongDistance("");//长途里程 order.setLongDistancePrice(new BigDecimal("0"));//长途里程费 order.setOverLongDistance(0D);//超出长途里程 order.setOverLongDistancePrice(new BigDecimal("0"));//超出长途里程费 // order.setWaitTime(0);//等待时长 order.setWaitTimePrice(new BigDecimal("0"));//等待费 order.setOutWaitTime(0);//超出等待时长 order.setOutWaitTimePrice(new BigDecimal("0"));//超出等待时长费 order.setBadWeatherDistance(new BigDecimal("0"));//恶劣天气里程 order.setBadWeatherPrice(new BigDecimal("0"));//恶劣天气里程费 order.setOverBadWeatherDistance(0D);//恶劣天气超出里程 order.setOverBadWeatherPrice(new BigDecimal("0"));//恶劣天气超出里程费 // order.setHolidayPrice(0D);//节假日 order.setDiscountedPrice(new BigDecimal("0"));//优惠金额 order.setCouponId(null);//优惠券 order.setDiscountAmount(new BigDecimal("0"));//折扣优惠金额 // order.setDiscount(0D);//折扣 // order.setHolidayPrice(0D); return order; } /** * 获取订单价格 * @param type 计算类型(1=预估价,2=订单费) * @param distance 行驶公里 * @param waitTime 等待时长 * @param order 订单数据 * @param city 查询天气的城市 * @return */ public TOrder getOrderPrice(Integer type, Double distance, Integer waitTime, TOrder order, String city, Integer branchOfficeId){ order = getOrderInitialPrice(order); TSystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper().eq("type", 5).eq("companyId", branchOfficeId)); // if(null == systemConfig){ // if(type == 1){//预估金额 // order.setEstimatedPrice(0D); // } // if(type == 2){//订单金额 // order.setOrderMoney(0D); // } // return order; // } JSONObject jsonObject = JSON.parseObject(systemConfig.getContent()); JSONArray chargeStandard = jsonObject.getJSONArray("ChargeStandard"); JSONObject extraCost = jsonObject.getJSONObject("ExtraCost"); Date date = order.getCreateTime(); for (int i = 0; i < chargeStandard.size(); i++) {//计算各个时段 JSONObject jsonObject1 = chargeStandard.getJSONObject(i); String num1 = jsonObject1.getString("num1"); String num2 = jsonObject1.getString("num2"); Double num3 = jsonObject1.getDouble("num3");//起步里程 Double num4 = jsonObject1.getDouble("num4");//起步价格 Double num5 = jsonObject1.getDouble("num5");//超过公里 Double num6 = jsonObject1.getDouble("num6");//超过num3每num5公里收取num6 Double num7 = jsonObject1.getDouble("num7");//长途起始公里 Double num8 = jsonObject1.getDouble("num8");//长途结束公里 Double num9 = jsonObject1.getDouble("num9");//长途费 Double num10 = jsonObject1.getDouble("num10");//超出长途里程每num10公里 Double num11 = jsonObject1.getDouble("num11");//超过num8每num10公里收取num11 String[] split = num1.split(":"); Integer hour1 = Integer.valueOf(split[0]); String[] split1 = num2.split(":"); Integer hour2 = Integer.valueOf(split1[0]); Calendar s = Calendar.getInstance(); s.setTime(date); s.set(Calendar.HOUR_OF_DAY, hour1); s.set(Calendar.MINUTE, Integer.valueOf(split[1])); s.set(Calendar.SECOND, 0); Calendar e = Calendar.getInstance(); e.setTime(date); e.set(Calendar.HOUR_OF_DAY, hour2); e.set(Calendar.MINUTE, Integer.valueOf(split1[1])); e.set(Calendar.SECOND, 0); if(hour1 > hour2){ if(s.getTimeInMillis() > date.getTime()){ s.set(Calendar.DAY_OF_YEAR, s.get(Calendar.DAY_OF_YEAR) - 1); }else{ e.set(Calendar.DAY_OF_YEAR, e.get(Calendar.DAY_OF_YEAR) + 1); } } if(date.getTime() >= s.getTimeInMillis() && date.getTime() < e.getTimeInMillis()){ if(num3.compareTo(distance) >= 0){//起步里程内 order.setStartDistance(distance);//起步里程 // order.setStartPrice(num4);//起步价 }else{ Double distance1 = distance;//原始里程 order.setStartDistance(num3);//起步里程 order.setStartPrice(new BigDecimal(num4));//起步价 order.setOverDriveDistance(new BigDecimal(distance1 - num3).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//超出起步里程 distance = new BigDecimal(distance).setScale(0, RoundingMode.UP).doubleValue();//向上取整 BigDecimal divide = new BigDecimal(distance - num3).divide(new BigDecimal(num5), 2, BigDecimal.ROUND_HALF_EVEN); BigDecimal multiply = divide.multiply(new BigDecimal(num6)); order.setOverDrivePrice(multiply);//超出起步里程费 //计算长途费(超出长途起始公里,费用开始按照长途规则计算。) if(distance.compareTo(num7) > 0){ order.setStartDistance(0D);//起步里程 order.setStartPrice(new BigDecimal("0"));//起步价 order.setOverDriveDistance(0D);//超出起步里程 order.setOverDrivePrice(new BigDecimal("0"));//超出起步里程费 order.setLongDistance(num7 + "-" + num8);//长途里程 order.setLongDistancePrice(new BigDecimal(num9));//长途费 } //计算长途里程超出的部分 if(distance.compareTo(num8) > 0){ order.setOverLongDistance(new BigDecimal(distance1 - num8).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());//超出长途里程 BigDecimal divide1 = new BigDecimal(distance - num8).divide(new BigDecimal(num10), 2, BigDecimal.ROUND_HALF_EVEN); BigDecimal multiply1 = divide1.multiply(new BigDecimal(num11)); order.setOverLongDistancePrice(multiply1);//超出长途里程费 } } break; } } //计算额外费用 Integer num1 = extraCost.getInteger("num1");//等待时长 Double num2 = extraCost.getDouble("num2");//等待费 Integer num3 = extraCost.getInteger("num3");//等待超出时长 Double num4 = extraCost.getDouble("num4");//等到超出时长费用单价 X/分钟 Double num5 = extraCost.getDouble("num5");//恶劣天气公里 Double num6 = extraCost.getDouble("num6");//恶劣天气费 Double num7 = extraCost.getDouble("num7");//恶劣天气超出公里 Double num8 = extraCost.getDouble("num8");//恶劣天气超出公里单价 X/公里 Double num9 = extraCost.getDouble("num9");//恶劣天气最高收取金额 Double num10 = extraCost.getDouble("num10");//节假日收费 //等待费用 if(waitTime.compareTo(num1 * 60) >= 0){ order.setWaitTime(num1 * 60);//等待时长 order.setWaitTimePrice(new BigDecimal(num2));//等待费用 Integer w = waitTime - (num1 * 60); BigDecimal multiply = new BigDecimal(w).divide(new BigDecimal(60), 0, RoundingMode.UP).multiply(new BigDecimal(num4)); order.setOutWaitTime(w);//等待时长超出分钟 order.setOutWaitTimePrice(multiply);//等待时长超出费用 } //恶劣天气 systemConfig = systemConfigService.selectOne(new EntityWrapper().eq("type", 8).eq("companyId", branchOfficeId)); if(null != systemConfig){ JSONObject jsonObject1 = JSON.parseObject(systemConfig.getContent()); Integer num11 = jsonObject1.getInteger("num1");//开启恶劣天气计价 Integer num31 = jsonObject1.getInteger("num3"); if(1 == num11){ order.setBadWeatherDistance(new BigDecimal(num5));//恶劣天气公里 order.setBadWeatherPrice(new BigDecimal(num6));//恶劣天气费 if(distance.compareTo(num7) > 0){ BigDecimal subtract = new BigDecimal(distance).subtract(new BigDecimal(num7)); BigDecimal multiply = subtract.multiply(new BigDecimal(num8)); order.setOverBadWeatherDistance(subtract.doubleValue());//恶劣天气超出公里 order.setOverBadWeatherPrice(multiply);//恶劣天气超出公里费 } double add = order.getOverBadWeatherPrice().add(order.getBadWeatherPrice()).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue(); if(num9.compareTo(add) < 0){//超出最高金额(重新调整金额) if(num9.compareTo(num6) < 0){//如果恶劣天气费大于最高金额 order.setBadWeatherPrice(new BigDecimal(num9));//恶劣天气费 order.setOverBadWeatherPrice(new BigDecimal("0"));//恶劣天气超出公里费 }else{ BigDecimal subtract = new BigDecimal(num9).subtract(new BigDecimal(add)); order.setOverBadWeatherPrice(subtract);//恶劣天气超出公里费 } } } if(1 == num31){//节假日 order.setHolidayPrice(num10); } } //计算总金额 BigDecimal bigDecimal =order.getStartPrice().add(order.getOverDrivePrice()) .add( order.getLongDistancePrice()) .add(order.getOverLongDistancePrice()) .add(order.getWaitTimePrice()) .add(order.getOutWaitTimePrice()) .add(order.getBadWeatherPrice()) .add(order.getOverBadWeatherPrice()) .add(order.getHolidayPrice()!=null?new BigDecimal(order.getHolidayPrice()):new BigDecimal(0)) .subtract(order.getDiscountAmount()!=null?order.getDiscountAmount():new BigDecimal(0)) .setScale(2, BigDecimal.ROUND_HALF_EVEN); if(type == 1){//预估价 order.setEstimatedPrice(bigDecimal); } if(type == 2){//订单金额 order.setOrderMoney(bigDecimal); } return order; } @Autowired private ITSystemConfigService systemConfigService; @Autowired private MongoTemplate mongoTemplate; @Autowired private IYouTuiDriverService youTuiDriverService; @Autowired private ITDriverWorkService driverWorkService; @Autowired private PushUtil pushUtil; /** * 订单推送逻辑 */ public void pushOrder(Long orderId,List ids){ TSystemConfig systemConfig = systemConfigService.selectOne(new EntityWrapper().eq("type", 1)); if(null == systemConfig){ return; } JSONObject jsonObject = JSON.parseObject(systemConfig.getContent()); Integer num4 = jsonObject.getInteger("num4");//接单时间 for (String id : ids) { TDriver driver1 = driverService.selectById(id); TSystemConfig systemConfig6 = systemConfigService.selectOne(new EntityWrapper().eq("type", 6) .eq("companyType",2) .eq("companyId",driver1.getBranchOfficeId())); JSONObject jsonObject6 = JSON.parseObject(systemConfig6.getContent()); Double num1 = jsonObject6.getDouble("num1"); if(driver1.getBalance().compareTo(new BigDecimal(num1))<0){ continue; } // driver1.setServerStatus(2); driverService.updateById(driver1); pushUtil.pushGrabOrder(Integer.valueOf(id), 2, orderId, num4); //创建定时任务处理订单到大厅 } new Timer().schedule(new TimerTask() { @Override public void run() { TOrder order1 = orderService.selectById(orderId); if(order1.getState() == 201 || (order1.getState() == 101 && null == order1.getDriverId())){ order1.setHallOrder(1); // 大厅订单结束时间 Date date = new Date(); LocalDateTime localDateTime = date.toInstant() .atZone(java.time.ZoneId.systemDefault()) .toLocalDateTime(); LocalDateTime newDateTime = localDateTime.plusMinutes(5); Date newDate = java.util.Date.from(newDateTime.atZone(java.time.ZoneId.systemDefault()).toInstant()); order1.setEndTime(newDate); orderService.updateById(order1); ExtraPushOrder(order1); redisUtil.setStrValue("lobbyOrder", "true"); } } }, num4 * 1000); } public void ExtraPushOrder(TOrder order){ String startLat = order.getStartLat(); String startLng = order.getStartLng(); //找到中心点 GeoJsonPoint geoJsonPoint = new GeoJsonPoint(Double.valueOf(startLng), Double.valueOf(startLat)); Double num = 5D;//范围公里 //构造半径 Distance distanceR = new Distance(num, Metrics.KILOMETERS); //画圆 Circle circle = new Circle(geoJsonPoint, distanceR); // 构造query对象 Query query = Query.query(Criteria.where("location").withinSphere(circle)); List locations = mongoTemplate.find(query, Location.class); List driverIds = locations.stream().map(Location::getDriverId).collect(Collectors.toList()); if(driverIds.size() == 0){ return; } List tDriverWorks = driverWorkService.selectList(new EntityWrapper().in("driverId", driverIds).eq("status", 1)); driverIds = tDriverWorks.stream().map(TDriverWork::getDriverId).collect(Collectors.toList()); List drivers = driverService.selectList(new EntityWrapper().eq("approvalStatus", 2) .eq("serverStatus", 1).eq("openOrderQRCode", 0).eq("status", 1).in("id", driverIds)); if(drivers.size() == 0){ return; } for (TDriver driver1 : drivers) { String value = redisUtil.getValue("DRIVER" + driver1.getId()); if (ToolUtil.isEmpty(value)) { continue; } pushUtil.pushGrabOrderExtras(driver1.getId(), 2); } } /** * 获取列表 */ @ApiOperation(value = "获取订单列表") @RequestMapping(value = "/orderList") @ResponseBody public Object orderList(String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName) { return tOrderService.getOrderList(createTime, code, source, userName, userPhone, state, driverName,1); } /** * 获取列表 */ @ApiOperation(value = "获取订单异常列表") @RequestMapping(value = "/orderExceptionList") @ResponseBody public Object orderExceptionList(String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName) { // return tOrderService.getOrderList(createTime, code, source, userName, userPhone, state, driverName,2); return tCancelOrderService.getCancelOrderList(createTime, code, source, userName, userPhone, state, driverName); } /** * 获取列表 */ @ApiOperation(value = "获取用户详情里的订单列表") @RequestMapping(value = "/appUserDetailList") @ResponseBody public Object appUserDetailList(String condition,Integer userId) { List list = new ArrayList<>(); EntityWrapper wrapper = new EntityWrapper<>(); if(Objects.nonNull(userId)){ wrapper.eq("userId",userId); } List tOrders = tOrderService.selectList(wrapper); for (TOrder tOrder : tOrders) { TAppUserDetailOrderResp tAppUserDetailOrderResp = new TAppUserDetailOrderResp(); BeanUtils.copyProperties(tOrder,tAppUserDetailOrderResp); // 计算总里程 if(Objects.nonNull(tOrder.getActualMileage())){ tAppUserDetailOrderResp.setMileageSum(tOrder.getActualMileage()/1000); } // 计算总时长 long travelTimeSum = 0; if(Objects.nonNull(tAppUserDetailOrderResp.getBoardingTime()) && Objects.nonNull(tAppUserDetailOrderResp.getGetoffTime())){ travelTimeSum = DateUtil.between(tAppUserDetailOrderResp.getBoardingTime(), tAppUserDetailOrderResp.getGetoffTime(), DateUnit.MINUTE); } tAppUserDetailOrderResp.setTravelTimeSum(Integer.valueOf(Long.toString(travelTimeSum))); list.add(tAppUserDetailOrderResp); } return list; } @RequestMapping(value = "/getOrderTrack") @ResponseBody public ResultUtil getOrderTrack(Integer orderDetailId){ if(ToolUtil.isNotEmpty(orderDetailId)){ try { //将数据存储到文件中 File file = new File(filePath + orderDetailId + ".json"); if(!file.exists()){ return ResultUtil.success(new ArrayList<>()); } //读取文件(字符流) BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); //循环取出数据 String str = null; StringBuffer sb = new StringBuffer(); while ((str = in.readLine()) != null) { sb.append(str); } List list = JSONArray.parseArray(sb.toString(), TOrderPosition.class); return ResultUtil.success(list); }catch (Exception e){ e.printStackTrace(); return ResultUtil.runErr(); } }else { return ResultUtil.paranErr(); } } /** * 关闭订单 */ @RequestMapping(value = "/cancelOrderUpdate") @ResponseBody public Object cancelOrderUpdate(@RequestParam Integer tOrderId) { TOrder tOrder = tOrderService.selectById(tOrderId); tOrder.setState(OrderStateEnum.CANCELED.getCode()); tOrderService.updateById(tOrder); if(null != tOrder.getDriverId()){ redisUtil.delSetValue("orderService", tOrder.getId().toString()); TDriver tDriver = driverService.selectById(tOrder.getDriverId()); tDriver.setServerStatus(1); driverService.updateById(tDriver); } Map map = new HashMap<>(); if (tOrder.getUserId()!=null){ map.put("id", tOrder.getUserId().toString()); } map.put("type", "1"); PushOrderInfoWarpper pushOrderInfoWarpper = new PushOrderInfoWarpper(); pushOrderInfoWarpper.setId(tOrder.getId().longValue()); pushOrderInfoWarpper.setState(tOrder.getState()); pushOrderInfoWarpper.setCancelObject(3); map.put("pushOrderInfoWarpper", JSON.toJSONString(pushOrderInfoWarpper)); String result = HttpRequestUtil.postRequest(PushURL.order_push_url, map); if(null != tOrder.getDriverId()){ map = new HashMap<>(); map.put("id", tOrder.getDriverId().toString()); map.put("type", "1"); PushOrderInfoWarpper pushOrderInfoWarpper1 = new PushOrderInfoWarpper(); pushOrderInfoWarpper1.setId(tOrder.getId().longValue()); pushOrderInfoWarpper1.setState(tOrder.getState()); pushOrderInfoWarpper1.setCancelObject(3); map.put("pushOrderInfoWarpper", JSON.toJSONString(pushOrderInfoWarpper1)); result = HttpRequestUtil.postRequest(PushURL.order_push_url, map); } redisUtil.setStrValue("cancelOrder", "true"); return SUCCESS_TIP; } /** * 获取列表 */ @RequestMapping(value = "/list-back") @ResponseBody public Object listBack(String condition) { return tOrderService.selectList(null); } /** * 新增 */ @RequestMapping(value = "/add") @ResponseBody public Object add(TOrder tOrder) { tOrderService.insert(tOrder); return SUCCESS_TIP; } /** * 删除 */ @RequestMapping(value = "/delete") @ResponseBody public Object delete(@RequestParam Integer tOrderId) { tOrderService.deleteById(tOrderId); return SUCCESS_TIP; } /** * 修改 */ @RequestMapping(value = "/update") @ResponseBody public Object update(TOrder tOrder) { tOrderService.updateById(tOrder); return SUCCESS_TIP; } /** * 详情 */ @RequestMapping(value = "/detail/{tOrderId}") @ResponseBody public Object detail(@PathVariable("tOrderId") Integer tOrderId) { return tOrderService.selectById(tOrderId); } @ApiOperation(value = "导出订单列表",notes="导出订单列表") @RequestMapping(value = "/export") @ResponseBody public void export(String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName,HttpServletResponse response) { try { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyyMMdd"); String time1 = format.format(date); String fileName = "OrderInfo"+time1+".xls"; String[] title = new String[] {"下单时间","订单编号","订单来源","开始服务时间","下单用户昵称", "下单用户手机","起点地址","终点地址","接单司机","司机电话","订单金额","取消次数","订单状态"}; List orderList = tOrderService.getOrderList(createTime, code, source, userName, userPhone, state, driverName,1); String[][] values = new String[orderList.size()][]; for (int i = 0; i < orderList.size(); i++) { TOrderResp d = orderList.get(i); values[i] = new String[title.length]; values[i][0] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d.getCreateTime()); values[i][1] = d.getCode(); Integer source1 = d.getSource(); if(1 == source1){ values[i][2] = "小程序"; }else if(2 == source1){ values[i][2] = "司机创建"; } if(Objects.nonNull(d.getStartTime())){ values[i][3] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d.getStartTime()); }else { values[i][3] = ""; } values[i][4] = d.getUserName(); values[i][5] = d.getUserPhone(); values[i][6] = d.getStartAddress(); values[i][7] = d.getEndAddress(); values[i][8] = d.getDriverName(); values[i][9] = d.getDriverPhone(); values[i][10] = String.valueOf(Objects.nonNull(d.getOrderMoney())?d.getOrderMoney(): BigDecimal.ZERO); values[i][11] = String.valueOf(d.getCancelCount()); Integer status1 = d.getState(); if(101 == status1){ values[i][12] = "待接单"; }else if(102 == status1){ values[i][12] = "已接单"; }else if(103 == status1){ values[i][12] = "前往预约点"; }else if(104 == status1){ values[i][12] = "到达预约点"; }else if(105 == status1){ values[i][12] = "开始服务"; }else if(106 == status1){ values[i][12] = "到达目的地"; }else if(107 == status1){ values[i][12] = "待支付"; }else if(108 == status1){ values[i][12] = "待评价"; }else if(109 == status1){ values[i][12] = "已完成"; }else if(201 == status1){ values[i][12] = "转单中"; }else if(301 == status1){ values[i][12] = "已取消"; }else if(401 == status1){ values[i][12] = "等待中"; } } HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("Variance"+time1, title, values, null); ExcelUtil.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } @ApiOperation(value = "导出订单列表",notes="导出订单列表") @RequestMapping(value = "/export-exception") @ResponseBody public void exportException(String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName,HttpServletResponse response) { try { Date date = new Date(); DateFormat format = new SimpleDateFormat("yyyyMMdd"); String time1 = format.format(date); String fileName = "OrderExceptionInfo"+time1+".xls"; String[] title = new String[] {"下单时间","订单编号","订单来源","乘车时间","下单用户昵称", "下单用户手机","起点","终点","接单司机","司机电话","预估价格","取消次数","订单状态"}; List orderList = tOrderService.getOrderList(createTime, code, source, userName, userPhone, state, driverName,1); String[][] values = new String[orderList.size()][]; for (int i = 0; i < orderList.size(); i++) { TOrderResp d = orderList.get(i); values[i] = new String[title.length]; values[i][0] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d.getCreateTime()); values[i][1] = d.getCode(); Integer source1 = d.getSource(); if(1 == source1){ values[i][2] = "小程序"; }else if(2 == source1){ values[i][2] = "司机创建"; } if(Objects.nonNull(d.getStartTime())){ values[i][3] = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d.getStartTime()); }else { values[i][3] = ""; } values[i][4] = d.getUserName(); values[i][5] = d.getUserPhone(); values[i][6] = d.getStartAddress(); values[i][7] = d.getEndAddress(); values[i][8] = d.getDriverName(); values[i][9] = d.getDriverPhone(); values[i][10] = String.valueOf(Objects.nonNull(d.getEstimatedPrice())?d.getEstimatedPrice(): BigDecimal.ZERO); values[i][11] = String.valueOf(d.getCancelCount()); Integer status1 = d.getState(); if(101 == status1){ values[i][12] = "待接单"; }else if(102 == status1){ values[i][12] = "已接单"; }else if(103 == status1){ values[i][12] = "前往预约点"; }else if(104 == status1){ values[i][12] = "到达预约点"; }else if(105 == status1){ values[i][12] = "开始服务"; }else if(106 == status1){ values[i][12] = "到达目的地"; }else if(107 == status1){ values[i][12] = "待支付"; }else if(108 == status1){ values[i][12] = "待评价"; }else if(109 == status1){ values[i][12] = "已完成"; }else if(201 == status1){ values[i][12] = "转单中"; }else if(301 == status1){ values[i][12] = "已取消"; }else if(401 == status1){ values[i][12] = "等待中"; } } HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook("Variance"+time1, title, values, null); ExcelUtil.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } }