package com.stylefeng.guns.modular.system.controller.checkCar; import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.stylefeng.guns.core.base.controller.BaseController; import com.stylefeng.guns.core.base.tips.ErrorTip; import com.stylefeng.guns.core.log.LogObjectHolder; import com.stylefeng.guns.core.shiro.ShiroKit; import org.springframework.data.redis.core.RedisTemplate; import com.stylefeng.guns.modular.system.model.TAppUser; import com.stylefeng.guns.modular.system.model.TOrderCheck; import com.stylefeng.guns.modular.system.service.ITAppUserService; import com.stylefeng.guns.modular.system.service.ITOrderCheckService; import com.stylefeng.guns.modular.system.util.ResultUtil; import com.stylefeng.guns.modular.system.controller.util.ExcelUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.IOException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; /** * 代检车订单管理控制器 * * @author fengshuonan * @Date 2025-07-28 23:31:10 */ @Controller @RequestMapping("/tOrderCheck") public class TOrderCheckController extends BaseController { private static final Logger log = LoggerFactory.getLogger(TOrderCheckController.class); private String PREFIX = "/system/tOrderCheck/"; @Autowired private ITOrderCheckService tOrderCheckService; @Autowired private ITAppUserService tAppUserService; @Autowired private RedisTemplate redisTemplate; /** * 跳转到代检车订单管理首页 */ @RequestMapping("") public String index() { return PREFIX + "tOrderCheck.html"; } /** * 跳转到添加代检车订单管理 */ @RequestMapping("/tOrderCheck_add") public String tOrderCheckAdd(Model model) { List tAppUsers = tAppUserService.selectList(new EntityWrapper().eq("status", 1).eq("is_exception", 1)); model.addAttribute("tAppUsers", tAppUsers); return PREFIX + "tOrderCheck_add.html"; } /** * 跳转到修改代检车订单管理 */ @RequestMapping("/tOrderCheck_update/{tOrderCheckId}") public String tOrderCheckUpdate(@PathVariable Integer tOrderCheckId, Model model) { TOrderCheck tOrderCheck = tOrderCheckService.selectById(tOrderCheckId); model.addAttribute("item",tOrderCheck); LogObjectHolder.me().set(tOrderCheck); return PREFIX + "tOrderCheck_edit.html"; } /** * 跳转到订单详情页面 */ @RequestMapping("/tOrderCheck_detail/{tOrderCheckId}") public String tOrderCheckDetail(@PathVariable Integer tOrderCheckId, Model model) { TOrderCheck orderInfo = tOrderCheckService.getOrderInfo(tOrderCheckId); if (orderInfo == null) { // 如果订单不存在,返回错误页面或重定向 return "redirect:" + PREFIX + "tOrderCheck.html"; } // 格式化所有需要的时间字段并设置到orderInfo对象中 java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (orderInfo.getCreateTime() != null) { orderInfo.setCreateTimeFormat(dateFormat.format(orderInfo.getCreateTime())); } if (orderInfo.getReservationTime() != null) { orderInfo.setReservationTimeFormat(dateFormat.format(orderInfo.getReservationTime())); } if (orderInfo.getDispatchTime() != null) { orderInfo.setDispatchTimeFormat(dateFormat.format(orderInfo.getDispatchTime())); } if (orderInfo.getOrderTakingTime() != null) { orderInfo.setOrderTakingTimeFormat(dateFormat.format(orderInfo.getOrderTakingTime())); } if (orderInfo.getArrivalTimeAtTheAppointmentPoint() != null) { orderInfo.setArrivalTimeAtTheAppointmentPointFormat(dateFormat.format(orderInfo.getArrivalTimeAtTheAppointmentPoint())); } if (orderInfo.getStartTime() != null) { orderInfo.setStartTimeFormat(dateFormat.format(orderInfo.getStartTime())); } if (orderInfo.getEndTime() != null) { orderInfo.setEndTimeFormat(dateFormat.format(orderInfo.getEndTime())); } if (orderInfo.getGoTime() != null) { orderInfo.setGoTimeFormat(dateFormat.format(orderInfo.getGoTime())); } if (orderInfo.getSuccessTime() != null) { orderInfo.setSuccessTimeFormat(dateFormat.format(orderInfo.getSuccessTime())); } if (orderInfo.getPayTime() != null) { orderInfo.setPayTimeFormat(dateFormat.format(orderInfo.getPayTime())); } if (orderInfo.getCheckPayTime() != null) { orderInfo.setCheckPayTimeFormat(dateFormat.format(orderInfo.getCheckPayTime())); } if (orderInfo.getCommentTime() != null) { orderInfo.setCommentTimeFormat(dateFormat.format(orderInfo.getCommentTime())); } // 处理车检图片 if (orderInfo.getCheckImg() != null && !orderInfo.getCheckImg().isEmpty()) { List checkImgList = Arrays.stream(orderInfo.getCheckImg().split(",")) .map(String::trim) .filter(s -> !s.isEmpty()) .collect(Collectors.toList()); orderInfo.setCheckImgList(checkImgList); } else { orderInfo.setCheckImgList(Collections.emptyList()); } // 将包含了所有格式化时间字段的orderInfo对象转换为JSON字符串 String orderInfoStr = JSON.toJSONString(orderInfo); model.addAttribute("orderInfoStr", orderInfoStr); model.addAttribute("orderInfo", orderInfo); return PREFIX + "tOrderCheck_detail.html"; } /** * 获取代检车订单管理列表 */ @RequestMapping(value = "/list") @ResponseBody public Object list(String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName) { return super.packForBT(tOrderCheckService.getOrderCheckList(createTime, code, source, userName, userPhone, state, driverName)); } /** * 删除代检车订单管理 */ @RequestMapping(value = "/delete") @ResponseBody public Object delete(@RequestParam Integer tOrderCheckId) { TOrderCheck tOrderCheck = new TOrderCheck(); tOrderCheck.setId(tOrderCheckId); tOrderCheck.setStatus(3); // 设置状态为已删除 tOrderCheckService.updateById(tOrderCheck); return SUCCESS_TIP; } /** * 修改代检车订单管理 */ @RequestMapping(value = "/update") @ResponseBody public Object update(TOrderCheck tOrderCheck) { tOrderCheckService.updateById(tOrderCheck); return SUCCESS_TIP; } /** * 代检车订单管理详情 */ @RequestMapping(value = "/detail/{tOrderCheckId}") @ResponseBody public Object detail(@PathVariable("tOrderCheckId") Integer tOrderCheckId) { return tOrderCheckService.selectById(tOrderCheckId); } /** * 关闭订单 */ @RequestMapping(value = "/cancel") @ResponseBody public Object cancel(@RequestParam Integer tOrderCheckId) { try { tOrderCheckService.cancel(tOrderCheckId); return SUCCESS_TIP; } catch (Exception e) { log.error("取消订单异常: ", e); return new ErrorTip(ResultUtil.ERROR, "服务器开小差啦"); } } /** * 跳转到派单页面 * * @param tOrderCheckId 订单ID * @param type 派单类型:1=派单,2=改派 * @param model 视图模型 * @return 派单页面路径 */ @RequestMapping("/tOrderCheck_dispatch/{tOrderCheckId}/{type}") public String tOrderCheckDispatch(@PathVariable Integer tOrderCheckId, @PathVariable Integer type, Model model) { try { // 获取订单和用户信息 TOrderCheck orderInfo = tOrderCheckService.getOrderInfo(tOrderCheckId); orderInfo.setReservationTimeFormat(DateUtil.format(orderInfo.getReservationTime(), DatePattern.NORM_DATETIME_PATTERN)); model.addAttribute("orderId", tOrderCheckId); model.addAttribute("dispatchType", type); model.addAttribute("orderInfoData", orderInfo); return PREFIX + "tOrderCheck_dispatch.html"; } catch (Exception e) { model.addAttribute("errorMsg", e.getMessage()); return PREFIX + "tOrderCheck_dispatch.html"; } } /** * 跳转到批量派单页面 * * @param orderIds 订单ids * @param model 视图模型 * @return 派单页面路径 */ @RequestMapping("/tOrderCheck_dispatchBatch") public String tOrderCheckDispatchBatch(String orderIds, Model model) { // 解析订单ID数组 String[] orderIdArray = orderIds.split(","); List orderIdList = Arrays.asList(orderIdArray).stream().map(Integer::valueOf).collect(Collectors.toList()); // 查询选中的订单信息 List orderList = tOrderCheckService.getOrdersByIds(orderIdList); // 验证订单状态(确保都是可派单状态) List validOrders = orderList.stream() .filter(item -> item.getState().equals(100)) .peek(item->{ item.setCreateTimeFormat(DateUtil.format(item.getCreateTime(), DatePattern.NORM_DATETIME_FORMAT)); item.setReservationTimeFormat(DateUtil.format(item.getReservationTime(), DatePattern.NORM_DATETIME_FORMAT)); }).collect(Collectors.toList()); // 将订单信息传递给前端页面 model.addAttribute("orderList", validOrders); model.addAttribute("orderIds", orderIds); return PREFIX + "tOrderCheck_dispatchBatch.html"; } /** * 获取可派单司机分页列表(Ajax接口) */ @RequestMapping(value = "/dispatchData") @ResponseBody public Object getDispatchDriverList(@RequestParam(required = false) Integer orderId, @RequestParam Integer dispatchType, @RequestParam(defaultValue = "") String keyword) { try { return super.packForBT(tOrderCheckService.getDispatchDriverList(orderId, dispatchType, keyword)); } catch (Exception e) { log.error("派单操作异常: ", e); return new ErrorTip(ResultUtil.ERROR, "服务器开小差啦"); } } /** * 执行派单/改派操作 */ @RequestMapping(value = "/executeDispatch") @ResponseBody public Object executeDispatch(@RequestParam Integer orderId, @RequestParam Integer driverId, @RequestParam Integer dispatchType) { try { tOrderCheckService.executeDispatch(orderId, driverId, dispatchType); return SUCCESS_TIP; } catch (Exception e) { log.error("派单操作异常: ", e); return new ErrorTip(ResultUtil.ERROR, "服务器开小差啦"); } } /** * 执行批量派单操作 */ @RequestMapping(value = "/executeBatchDispatch") @ResponseBody public Object executeBatchDispatch(@RequestParam String orderIds, @RequestParam String driverIds) { try { // 解析订单ID数组 List orderIdList = Arrays.stream(orderIds.split(",")) .map(String::trim) .map(Integer::parseInt) .collect(Collectors.toList()); // 解析司机ID数组 List driverIdList = Arrays.stream(driverIds.split(",")) .map(String::trim) .map(Integer::parseInt) .collect(Collectors.toList()); // 验证订单数量和司机数量是否匹配 if (orderIdList.size() != driverIdList.size()) { return new ErrorTip(ResultUtil.ERROR, "订单数量与司机数量不匹配"); } // 执行批量派单 tOrderCheckService.executeBatchDispatch(orderIdList, driverIdList); return SUCCESS_TIP; } catch (Exception e) { log.error("批量派单操作异常: ", e); return new ErrorTip(ResultUtil.ERROR, e.getMessage()); } } /** * 新建订单 */ @RequestMapping(value = "/add") @ResponseBody public Object add(@RequestParam Integer userId, @RequestParam String startAddress, @RequestParam String endAddress, @RequestParam String reservationTime) { try { tOrderCheckService.addOrder(userId, startAddress, endAddress, reservationTime); return SUCCESS_TIP; } catch (Exception e) { log.error("新建订单失败: {}", e.getMessage(), e); return new ErrorTip(ResultUtil.ERROR, "服务器开小差啦"); } } /** * 导出车检订单列表 */ @RequestMapping(value = "/export") @ResponseBody public void export(HttpServletResponse response, String createTime, String code, Integer source, String userName, String userPhone, Integer state, String driverName) throws IOException { try { // 获取导出数据 List exportData = tOrderCheckService.exportOrderCheckList(createTime, code, source, userName, userPhone, state, driverName); // 定义Excel表头 String[] headers = {"下单时间", "订单编号", "订单来源", "预约时间", "下单用户昵称", "下单用户手机", "取车地", "还车地", "接单司机", "司机电话", "状态"}; // 枚举值映射 Map stateMap = new HashMap<>(); stateMap.put(100, "待派单"); stateMap.put(101, "待接单"); stateMap.put(102, "服务中"); stateMap.put(104, "服务中"); stateMap.put(105, "服务中"); stateMap.put(106, "服务中"); stateMap.put(107, "服务中"); stateMap.put(108, "服务中"); stateMap.put(109, "已完成"); stateMap.put(110, "已完成"); stateMap.put(111, "取消"); Map sourceMap = new HashMap<>(); sourceMap.put(1, "小程序"); sourceMap.put(2, "管理后台"); // 时间格式化器 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 构建数据数组 String[][] values = new String[exportData.size()][headers.length]; for (int i = 0; i < exportData.size(); i++) { TOrderCheck order = exportData.get(i); values[i][0] = order.getCreateTime() != null ? dateFormat.format(order.getCreateTime()) : ""; values[i][1] = order.getCode() != null ? order.getCode() : ""; values[i][2] = sourceMap.getOrDefault(order.getSource(), "未知"); values[i][3] = order.getReservationTime() != null ? dateFormat.format(order.getReservationTime()) : ""; values[i][4] = order.getUserName() != null ? order.getUserName() : ""; values[i][5] = order.getUserPhone() != null ? order.getUserPhone() : ""; values[i][6] = order.getStartAddress() != null ? order.getStartAddress() : ""; values[i][7] = order.getEndAddress() != null ? order.getEndAddress() : ""; values[i][8] = order.getDriverName() != null ? order.getDriverName() : ""; values[i][9] = order.getDriverPhone() != null ? order.getDriverPhone() : ""; values[i][10] = stateMap.getOrDefault(order.getState(), "未知状态"); } // 生成Excel文件名 String fileName = "车检订单列表_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".xls"; // 生成Excel HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook("车检订单列表", headers, values, null); // 设置响应头 ExcelUtil.setResponseHeader(response, URLEncoder.encode(fileName, "UTF-8")); // 输出文件 workbook.write(response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { log.error("导出车检订单列表失败: {}", e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write("导出失败: " + e.getMessage()); } } /** * 检查代检车新订单通知 */ @RequestMapping(value = "/checkNewOrderNotification") @ResponseBody public Object checkNewOrderNotification() { try { // 获取当前用户信息 Integer roleType = ShiroKit.getUser().getRoleType(); Integer objectId = ShiroKit.getUser().getObjectId(); Map result = new HashMap<>(); List orderIds = new ArrayList<>(); String redisKey; if (roleType == 1) { // 平台用户 - 查看所有新订单 redisKey = "newCheckCarOrder:platform"; } else { // 分公司用户 - 只查看本分公司的新订单 redisKey = "newCheckCarOrder:branch:" + objectId; } // 从Redis List获取新订单ID列表 List orderList = redisTemplate.opsForList().range(redisKey, 0, -1); if (orderList != null && !orderList.isEmpty()) { orderIds = orderList; } boolean hasNewOrder = !orderIds.isEmpty(); int orderCount = orderIds.size(); // 构建返回结果 result.put("hasNewOrder", hasNewOrder); result.put("orderCount", orderCount); result.put("orderIds", orderIds); result.put("currentTime", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_FORMAT)); // 如果有新订单,清空Redis中的记录(表示已经通知过了) if (hasNewOrder) { redisTemplate.delete(redisKey); } return result; } catch (Exception e) { log.error("检查代检车新订单通知失败: {}", e.getMessage(), e); Map errorResult = new HashMap<>(); errorResult.put("hasNewOrder", false); errorResult.put("orderCount", 0); errorResult.put("orderIds", new ArrayList<>()); errorResult.put("error", "检查通知失败"); return errorResult; } } }