package com.ruoyi.system.controller; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.page.TableDataInfo; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.system.ControllerUtil.*; import com.ruoyi.system.domain.*; import com.ruoyi.system.domain.AppleDoMain.OrderApple; import com.ruoyi.system.domain.AppleDoMain.AddressApple; import com.ruoyi.system.service.*; import com.winnerlook.model.VoiceResponseResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; import java.text.SimpleDateFormat; import java.math.BigDecimal; import com.ruoyi.system.config.QiniuConfig; import com.ruoyi.system.utils.QiniuUploadUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ruoyi.system.domain.WechatTransfer; import com.alibaba.fastjson2.JSONArray; import com.ruoyi.system.domain.QuoteCraft; import com.ruoyi.system.domain.QuoteType; import com.ruoyi.system.domain.QuoteMaterialType; import com.ruoyi.system.domain.QuoteMaterial; /** * 小程序控制器 * * * @author Mr. Zhang Pan * @version 2.0 */ @RestController public class AppletController extends BaseController { private static final Logger logger = LoggerFactory.getLogger(AppletController.class); @Autowired private IServiceCateService serviceCateService; @Autowired private IUsersService usersService; @Autowired private ISiteConfigService siteConfigService; @Autowired private IAdvImgService advImgService; @Autowired private IServiceGoodsService serviceGoodsService; @Autowired private IUserAddressService userAddressService; @Autowired private IOrderService orderService; @Autowired private IOrderReworkService orderReworkService; @Autowired private ICooperateService cooperateService; @Autowired private ICouponUserService couponUserService; @Autowired private IIntegralLogService integralLogService; @Autowired private IIntegralOrderService integralOrderService; @Autowired private IUserUseSecondaryCardService userUseSecondaryCardService; @Autowired private IIntegralProductService integralProductService; @Autowired private IIntegralOrderLogService integralOrderLogService; @Autowired private IIntegralCateService integralCateService; @Autowired private IOrderLogService orderLogService; @Autowired private IDiyCityService diyCityService; @Autowired private ISiteSkillService siteSkillService; @Autowired private QiniuConfig qiniuConfig; @Autowired private IGoodsCartService goodsCartService; @Autowired private IGoodsOrderService goodsOrderService; @Autowired private ICouponsService couponsService; @Autowired private IWorkerSignService workerSignService; @Autowired private IWorkerLevelService workerLevelService; @Autowired private IOrderCommentService orderCommentService; @Autowired private IWorkerMarginLogService workerMarginLogService; @Autowired private IWorkerMoneyLogService workerMoneyLogService; @Autowired private IWechatTransferService wechatTransferService; @Autowired private IQuoteCraftService quoteCraftService; @Autowired private IQuoteTypeService quoteTypeService; @Autowired private IQuoteMaterialTypeService quoteMaterialTypeService; @Autowired private IQuoteMaterialService quoteMaterialService; @Autowired private IGoodsOrderCursorService goodsOrderCursorService; @Autowired private IWorkerApplyService workerApplyService; @Autowired private IUserMemberRechargeProgramService userMemberRechargeProgramService; @Autowired private IUserSecondaryCardService userSecondaryCardService; @Autowired private IUserGroupBuyingService userGroupBuyingService; @Autowired private IUsersPayBeforService usersPayBeforService; @Autowired private IUserDemandQuotationService userDemandQuotationService; @Autowired private WechatPayV3Util wechatPayV3Util; /** * 获取服务分类列表 * 功能说明: * - 获取状态为启用的服务分类 * - 支持二级分类树形结构 * - 将二级分类组装在一级分类下的children字段 * - 只返回title和icon字段 * - 自动添加图片CDN前缀 * - 支持用户登录状态验证(可选) * * @param request HTTP请求对象 * @return 分类树形列表数据(只包含title和icon) */ @GetMapping(value = "/api/service/cate") public AjaxResult getServiceCategories(HttpServletRequest request) { try { // 验证用户登录状态(可选) AppletControllerUtil.getUserData(request.getHeader("token"), usersService); String cityid= request.getHeader("ct"); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"+cityid); // 1. 查询所有启用状态的服务分类 ServiceCate serviceCateQuery = new ServiceCate(); serviceCateQuery.setStatus(1L); serviceCateQuery.setType(1L); if (StringUtils.isNotBlank(cityid)){ serviceCateQuery.setCity(cityid); } List allCategoryList = serviceCateService.selectServiceCateList(serviceCateQuery); // 2. 分离一级分类和二级分类 List firstLevelCategories = new ArrayList<>(); Map> secondLevelMap = new HashMap<>(); for (ServiceCate category : allCategoryList) { if (category.getParentId() == null || category.getParentId() == 0L) { // 一级分类 firstLevelCategories.add(category); } else { // 二级分类,按父级ID分组 secondLevelMap.computeIfAbsent(category.getParentId(), k -> new ArrayList<>()).add(category); } } // 3. 构建简化的分类数据(只包含title和icon) List> resultList = new ArrayList<>(); for (ServiceCate firstLevel : firstLevelCategories) { Map firstLevelData = new HashMap<>(); firstLevelData.put("id", firstLevel.getId()); firstLevelData.put("title", firstLevel.getTitle()); firstLevelData.put("icon", AppletControllerUtil.buildImageUrl(firstLevel.getIcon())); // 4. 处理二级分类 List> childrenList = new ArrayList<>(); List children = secondLevelMap.get(firstLevel.getId()); if (children != null && !children.isEmpty()) { for (ServiceCate child : children) { Map childData = new HashMap<>(); childData.put("id", child.getId()); childData.put("title", child.getTitle()); childData.put("icon", AppletControllerUtil.buildImageUrl(child.getIcon())); childrenList.add(childData); } } firstLevelData.put("children", childrenList); resultList.add(firstLevelData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { return AppletControllerUtil.appletError("获取服务分类列表失败:" + e.getMessage()); } } /** * 获取系统配置信息 * 功能说明: * - 根据配置名称获取对应的配置值 * - 配置值以JSON格式返回 * - 支持动态配置管理 * * @param name 配置项名称 * @param request HTTP请求对象 * @return 配置信息数据 */ @GetMapping(value = "/api/public/config/{name}") public AjaxResult getConfig(@PathVariable("name") String name, HttpServletRequest request) { try { // 参数验证 if (StringUtils.isEmpty(name)) { return AppletControllerUtil.appletWarning("配置名称不能为空"); } // 查询配置信息 SiteConfig config = AppletControllerUtil.getSiteConfig(name, siteConfigService); if (config == null) { return AppletControllerUtil.appletWarning("未找到指定的配置项:" + name); } // 解析配置值为JSON对象 JSONObject configJson = AppletControllerUtil.parseConfigValue(config.getValue()); return AppletControllerUtil.appletSuccess(configJson); } catch (Exception e) { return AppletControllerUtil.appletError("获取配置信息失败:" + e.getMessage()); } } /** * 获取默认配置信息 * * @param request HTTP请求对象 * @return 返回config_one配置的JSON对象 *

* 功能说明: * - 获取名为"config_one"的系统配置 * - 将配置值解析为JSON对象并返回 * - 用于小程序获取基础配置信息 */ @GetMapping(value = "/api/public/get/config") public AjaxResult getconfig(HttpServletRequest request) { try { SiteConfig configQuery = new SiteConfig(); configQuery.setName("config_one"); List list = siteConfigService.selectSiteConfigList(configQuery); if (list != null && !list.isEmpty()) { JSONObject jsonObject = JSONObject.parseObject(list.get(0).getValue()); return AppletControllerUtil.appletSuccess(jsonObject); } else { return AppletControllerUtil.appletWarning("未找到默认配置信息"); } } catch (Exception e) { return AppletControllerUtil.appletError("获取配置信息失败:" + e.getMessage()); } } /** * 查询用户收货地址列表 * * @param limit 每页显示数量 * @param page 页码 * @param request HTTP请求对象 * @return 分页地址列表 *

* 请求参数: * - limit: 每页显示数量,默认15 * - page: 页码,默认1 *

*/ @GetMapping("/api/user/address/list") public AjaxResult getaddresslist( @RequestParam(value = "limit", defaultValue = "15") int limit, @RequestParam(value = "page", defaultValue = "1") int page, HttpServletRequest request) { try { // 1. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 设置分页参数 PageHelper.startPage(page, limit); // 5. 查询用户地址列表 UserAddress userAddressQuery = new UserAddress(); userAddressQuery.setUid(user.getId()); List addressList = userAddressService.selectUserAddressList(userAddressQuery); // 6. 获取分页信息并构建响应 TableDataInfo tableDataInfo = getDataTable(addressList); // 7. 构建符合要求的分页响应格式 Map pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit); return AppletControllerUtil.appletSuccess(pageData); } catch (Exception e) { System.err.println("查询用户地址列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询地址列表失败:" + e.getMessage()); } } /** * 根据地址ID查询用户收货地址详情 * * @param id 地址ID * @param request HTTP请求对象 * @return 地址详细信息 *

* 接口说明: * - 根据地址ID获取单个地址的详细信息 * - 验证用户登录状态和地址归属权 * - 返回AddressApple格式的地址数据,用于前端修改页面 *

*/ @GetMapping("/api/user/address/info/{id}") public AjaxResult getAddressInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 1. 参数验证 if (id == null || id <= 0) { return AppletControllerUtil.appletWarning("地址ID无效"); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 查询地址信息 UserAddress userAddress = userAddressService.selectUserAddressById(id); if (userAddress == null) { return AppletControllerUtil.appletWarning("地址不存在"); } // 5. 验证地址归属权 if (!userAddress.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权访问该地址信息"); } // 6. 转换为AddressApple格式并返回 AddressApple addressApple = AddressApple.fromUserAddress(userAddress); return AppletControllerUtil.appletSuccess(addressApple); } catch (Exception e) { System.err.println("查询用户地址详情异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询地址详情失败:" + e.getMessage()); } } /** * 修改用户收货地址 * * @param params 地址修改参数 * @param request HTTP请求对象 * @return 修改结果 * 接口说明: * - 验证用户登录状态和地址归属权 * - 支持修改地址的所有字段 * - 自动处理默认地址逻辑(设为默认时会取消其他默认地址) * - 返回修改后的地址信息 */ @PostMapping("/api/user/address/edit") public AjaxResult editAddress(@RequestBody Map params, HttpServletRequest request) { try { // 1. 参数验证 if (params == null || params.get("id") == null) { return AppletControllerUtil.appletWarning("地址ID不能为空"); } Long addressId; try { addressId = Long.valueOf(params.get("id").toString()); if (addressId <= 0) { return AppletControllerUtil.appletWarning("地址ID无效"); } } catch (NumberFormatException e) { return AppletControllerUtil.appletWarning("地址ID格式错误"); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 查询原地址信息并验证归属权 UserAddress existingAddress = userAddressService.selectUserAddressById(addressId); if (existingAddress == null) { return AppletControllerUtil.appletWarning("地址不存在"); } if (!existingAddress.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权修改该地址"); } // 5. 构建更新的地址对象 UserAddress updateAddress = AppletControllerUtil.buildUpdateAddress(params, addressId, user.getId()); // 6. 验证必填字段 String validationResult = AppletControllerUtil.validateAddressParams(updateAddress); if (validationResult != null) { return AppletControllerUtil.appletWarning(validationResult); } // 7. 处理默认地址逻辑 if (updateAddress.getIsDefault() != null && updateAddress.getIsDefault() == 1L) { // 如果设置为默认地址,先将该用户的所有地址设为非默认 userAddressService.updateUserAddressDefault(user.getId()); } // 8. 执行地址更新 int updateResult = userAddressService.updateUserAddress(updateAddress); if (updateResult > 0) { return AppletControllerUtil.appletSuccess("地址修改成功"); } else { return AppletControllerUtil.appletWarning("地址修改失败"); } } catch (Exception e) { System.err.println("修改用户地址异常:" + e.getMessage()); return AppletControllerUtil.appletError("修改地址失败:" + e.getMessage()); } } /** * 新增用户收货地址 * * @param params 地址新增参数 * @param request HTTP请求对象 * @return 新增结果 * 接口说明: * - 验证用户登录状态 * - 支持新增地址的所有字段 * - 自动处理默认地址逻辑(设为默认时会取消其他默认地址) * - 返回新增后的地址信息 */ @PostMapping("/api/user/address/add") public AjaxResult addAddress(@RequestBody Map params, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 构建新增的地址对象 UserAddress newAddress = AppletControllerUtil.buildNewAddress(params, user.getId()); // 4. 验证必填字段 String validationResult = AppletControllerUtil.validateAddressParams(newAddress); if (validationResult != null) { return AppletControllerUtil.appletWarning(validationResult); } // 5. 处理默认地址逻辑 if (newAddress.getIsDefault() != null && newAddress.getIsDefault() == 1L) { // 如果设置为默认地址,先将该用户的所有地址设为非默认 userAddressService.updateUserAddressDefault(user.getId()); } // 6. 执行地址新增 int insertResult = userAddressService.insertUserAddress(newAddress); if (insertResult > 0) { return AppletControllerUtil.appletSuccess("地址新增成功"); } else { return AppletControllerUtil.appletWarning("地址新增失败"); } } catch (Exception e) { System.err.println("新增用户地址异常:" + e.getMessage()); return AppletControllerUtil.appletError("新增地址失败:" + e.getMessage()); } } /** * 售后返修申请接口 * * @param params 请求参数 包含order_id(订单ID)、phone(联系电话)、mark(返修原因备注) * @param request HTTP请求对象 * @return 返修申请结果 *

* 功能说明: * - 验证用户登录状态和订单归属权 * - 检查订单状态是否允许申请售后 * - 处理售后返修申请逻辑 * - 更新订单状态为售后处理中 * - 记录返修申请信息和联系方式 *

* 请求参数: * - order_id: 订单ID * - phone: 联系电话 * - mark: 返修原因备注 */ @PostMapping("/api/service/order/rework") public AjaxResult serviceOrderRework(@RequestBody Map params, HttpServletRequest request) { try { // 1. 参数验证 if (params == null) { return AppletControllerUtil.appletWarning("请求参数不能为空"); } String orderId = (String) params.get("order_id"); String phone = (String) params.get("phone"); String mark = (String) params.get("mark"); if (StringUtils.isEmpty(orderId)) { return AppletControllerUtil.appletWarning("订单ID不能为空"); } if (StringUtils.isEmpty(phone)) { return AppletControllerUtil.appletWarning("联系电话不能为空"); } // 验证手机号格式 if (!phone.matches("^1[3-9]\\d{9}$")) { return AppletControllerUtil.appletWarning("联系电话格式不正确"); } if (StringUtils.isEmpty(mark)) { return AppletControllerUtil.appletWarning("返修原因不能为空"); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 查询订单信息并验证归属权 Order order = orderService.selectOrderByOrderId(orderId); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } if (!order.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权操作此订单"); } // 5. 验证订单状态是否允许申请售后 if (!AppletControllerUtil.isOrderAllowRework(order.getStatus())) { return AppletControllerUtil.appletWarning("当前订单状态不允许申请售后"); } // 6. 处理售后返修申请 boolean reworkResult = AppletControllerUtil.processReworkApplication(order, phone, mark, user, orderReworkService, orderService); if (reworkResult) { return AppletControllerUtil.appletSuccess("售后返修申请已提交,我们会尽快联系您处理"); } else { return AppletControllerUtil.appletWarning("售后申请提交失败,请稍后重试"); } } catch (Exception e) { System.err.println("售后返修申请异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("售后申请失败:" + e.getMessage()); } } /** * 获取用户服务订单列表 * * @param params 请求参数 包含page(页码)、limit(每页数量)、status(订单状态) * @param request HTTP请求对象 * @return 返回分页的服务订单列表 *

* 功能说明: * - 获取当前登录用户的服务类订单(type=1) * - 支持按订单状态筛选 * - 返回带分页信息的订单列表 * - 自动填充商品信息(标题、图标、价格等) */ @PostMapping("api/service/order/lst") public AjaxResult getserviceorderlst(@RequestBody Map params, HttpServletRequest request) { int page = (int) params.get("page"); int limit = (int) params.get("limit"); String status = (String) params.get("status"); // 1. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 设置分页参数 PageHelper.startPage(page, limit); // 5. 查询用户地址列表 OrderApple order = new OrderApple(); // order.setType(1); order.setUid(user.getId()); if (StringUtils.isNotNull(status) && !"".equals(status)) { order.setStatus(Long.valueOf(status)); } List orderList = orderService.selectOrderAppleList(order); for (OrderApple orderdata : orderList) { Map jsonObject = new HashMap<>(); if (orderdata.getProduct_id() != null) { ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(orderdata.getProduct_id()); if (serviceGoods != null) { jsonObject.put("title", serviceGoods.getTitle()); jsonObject.put("icon", "https://img.huafurenjia.cn/" + serviceGoods.getIcon()); jsonObject.put("id", serviceGoods.getId()); jsonObject.put("price_zn", serviceGoods.getPriceZn()); jsonObject.put("sub_title", serviceGoods.getSubTitle()); orderdata.setProduct(jsonObject); } } } // 6. 获取分页信息并构建响应 TableDataInfo tableDataInfo = getDataTable(orderList); // 7. 构建符合要求的分页响应格式 Map pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit); return AppletControllerUtil.appletSuccess(pageData); } /** * 获取用户商品订单列表 * * @param params 请求参数 包含page(页码)、limit(每页数量)、status(订单状态) * @param request HTTP请求对象 * @return 返回分页的商品订单列表 *

* 功能说明: * - 获取当前登录用户的商品类订单 * - 支持按订单状态筛选 * - 返回带分页信息的订单列表 * - 包含完整的商品信息和订单状态文本 */ @PostMapping("/api/goods/order/lst") public AjaxResult getgoodsorderlst(@RequestBody Map params, HttpServletRequest request) { try { int page = (int) params.get("page"); int limit = (int) params.get("limit"); String status = (String) params.get("status"); // 1. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 设置分页参数 PageHelper.startPage(page, limit); // 5. 构建查询条件 GoodsOrder queryOrder = new GoodsOrder(); queryOrder.setUid(user.getId()); if (StringUtils.isNotNull(status) && !status.isEmpty()) { if ("7".equals(status)){ queryOrder.setReturnstatus(7L); }else{ queryOrder.setStatus(Long.valueOf(status)); } } // 6. 查询商品订单列表 List orderList = goodsOrderService.selectGoodsOrdergrouBymAIDList(queryOrder); // 7. 为每个订单填充商品信息 List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (GoodsOrder order : orderList) { Map orderData = new HashMap<>(); // 订单基本信息 orderData.put("id", order.getId()); orderData.put("order_id", order.getMainOrderId()); orderData.put("order_no", order.getMainOrderId()); // 小程序常用字段 orderData.put("status", order.getStatus()); orderData.put("status_text", getOrderStatusText(order.getStatus())); // 状态文本 orderData.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); orderData.put("num", order.getNum()); if (order.getSku() != null) { orderData.put("sku",AppletControllerUtil.parseSkuStringToObject(order.getSku())); } else { orderData.put("sku", null); } // 时间字段格式化 if (order.getPayTime() != null) { orderData.put("pay_time", sdf.format(order.getPayTime())); } else { orderData.put("pay_time", null); } if (order.getCreatedAt() != null) { orderData.put("created_at", sdf.format(order.getCreatedAt())); } else { orderData.put("created_at", null); } GoodsOrder goodsOrderDATA = new GoodsOrder(); goodsOrderDATA.setMainOrderId(order.getMainOrderId()); List goodsOrderList = goodsOrderService.selectGoodsOrderList(goodsOrderDATA); List> goodsOrderListDATA = new ArrayList<>(); for (GoodsOrder goodsOrder : goodsOrderList) { ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsOrder.getProductId()); if (serviceGoods != null) { Map productInfo = new HashMap<>(); productInfo.put("id", serviceGoods.getId()); productInfo.put("title", serviceGoods.getTitle()); productInfo.put("sub_title", serviceGoods.getSubTitle()); productInfo.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); productInfo.put("price", goodsOrder.getTotalPrice() != null ? goodsOrder.getTotalPrice().toString() : "0.00"); productInfo.put("sku",AppletControllerUtil.parseSkuStringToObject(goodsOrder.getSku())); productInfo.put("num", goodsOrder.getNum()); goodsOrderListDATA.add(productInfo); } } orderData.put("product", goodsOrderListDATA); resultList.add(orderData); } // 6. 构建分页信息 // PageInfo pageInfo = new PageInfo<>(orderList); PageInfo pageInfo = new PageInfo<>(orderList); // 7. 构建返回数据格式 Map responseData = new HashMap<>(); responseData.put("current_page", pageInfo.getPageNum()); responseData.put("data", resultList); responseData.put("from", pageInfo.getStartRow()); responseData.put("last_page", pageInfo.getPages()); responseData.put("per_page", pageInfo.getPageSize()); responseData.put("to", pageInfo.getEndRow()); responseData.put("total", pageInfo.getTotal()); // 构建分页链接信息 String baseUrl = "https://www.huafurenjia.cn/api/goods/order/lst/"; responseData.put("first_page_url", baseUrl + "?page=1"); responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); responseData.put("next_page_url", pageInfo.isHasNextPage() ? baseUrl + "?page=" + pageInfo.getNextPage() : null); responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? baseUrl + "?page=" + pageInfo.getPrePage() : null); responseData.put("path", baseUrl); // // // 8. 构建分页信息 // PageInfo pageInfo = new PageInfo<>(orderList); // // 9. 构建返回数据格式(简化版本,更适合小程序) // Map responseData = new HashMap<>(); // responseData.put("current_page", pageInfo.getPageNum()); // responseData.put("data", resultList); // responseData.put("total", pageInfo.getTotal()); // responseData.put("per_page", pageInfo.getPageSize()); // responseData.put("last_page", pageInfo.getPages()); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { System.err.println("查询商品订单列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询商品订单列表失败:" + e.getMessage()); } } /** * 获取订单状态文本 * * @param status 订单状态 * @return 状态文本 */ private String getOrderStatusText(Long status) { if (status == null) { return "未知状态"; } switch (status.intValue()) { case 1: return "待付款"; case 2: return "待发货"; case 3: return "待收货"; case 4: return "待评价"; case 5: return "已完成"; case 6: return "已取消"; case 7: return "售后中"; case 8: return "已退款"; default: return "未知状态"; } } /** * 用户登录验证接口 * * @param request HTTP请求对象 * @return 返回用户信息或错误信息 *

* 功能说明: * - 通过请求头中的token验证用户身份 * - 查询用户基本信息并返回 * - 设置remember_token字段用于前端使用 */ @PostMapping(value = "/api/user/login") public AjaxResult getuserlogin(HttpServletRequest request) { String token = request.getHeader("token"); Map result = new HashMap<>(); Users users = usersService.selectUsersByRememberToken(token); if (users != null) { result.put("user", users); users.setRemember_token(users.getRememberToken()); return AppletControllerUtil.appletSuccess(result); } else { result.put("user", ""); return AppletControllerUtil.appletSuccess(result); } } /** * 获取服务商品列表 * 前端参数格式:{cate_id: 18} * 业务逻辑: * - 如果cate_id为空或null:返回所有分类的服务分组 * - 如果是一级分类:返回该一级分类下的服务分组 + 该一级分类下所有二级分类的服务分组 * - 如果是二级分类:返回该二级分类下的服务分组 * 返回格式:分类title + [服务列表] 的分组结构 */ @PostMapping(value = "/api/service/lst") public AjaxResult getServiceGoodsList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 获取分类ID参数 String city = request.getHeader("ct"); Long cateId = null; if (params.get("cate_id") != null) { Object cateIdObj = params.get("cate_id"); try { if (cateIdObj instanceof Integer) { cateId = ((Integer) cateIdObj).longValue(); } else if (cateIdObj instanceof String) { String cateIdStr = cateIdObj.toString().trim(); if (!cateIdStr.isEmpty()) { cateId = Long.parseLong(cateIdStr); } } else { cateId = Long.parseLong(cateIdObj.toString()); } } catch (NumberFormatException e) { return AppletControllerUtil.appletkaifaWarning("分类ID格式错误"); } } // 2. 如果cate_id为空,查询默认的服务分类 if (cateId == null) { // 查询启用状态、类型为服务、排序第一的分类 ServiceCate defaultCateQuery = new ServiceCate(); if (StringUtils.isNotBlank(city)){ defaultCateQuery.setCity(city); } defaultCateQuery.setStatus(1L); // 启用状态 defaultCateQuery.setType(1L); // 类型为服务(假设1为服务类型) List defaultCateList = serviceCateService.selectServiceCateList(defaultCateQuery); if (defaultCateList.isEmpty()) { return AppletControllerUtil.appletkaifaWarning("未找到默认服务分类"); } // 按排序字段升序排列,取第一个 defaultCateList.sort((a, b) -> { Long sortA = a.getSort() != null ? a.getSort() : Long.MAX_VALUE; Long sortB = b.getSort() != null ? b.getSort() : Long.MAX_VALUE; return sortA.compareTo(sortB); }); // 给cate_id赋值为排序第一的分类ID cateId = defaultCateList.get(0).getId(); } // 3. 构建返回数据 List> resultList = new ArrayList<>(); // 3. 查询分类信息,判断是一级还是二级分类 ServiceCate category = serviceCateService.selectServiceCateById(cateId); if (category == null) { return AppletControllerUtil.appletkaifaWarning("分类不存在"); } if (category.getParentId() == null || category.getParentId() == 0L) { // 一级分类:返回该一级分类的服务分组 + 所有二级分类的服务分组 // 先添加一级分类本身的服务 List> firstLevelServices = getServicesByCategory(cateId, city); if (!firstLevelServices.isEmpty()) { Map firstLevelGroup = new HashMap<>(); firstLevelGroup.put("id", category.getId()); firstLevelGroup.put("title", category.getTitle()); firstLevelGroup.put("services", firstLevelServices); resultList.add(firstLevelGroup); } // 再添加该一级分类下所有二级分类的服务分组 ServiceCate childQuery = new ServiceCate(); childQuery.setParentId(cateId); childQuery.setStatus(1L); List childCategories = serviceCateService.selectServiceCateList(childQuery); for (ServiceCate child : childCategories) { List> childServices = getServicesByCategory(child.getId(), city); if (!childServices.isEmpty()) { Map childGroup = new HashMap<>(); childGroup.put("id", category.getId()); childGroup.put("title", child.getTitle()); childGroup.put("services", childServices); resultList.add(childGroup); } } } else { // 二级分类:只返回该二级分类的服务分组 List> services = getServicesByCategory(cateId, city); if (!services.isEmpty()) { Map group = new HashMap<>(); group.put("id", category.getId()); group.put("title", category.getTitle()); group.put("services", services); resultList.add(group); } } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { return AppletControllerUtil.appletkaifaWarning("查询服务商品列表失败:" + e.getMessage()); } } /** * 根据分类ID查询该分类下的服务列表 * @param categoryId 分类ID * @return 服务列表(只包含id、title、icon) */ private List> getServicesByCategory(Long categoryId,String city) { List> serviceList = new ArrayList<>(); ServiceGoods queryGoods = new ServiceGoods(); queryGoods.setCateId(categoryId); queryGoods.setStatus("1"); // 只查询启用状态的商品 if (StringUtils.isNotBlank(city)){ queryGoods.setCity(city); } List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); for (ServiceGoods goods : goodsList) { Map serviceData = new HashMap<>(); serviceData.put("id", goods.getId()); serviceData.put("title", goods.getTitle()); serviceData.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); serviceList.add(serviceData); } return serviceList; } /** * 获取服务商品详细信息 * * @param id 商品ID * @param request HTTP请求对象 * @return 商品详细信息 *

* 接口说明: * - 根据商品ID获取详细信息 * - type=1时返回ServiceGoodsResponse格式 * - type=2时返回json.txt中的商品格式 * - 包含图片、基础信息等数组数据 */ @GetMapping(value = "/api/service/info/id/{id}") public AjaxResult serviceGoodsQuery(@PathVariable("id") long id, @RequestParam(value = "type", required = false) Integer type, HttpServletRequest request) { try { // 参数验证 if (id <= 0) { return AppletControllerUtil.appletError("商品ID无效"); } // 查询商品信息 ServiceGoods serviceGoodsData = serviceGoodsService.selectServiceGoodsById(id); if (serviceGoodsData == null) { return AppletControllerUtil.appletError("商品不存在或已下架"); } if (type != null && type == 1) { if (serviceGoodsData.getIsgroup()!=1){ return AppletControllerUtil.appletError("改服务不是拼团服务"); } } //次卡详情 if (type != null && type == 2) { UserSecondaryCard goods = userSecondaryCardService.selectUserSecondaryCardById(id); Map map = new HashMap<>(); map.put("isyikoujia", 1); map.put("id", goods.getId()); map.put("allsellnum", 10); map.put("orderid", goods.getOrderid()); map.put("title", goods.getTitle()); map.put("goodsids", goods.getGoodsids()); map.put("show_money", goods.getShowMoney()); map.put("real_money", goods.getRealMoney()); map.put("showimage", AppletControllerUtil.buildImageUrl(goods.getShowimage())); map.put("carouselImage", AppletControllerUtil.parseImagesStringToArray(goods.getCarouselImage())); map.put("status", goods.getStatus()); map.put("creattime", goods.getCreattime()); map.put("type", goods.getType()); map.put("num", goods.getNum()); map.put("allnum", goods.getAllnum()); map.put("introduction", goods.getIntroduction()); List idsList = JSONArray.parseArray(goods.getGoodsids(), String.class); List serviceGoodsList = serviceGoodsService.selectServiceGoodsfrocikaList(idsList); List> serviceDetail = new ArrayList<>(); if(serviceGoodsList != null && !serviceGoodsList.isEmpty()) { for(ServiceGoods serviceGoods : serviceGoodsList) { Map card = new HashMap<>(); card.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); card.put("title", serviceGoods.getTitle()); card.put("price", serviceGoods.getPrice()); card.put("id", serviceGoods.getId()); serviceDetail.add( card); } } map.put("serviceDetail", serviceDetail); // card.setServiceDetail(serviceGoodsService.selectServiceGoodsfrocikaList(idsList)); return AppletControllerUtil.appletSuccess(map); } //拼团详情 // 原有逻辑:普通服务详情 if (serviceGoodsData.getType() != null && serviceGoodsData.getType() == 2) { // type=2时返回json.txt格式 Map goodsData = AppletControllerUtil.buildType2ServiceGoodsResponse(serviceGoodsData); return AppletControllerUtil.appletSuccess(goodsData); } else { // type=1时返回ServiceGoodsResponse格式 Map goodsData = AppletControllerUtil.buildType2ServiceGoodsResponse(serviceGoodsData); //根据需求就要添加拼团相关数据 if (type != null) { //拼团独有数据 if (type == 1) { // 拼团服务详情 goodsData.put("isyikoujia", 1); goodsData.put("allsellnum", 10); goodsData.put("isgroup", serviceGoodsData.getIsgroup()); goodsData.put("groupnum", serviceGoodsData.getGroupnum()); goodsData.put("groupprice", serviceGoodsData.getGroupprice()); List> groupBuyingList = userGroupBuyingService.selectGroupBuyingGroupByProductAndOrder(Math.toIntExact(serviceGoodsData.getId())); for (Map groupBuying : groupBuyingList) { //还差几人成团 JSONArray groupBuyingArray = JSONArray.parseArray(groupBuying.get("name").toString()); // JSONArray groupBuyingArray =new JSONArray(); groupBuying.put("neednum", serviceGoodsData.getGroupnum() - groupBuyingArray.size()); groupBuying.put("image", AppletControllerUtil.parseImagesStringToArray(groupBuying.get("image").toString())); //parseImagesStringToArray(goods.getImgs()) //groupBuying.put("neednum", AppletControllerUtil.buildImageUrl(groupBuying.get("image").toString())); } goodsData.put("groupBuyData", groupBuyingList); } //秒杀独有数据 if (type == 3) { // 获取秒杀相关数据 long msdata = 0L; try { // 获取config_one配置中的秒杀结束时间 SiteConfig configQuery = new SiteConfig(); configQuery.setName("config_one"); List configList = siteConfigService.selectSiteConfigList(configQuery); if (configList != null && !configList.isEmpty()) { String configValue = configList.get(0).getValue(); if (configValue != null && !configValue.trim().isEmpty()) { JSONObject configJson = JSONObject.parseObject(configValue); String mstime = configJson.getString("mstime"); if (mstime != null && !mstime.trim().isEmpty()) { // 解析秒杀结束时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date endTime = sdf.parse(mstime); msdata = endTime.getTime(); // 返回结束时间的毫秒数 } } } } catch (Exception e) { // 解析异常时设置为0 msdata = 0L; } // 秒杀服务详情 goodsData.put("isyikoujia", 1); goodsData.put("msdata", msdata); goodsData.put("allsellnum", 10); goodsData.put("isfixed", serviceGoodsData.getIsfixed()); goodsData.put("fixedprice", serviceGoodsData.getFixedprice()); } //报价数据下师傅的报价详情 if (type == 4) { goodsData.put("isyikoujia", 2); // 秒杀服务详情 // List> quoteList = new List>() ; // // goodsData.put("isfixed", serviceGoodsData.getIsfixed()); // goodsData.put("fixedprice", serviceGoodsData.getFixedprice()); } }else{ goodsData.put("isyikoujia", 2); } return AppletControllerUtil.appletSuccess(goodsData); } } catch (Exception e) { return AppletControllerUtil.appletError("查询商品详情失败:" + e.getMessage()); } } /** * 获取广告图片列表 * * @param type 广告类型 * @param request HTTP请求对象 * @return 广告图片列表 *

* 接口说明: * - 根据广告类型获取对应的图片列表 * - 自动添加图片CDN前缀 * - 支持多种广告位配置 */ @GetMapping(value = "/api/public/adv/lst/{type}") public AjaxResult getAdvImgData(@PathVariable("type") long type, HttpServletRequest request) { try { // 参数验证 if (type < 0) { return AppletControllerUtil.appletWarning("广告类型无效"); } // 构建查询条件 AdvImg advImgQuery = new AdvImg(); advImgQuery.setType(type); advImgQuery.setStatus(1L); // 查询广告图片列表 List advImgList = advImgService.selectAdvImgList(advImgQuery); // 为每张图片添加CDN前缀 for (AdvImg advImg : advImgList) { advImg.setImage(AppletControllerUtil.buildImageUrl(advImg.getImage())); } return AppletControllerUtil.appletSuccess(advImgList); } catch (Exception e) { return AppletControllerUtil.appletWarning("获取广告图片失败:" + e.getMessage()); } } /** * 获取商城分类列表 * * @param request HTTP请求对象 * @return 商城分类列表 *

* 接口说明: * - 查询类型为商品且状态为启用的分类数据 * - 只返回title和icon字段 * - 自动添加图片CDN前缀 * - 保持原有排序不变 * - 无需用户登录验证 */ @GetMapping(value = "/api/mall/cate/lst") public AjaxResult getMallCategoryList(HttpServletRequest request) { try { // 构建查询条件 ServiceCate serviceCateQuery = new ServiceCate(); serviceCateQuery.setStatus(1L); // 状态为启用 serviceCateQuery.setType(2L); // 类型为商品(假设2为商品类型,请根据实际业务调整) // 查询商城分类列表 List categoryList = serviceCateService.selectServiceCateList(serviceCateQuery); // 构建返回数据(只包含title和icon) List> resultList = new ArrayList<>(); for (ServiceCate category : categoryList) { Map categoryData = new HashMap<>(); categoryData.put("id", category.getId()); categoryData.put("title", category.getTitle()); categoryData.put("icon", AppletControllerUtil.buildImageUrl(category.getIcon())); resultList.add(categoryData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { return AppletControllerUtil.appletError("获取商城分类列表失败:" + e.getMessage()); } } /** * 获取热门推荐商品 * * @param request HTTP请求对象 * @return 热门推荐商品列表(销量前6个) *

* 接口说明: * - 查询type=2的商品 * - 按销量降序排列,取前6个 * - 返回id、title、icon、price、sales字段 * - 自动添加图片CDN前缀 * - 无需用户登录验证 */ @GetMapping(value = "/api/hot/recommend") public AjaxResult getHotRecommendGoods(HttpServletRequest request) { try { // 构建查询条件 ServiceGoods queryGoods = new ServiceGoods(); queryGoods.setType(2); // 查询type=2的商品 queryGoods.setStatus("1"); // 只查询启用状态的商品 // 查询符合条件的商品列表 List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); // 按销量降序排序 goodsList.sort((a, b) -> { Long salesA = a.getSales() != null ? a.getSales() : 0L; Long salesB = b.getSales() != null ? b.getSales() : 0L; return salesB.compareTo(salesA); }); // 取前6个 if (goodsList.size() > 6) { goodsList = goodsList.subList(0, 6); } // 构建返回数据 List> resultList = new ArrayList<>(); for (ServiceGoods goods : goodsList) { Map goodsData = new HashMap<>(); goodsData.put("id", goods.getId()); goodsData.put("title", goods.getTitle()); goodsData.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); goodsData.put("price", goods.getPrice() != null ? goods.getPrice().toString() : "0.00"); goodsData.put("sales", goods.getSales() != null ? goods.getSales() : 0L); resultList.add(goodsData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { return AppletControllerUtil.appletError("获取热门推荐商品失败:" + e.getMessage()); } } /** * 根据分类ID查询商品列表 * * @param request HTTP请求对象 * @return 该分类下的商品列表 *

* 接口说明: * - 根据分类ID查询商品 * - 只查询启用状态的商品 * - 返回id、title、icon、price、sales字段 * - 自动添加图片CDN前缀 * - 无需用户登录验证 */ @PostMapping(value = "/api/goods/cate") public AjaxResult getGoodsByCategory(@RequestBody Map params, HttpServletRequest request) { try { // 1. 获取分页参数 int page = params.get("page") != null ? (Integer) params.get("page") : 1; int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; String cateId = params.get("cateId").toString(); // 验证分页参数 if (page < 1) page = 1; if (limit < 1) limit = 15; // if (limit > 100) limit = 100; // 限制最大每页数量 // 2. 设置分页参数 PageHelper.startPage(page, limit); // 3. 构建查询条件 ServiceGoods queryGoods = new ServiceGoods(); queryGoods.setStatus("1"); // 只查询启用状态的商品 queryGoods.setType(2);// 只查询商品类 // 判断是否查询全部商品 boolean queryAll = "00".equals(cateId.trim()) || cateId.trim().isEmpty(); if (!queryAll) { // 验证分类ID格式 Long categoryId; try { categoryId = Long.parseLong(cateId); if (categoryId <= 0) { return AppletControllerUtil.appletWarning("分类ID无效"); } } catch (NumberFormatException e) { return AppletControllerUtil.appletWarning("分类ID格式错误"); } // 验证分类是否存在 ServiceCate category = serviceCateService.selectServiceCateById(categoryId); if (category == null) { return AppletControllerUtil.appletWarning("分类不存在"); } queryGoods.setCateId(categoryId); // 根据分类ID查询 } // 4. 查询商品列表 List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); // 5. 构建返回数据 List> resultList = new ArrayList<>(); for (ServiceGoods goods : goodsList) { Map goodsData = new HashMap<>(); goodsData.put("id", goods.getId()); goodsData.put("title", goods.getTitle()); goodsData.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); goodsData.put("price", goods.getPrice() != null ? goods.getPrice().toString() : "0.00"); goodsData.put("sales", goods.getSales() != null ? goods.getSales() : 0L); goodsData.put("cate_id", goods.getCateId()); resultList.add(goodsData); } // 6. 构建分页信息 PageInfo pageInfo = new PageInfo<>(goodsList); // 7. 构建返回数据格式 Map responseData = new HashMap<>(); responseData.put("current_page", pageInfo.getPageNum()); responseData.put("data", resultList); responseData.put("from", pageInfo.getStartRow()); responseData.put("last_page", pageInfo.getPages()); responseData.put("per_page", pageInfo.getPageSize()); responseData.put("to", pageInfo.getEndRow()); responseData.put("total", pageInfo.getTotal()); // 构建分页链接信息 String baseUrl = "https://www.huafurenjia.cn/api/goods/cate/" + cateId; responseData.put("first_page_url", baseUrl + "?page=1"); responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); responseData.put("next_page_url", pageInfo.isHasNextPage() ? baseUrl + "?page=" + pageInfo.getNextPage() : null); responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? baseUrl + "?page=" + pageInfo.getPrePage() : null); responseData.put("path", baseUrl); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { return AppletControllerUtil.appletError("查询分类商品失败:" + e.getMessage()); } } /** * 获取一级城市列表 * * @param request HTTP请求对象 * @return 一级城市列表 *

* 接口说明: * - 查询parent_id=0的城市数据 * - 只返回id和title字段 * - 无需用户登录验证 */ @GetMapping(value = "/api/city/list") public AjaxResult getCityList(HttpServletRequest request) { try { // 构建查询条件 DiyCity queryCond = new DiyCity(); queryCond.setParentId(0L); // 查询parent_id=0的一级城市 // 查询一级城市列表 List cityList = diyCityService.selectDiyCityList(queryCond); // 构建返回数据(只包含id和title) List> resultList = new ArrayList<>(); for (DiyCity city : cityList) { Map cityData = new HashMap<>(); cityData.put("id", city.getId()); cityData.put("title", city.getTitle()); resultList.add(cityData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { return AppletControllerUtil.appletError("获取城市列表失败:" + e.getMessage()); } } /** * 根据经纬度获取城市信息 * * @param params 请求参数,包含latitude(纬度)、longitude(经度) * @param request HTTP请求对象 * @return 城市信息 *

* 接口说明: * - 接收前端传入的经纬度坐标 * - 调用高德地图逆地理编码API获取城市信息 * - 返回城市名称和详细地址信息 * - 无需用户登录验证 */ @PostMapping(value = "/api/location/city") public AjaxResult getCityByLocation(@RequestBody Map params, HttpServletRequest request) { try { // 1. 参数验证 if (params == null) { return AppletControllerUtil.appletWarning("请求参数不能为空"); } String latitude = params.get("latitude") != null ? params.get("latitude").toString() : ""; String longitude = params.get("longitude") != null ? params.get("longitude").toString() : ""; if (latitude.isEmpty() || longitude.isEmpty()) { return AppletControllerUtil.appletWarning("经纬度参数不能为空"); } // 验证经纬度格式并转换为double double lat, lng; try { lat = Double.parseDouble(latitude); lng = Double.parseDouble(longitude); // 验证经纬度范围 if (lat < -90 || lat > 90) { return AppletControllerUtil.appletWarning("纬度范围应在-90到90之间"); } if (lng < -180 || lng > 180) { return AppletControllerUtil.appletWarning("经度范围应在-180到180之间"); } } catch (NumberFormatException e) { return AppletControllerUtil.appletWarning("经纬度格式错误"); } // 2. 调用高德地图工具类获取位置信息 String city = GaoDeMapUtil.getCityByLocation(lng, lat); String address = GaoDeMapUtil.getAddressByLocation(lng, lat); // 3. 构建返回数据 Map locationInfo = new HashMap<>(); locationInfo.put("city", city != null ? city : ""); locationInfo.put("formatted_address", address != null ? address : ""); locationInfo.put("latitude", latitude); locationInfo.put("longitude", longitude); return AppletControllerUtil.appletSuccess(locationInfo); } catch (Exception e) { return AppletControllerUtil.appletError("获取位置信息失败:" + e.getMessage()); } } /** * 微信用户登录接口 * * @param params 请求参数 * @param request HTTP请求对象 * @return 登录结果 * 登录流程: * 1. 验证请求参数 * 2. 通过usercode获取微信openid * 3. 检查用户是否已存在(通过openid) * 4. 如果用户存在,直接返回用户信息 * 5. 如果用户不存在,获取手机号并创建/更新用户 */ @PostMapping(value = "/api/user/phone/login") public AjaxResult wechatLogin(@RequestBody Map params, HttpServletRequest request) { // 使用AppletLoginUtil执行完整的微信登录流程 return AppletLoginUtil.executeWechatLogin(params, usersService); } /** * 获取用户基本信息接口 * * @param request HTTP请求对象 * @return 用户基本信息 *

* 接口说明: * - 通过token获取当前登录用户的基本信息 * - 返回完整的用户数据 * - 需要用户登录验证 *

*/ @GetMapping(value = "/api/user/info") public AjaxResult apiuserinfo(HttpServletRequest request) { try { SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd"); Map order_num = new HashMap<>(); Map goods_order_num = new HashMap<>(); // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 构建用户信息响应数据 Map userInfo = buildUserInfoResponse(user); userInfo.put("remember_token", userInfo.get("rememberToken")); // 新增:根据会员状态查询充值项目 Integer queryType = (user.getIsmember() != null && user.getIsmember() == 1) ? 2 : 1; UserMemberRechargeProgram query = new UserMemberRechargeProgram(); query.setType(queryType); query.setStatus(0); // 只查启用 java.util.List rechargePrograms = userMemberRechargeProgramService.selectUserMemberRechargeProgramList(query); userInfo.put("memberRechargePrograms", rechargePrograms.getFirst()); //List counts = orderService.selectOrderCountByBigtype(user.getId()); // OrderTypeCount order_num.put("yuyue",orderService.selectOrderCountByBigtype(user.getId(),1)); order_num.put("baojia",orderService.selectOrderCountByBigtype(user.getId(),2)); order_num.put("yikoujia",orderService.selectOrderCountByBigtype(user.getId(),3)); userInfo.put("order_num", order_num); goods_order_num.put("daifukuan",goodsOrderService.countGoodsOrderByUidAndStatus(user.getId(),1)); goods_order_num.put("daifahuo",goodsOrderService.countGoodsOrderByUidAndStatus(user.getId(),2)); goods_order_num.put("daishouhuo",goodsOrderService.countGoodsOrderByUidAndStatus(user.getId(),3)); goods_order_num.put("daipingjia",goodsOrderService.countGoodsOrderByUidAndStatus(user.getId(),4)); goods_order_num.put("shouhou",goodsOrderService.countGoodsOrderByUidAndStatus(user.getId(),20)); userInfo.put("goods_order_num", goods_order_num); // 新增tx_time字段 List txTimeArr = new ArrayList<>(); try { SiteConfig configQuery = new SiteConfig(); configQuery.setName("config_four"); List configList = siteConfigService.selectSiteConfigList(configQuery); if (configList != null && !configList.isEmpty()) { String configValue = configList.get(0).getValue(); if (configValue != null && !configValue.trim().isEmpty()) { JSONObject json = JSONObject.parse(configValue); if (json.containsKey("time")) { Object timeObj = json.get("time"); if (timeObj instanceof List) { txTimeArr = (List) timeObj; } else if (timeObj instanceof JSONArray) { txTimeArr = ((JSONArray) timeObj).toJavaList(Object.class); } } } } } catch (Exception ignore) { } userInfo.put("tx_time", txTimeArr); // 新增:查询该用户可用优惠券数量 // int couponNum = CouponUtil.iscoupon(user.getId(), couponsService, couponUserService).size(); int couponNum = couponUserService.selectCountCouponsByUid(user.getId(), 1L); // try { // com.ruoyi.system.domain.CouponUser queryCoupon = new com.ruoyi.system.domain.CouponUser(); // queryCoupon.setUid(user.getId()); // queryCoupon.setStatus(0L); // 0=可用 // java.util.List couponList = couponUserService.selectCouponUserList(queryCoupon); // couponNum = couponList != null ? couponList.size() : 0; // } catch (Exception e) { // } userInfo.put("couponNum", couponNum); return AppletControllerUtil.appletSuccess(userInfo); } catch (Exception e) { System.err.println("查询用户基本信息异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询用户信息失败:" + e.getMessage()); } } /** * 构建用户信息响应数据 * * @param user 用户实体 * @return 格式化的用户信息 */ private Map buildUserInfoResponse(Users user) { Map userInfo = new HashMap<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd"); // 基本信息 userInfo.put("id", user.getId()); userInfo.put("name", user.getName()); userInfo.put("nickname", user.getNickname()); userInfo.put("phone", user.getPhone()); userInfo.put("password", null); // 密码不返回 // userInfo.put("ismember", user.getIsmember()); // if (user.getMemberBegin() != null) { // userInfo.put("member_begin", sdfday.format(user.getMemberBegin())); // } // if (user.getMemberEnd() != null){ // userInfo.put("member_end", sdfday.format(user.getMemberEnd())); // } // userInfo.put("member_begin", sdfday.format(user.getMemberBegin())); // userInfo.put("member_end", sdfday.format(user.getMemberEnd())); userInfo.put("balance", user.getBalance()); userInfo.put("shop_money", user.getConsumption()); userInfo.put("service_money", user.getServicefee()); userInfo.put("birthday",user.getBirthday() != null ? sdfday.format(user.getBirthday()) : null); // 头像处理 String avatar = user.getAvatar(); if (avatar != null && !avatar.isEmpty()) { userInfo.put("avatar", AppletControllerUtil.buildImageUrl(avatar)); } else { userInfo.put("avatar", "https://img.huafurenjia.cn/default/user_avatar.jpeg"); } // 其他业务字段 if (user.getType().equals("2")) { BigDecimal bb= user.getCommission(); //冻结金额 BigDecimal lookmoney= workerMoneyLogService.selectWorkerLookMoneySum(Math.toIntExact(user.getId())); if (user.getCommission()== null) { bb= new BigDecimal(0); } userInfo.put("commission", bb.subtract(lookmoney)); userInfo.put("total_comm", user.getTotalComm() != null ? user.getTotalComm().toString() : "0.00"); userInfo.put("propose", user.getPropose() != null ? user.getPropose().toString() : "0.00"); userInfo.put("lookmoney",lookmoney); userInfo.put("workerLatitude",user.getWorkerLatitude()); userInfo.put("workerLongitude",user.getWorkerLongitude()); userInfo.put("workerAdress",user.getWorkerAdress()); } if (user.getType().equals("1")) { userInfo.put("balance", user.getBalance() != null ? user.getBalance().toString() : "0.00"); userInfo.put("ismember", user.getIsmember()); userInfo.put("member_begin",user.getMemberBegin() != null ? sdfday.format(user.getMemberBegin()) : null ); userInfo.put("member_end",user.getMemberEnd() != null ? sdfday.format(user.getMemberEnd()) : null ); } userInfo.put("integral", user.getIntegral() != null ? user.getIntegral() : 0); userInfo.put("is_stop", user.getIsStop() != null ? user.getIsStop() : 1); userInfo.put("job_number", user.getJobNumber()); userInfo.put("level", user.getLevel()); userInfo.put("login_status", user.getLoginStatus() != null ? user.getLoginStatus() : 2); userInfo.put("margin", user.getMargin() != null ? user.getMargin() : 0); userInfo.put("middle_auth", user.getMiddleAuth()); userInfo.put("openid", user.getOpenid()); userInfo.put("prohibit_time", user.getProhibitTime()); userInfo.put("prohibit_time_str", null); userInfo.put("remember_token", user.getRememberToken()); userInfo.put("status", user.getStatus() != null ? user.getStatus() : 1); userInfo.put("tpd", 0); // 默认值 userInfo.put("total_integral", user.getTotalIntegral() != null ? user.getTotalIntegral() : 100); userInfo.put("type", user.getType() != null ? user.getType().toString() : "1"); userInfo.put("worker_time", user.getWorkerTime()); // 时间字段格式化 if (user.getCreatedAt() != null) { userInfo.put("created_at", sdf.format(user.getCreatedAt())); } else { userInfo.put("created_at", null); } if (user.getUpdatedAt() != null) { userInfo.put("updated_at", sdf.format(user.getUpdatedAt())); } else { userInfo.put("updated_at", null); } // 处理服务城市ID数组 if (user.getServiceCityIds() != null && !user.getServiceCityIds().isEmpty()) { userInfo.put("service_city_ids", AppletControllerUtil.parseStringToList(user.getServiceCityIds())); } else { userInfo.put("service_city_ids", new ArrayList<>()); } // 处理技能ID数组 if (user.getSkillIds() != null && !user.getSkillIds().isEmpty()) { userInfo.put("skill_ids", AppletControllerUtil.parseStringToList(user.getSkillIds())); } else { userInfo.put("skill_ids", new ArrayList<>()); } return userInfo; } /** * 修改用户基本信息接口 * * @param params 请求参数,包含用户信息字段 * @param request HTTP请求对象 * @return 修改结果 *

* 接口说明: * - 通过token验证用户身份后修改用户基本信息 * - 支持修改用户的各种字段信息 * - 自动处理服务城市ID和技能ID数组 * - 需要用户登录验证 *

*/ @PostMapping(value = "/api/user/edit/info") public AjaxResult editUserInfo(@RequestBody Map params, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取当前登录用户信息 Users currentUser = (Users) userValidation.get("user"); if (currentUser == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 验证请求参数 if (params == null || params.isEmpty()) { return AppletControllerUtil.appletWarning("请求参数不能为空"); } // 4. 验证用户ID是否匹配(安全性检查) Object userIdObj = params.get("id"); if (userIdObj != null) { Long userId = Long.valueOf(userIdObj.toString()); if (!userId.equals(currentUser.getId())) { return AppletControllerUtil.appletWarning("无权修改其他用户的信息"); } } // 5. 构建更新用户对象 Users updateUser = AppletControllerUtil.buildUpdateUserFromdataParams(params, currentUser.getId()); // 6. 验证必要字段 String validationResult = validateUserEditdataParams(updateUser); if (validationResult != null) { return AppletControllerUtil.appletWarning(validationResult); } // 7. 执行用户信息更新 int updateResult = usersService.updateUsers(updateUser); if (updateResult > 0) { // 8. 返回成功响应(按照图片中的格式返回空数组) return AppletControllerUtil.appletSuccess(new ArrayList<>()); } else { return AppletControllerUtil.appletWarning("用户信息修改失败"); } } catch (Exception e) { System.err.println("修改用户基本信息异常:" + e.getMessage()); return AppletControllerUtil.appletError("修改用户信息失败:" + e.getMessage()); } } /** * 验证用户编辑参数 * * @param user 用户对象 * @return 验证结果,null表示验证通过 */ private String validateUserEditdataParams(Users user) { // 验证手机号格式(如果提供了的话) if (user.getPhone() != null && !user.getPhone().isEmpty()) { if (!user.getPhone().matches("^1[3-9]\\d{9}$")) { return "手机号格式不正确"; } } // 验证用户名长度 if (user.getName() != null && user.getName().length() > 50) { return "用户名长度不能超过50个字符"; } // 验证昵称长度 if (user.getNickname() != null && user.getNickname().length() > 50) { return "昵称长度不能超过50个字符"; } return null; // 验证通过 } /** * 验证用户token接口 * * @param request HTTP请求对象 * @return 验证结果 *

* 接口说明: * - 验证用户token的有效性 * - 返回用户基本信息 * - 检查用户账号状态 * - 过滤敏感信息 */ @PostMapping(value = "/api/user/validate") public AjaxResult validateToken(HttpServletRequest request) { try { // 1. 获取token String token = AppletLoginUtil.extractToken( request.getHeader("Authorization"), request.getHeader("token") ); if (token == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 验证token Map validateResult = AppletLoginUtil.validateUserToken(token, usersService); // 3. 返回验证结果 boolean valid = (Boolean) validateResult.get("valid"); if (valid) { return AppletControllerUtil.appletSuccess(validateResult); } else { return AppletControllerUtil.appletWarning((String) validateResult.get("message")); } } catch (Exception e) { return AppletControllerUtil.appletWarning("验证token失败:" + e.getMessage()); } } /** * 查询支付订单状态接口 * * @param orderNo 订单号 * @param request HTTP请求对象 * @return 查询结果 */ @GetMapping(value = "/api/pay/query/{orderNo}") public AjaxResult queryPayOrder(@PathVariable("orderNo") String orderNo, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } WechatPayUtil wechatPayUtil = new WechatPayUtil(); // 2. 查询订单状态 Map queryResult = wechatPayUtil.queryOrder(orderNo, null); // 3. 返回结果 boolean success = (Boolean) queryResult.get("success"); if (success) { return AppletControllerUtil.appletSuccess(queryResult); } else { return AppletControllerUtil.appletWarning((String) queryResult.get("message")); } } catch (Exception e) { return AppletControllerUtil.appletWarning("查询订单状态失败:" + e.getMessage()); } } /** * 合作申请提交接口 * * @param params 请求参数,包含company(公司名称)、name(姓名)、phone(电话)、address(地址)、info(合作意向) * @param request HTTP请求对象 * @return 申请提交结果 *

* 功能说明: * - 验证用户登录状态(可选) * - 接收合作申请表单数据 * - 验证必填字段 * - 保存合作申请记录 * - 设置默认状态为待处理 *

*/ @PostMapping("/api/form/cooperate") public AjaxResult submitCooperateApplication(@RequestBody Map params, HttpServletRequest request) { try { // 1. 参数验证 if (params == null) { return AppletControllerUtil.appletWarning("请求参数不能为空"); } String company = (String) params.get("company"); String name = (String) params.get("name"); String phone = (String) params.get("phone"); String address = (String) params.get("address"); String info = (String) params.get("info"); // 2. 验证必填字段 if (StringUtils.isEmpty(company)) { return AppletControllerUtil.appletWarning("公司名称不能为空"); } if (StringUtils.isEmpty(name)) { return AppletControllerUtil.appletWarning("联系人姓名不能为空"); } if (StringUtils.isEmpty(phone)) { return AppletControllerUtil.appletWarning("联系电话不能为空"); } // 验证手机号格式 if (!phone.matches("^1[3-9]\\d{9}$")) { return AppletControllerUtil.appletWarning("联系电话格式不正确"); } if (StringUtils.isEmpty(address)) { return AppletControllerUtil.appletWarning("联系地址不能为空"); } if (StringUtils.isEmpty(info)) { return AppletControllerUtil.appletWarning("合作意向不能为空"); } // 3. 获取用户信息(可选,不强制要求登录) Long uid = null; String uname = null; String token = request.getHeader("token"); if (StringUtils.isNotEmpty(token)) { Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if ((Boolean) userValidation.get("valid")) { Users user = (Users) userValidation.get("user"); if (user != null) { uid = user.getId(); uname = user.getNickname(); } } } // 4. 构建合作申请对象 Cooperate cooperate = AppletControllerUtil.buildCooperateApplication(params, uid, uname); // 5. 验证合作申请参数 String validationResult = AppletControllerUtil.validateCooperateParams(cooperate); if (validationResult != null) { return AppletControllerUtil.appletWarning(validationResult); } // 6. 保存合作申请记录 int insertResult = cooperateService.insertCooperate(cooperate); if (insertResult > 0) { return AppletControllerUtil.appletSuccess("合作申请提交成功,我们会尽快联系您"); } else { return AppletControllerUtil.appletWarning("合作申请提交失败,请稍后重试"); } } catch (Exception e) { System.err.println("合作申请提交异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("合作申请提交失败:" + e.getMessage()); } } /** * 查询用户优惠券列表 * * @param params 请求参数,包含status(优惠券状态)、product_id(指定商品ID)、price(最低价格) * @param request HTTP请求对象 * @return 返回用户优惠券列表 */ @PostMapping("/api/coupon/my/lst") public AjaxResult getMyCouponList(@RequestBody Map params, HttpServletRequest request) { // 3. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Long userId = user.getId(); // 获取当前用户id Integer status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : null; String productId = params.get("product_id") != null ? params.get("product_id").toString() : null; BigDecimal totalPrice = params.get("price") != null ? new BigDecimal(params.get("price").toString()) : null; // 过期的优惠券标记为已过期 CouponUser couponUser = new CouponUser(); couponUser.setStatus(1L); couponUser.setUid(user.getId()); List couponUserList = couponUserService.selectCouponUserNoList(couponUser); for (CouponUser c: couponUserList){ c.setStatus(3L); couponUserService.updateCouponUser(c); } //安状态进行赋值 //待领取优惠券 if (status==4){ // Coupons coupons = new Coupons(); // coupons.setSearchValue("12"); List couponsList =CouponUtil.iscoupon(userId,couponsService,couponUserService); if (!couponsList.isEmpty()){ return AppletControllerUtil.appletSuccess(AppletControllerUtil.buildCouponDataList(couponsList,serviceCateService,serviceGoodsService)); } }else{ CouponUser couponUserData = new CouponUser(); couponUserData.setStatus(Long.valueOf(status)); couponUserData.setUid(user.getId()); List couponUserDataList = couponUserService.selectCouponUserList(couponUserData); if (couponUserDataList!=null){ return AppletControllerUtil.appletSuccess(AppletControllerUtil.buildCouponUserList(couponUserDataList,serviceCateService,serviceGoodsService,productId,totalPrice)); } } JSONArray jsonArray = new JSONArray(); // 按is_use排序 return AppletControllerUtil.appletSuccess(jsonArray); } /** * 积分订单收货确认接口 * @param request * @return AjaxResult * 订单状态 1:待支付 2:已支付,待发货3:待收货 4:待评价 5:已收货 6:取消 20:申请退款 21:同意退款 22:驳回退款 */ @GetMapping("/api/integral/user/order/confirm/{id}") public AjaxResult confirmOrder(@PathVariable("id") String id,HttpServletRequest request) { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } IntegralOrder integralOrder = integralOrderService.selectIntegralOrderById(Long.valueOf(id)); if (integralOrder==null){ return AppletControllerUtil.appletWarning("订单不存在"); } if(!user.getId().equals(integralOrder.getUid())){ return AppletControllerUtil.appletWarning("确认收货失败,收货人和操作人应为同一人,请确认后再进行操作"); } if (!integralOrder.getStatus().equals("2")){ return AppletControllerUtil.appletWarning("订单状态错误"); } integralOrder.setStatus("3"); integralOrderService.updateIntegralOrder(integralOrder); IntegralOrderLog integralOrderLog = new IntegralOrderLog(); integralOrderLog.setOrderId(integralOrder.getOrderId()); integralOrderLog.setOid(integralOrder.getId()); integralOrderLog.setType(3L); integralOrderLog.setTitle("确认收货"); JSONObject jsonObject = new JSONObject(); jsonObject.put("name","用户确认收货"); integralOrderLog.setContent(jsonObject.toJSONString()); int flg=integralOrderLogService.insertIntegralOrderLog(integralOrderLog); if (flg>0){ return AppletControllerUtil.appletSuccess("确认收货成功"); }else{ return AppletControllerUtil.appletWarning("确认收货失败"); } } /** * 商品订单评价接口 * @param param {order_id, content, num, images} * @param request * @return AjaxResult * 订单状态 1:待支付 2:已支付,待发货3:待收货 4:待评价 5:已收货 6:取消 20:申请退款 21:同意退款 22:驳回退款 */ @PostMapping("/api/goods/order/comment") public AjaxResult commentGoodsOrder(@RequestBody Map param, HttpServletRequest request) { // 参数校验 String orderId = (String) param.get("order_id"); String content = (String) param.get("content"); Integer num = param.get("num") != null ? Integer.parseInt(param.get("num").toString()) : null; Object imagesObj = param.get("images"); Object labels = param.get("labels"); if (orderId == null || orderId.isEmpty()) { return AppletControllerUtil.appletWarning("请选择评价的订单"); } if (content == null || content.isEmpty()) { return AppletControllerUtil.appletWarning("请输入评价内容"); } if (num == null) { return AppletControllerUtil.appletWarning("请打分"); } // 获取当前登录用户(假设有token或session,示例用1L) Long uid = 1L; // 判断是否已评价 GoodsOrder goodsOrder = null; { GoodsOrder query = new GoodsOrder(); query.setOrderId(orderId); List orderList = goodsOrderService.selectGoodsOrderList(query); if (orderList == null || orderList.isEmpty()) { return AppletControllerUtil.appletWarning("订单不存在"); } goodsOrder = orderList.get(0); } int count = orderCommentService.selectCountOrderCommentByOid(goodsOrder.getOrderId()); if (count > 0) { return AppletControllerUtil.appletWarning("请勿重复提交"); } // 评分类型 long numType = num == 1 ? 3 : ((num == 2 || num == 3) ? 2 : 1); // 组装评价对象 OrderComment comment = new OrderComment(); comment.setOid(goodsOrder.getId()); comment.setOrderId(orderId); comment.setProductId(goodsOrder.getProductId()); comment.setContent(content); comment.setLabels(labels != null ? JSON.toJSONString(labels) : null ); comment.setNum((long) num); comment.setUid(goodsOrder.getUid()); // 或uid comment.setImages(imagesObj != null ? JSON.toJSONString(imagesObj) : null); comment.setNumType(numType); comment.setCreatedAt(new java.util.Date()); comment.setUpdatedAt(new java.util.Date()); comment.setStatus(1); // 显示 int result = orderCommentService.insertOrderComment(comment); if (result > 0) { goodsOrder.setStatus(5L); // 订单状态改为已收货 goodsOrderService.updateGoodsOrder(goodsOrder); return AjaxResult.success(); } else { return AppletControllerUtil.appletWarning("操作失败"); } } /** * 查询用户积分日志列表 * * @param params 请求参数,包含limit(每页数量)、page(页码) * @param request HTTP请求对象 * @return 返回分页的积分日志列表 */ @PostMapping("/api/integral/user/log/lst") public AjaxResult getUserIntegralLogList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 获取分页参数 int page = params.get("page") != null ? (Integer) params.get("page") : 1; int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; // 2. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 3. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 5. 设置分页参数 PageHelper.startPage(page, limit); // 6. 构建查询条件并查询 IntegralLog integralLogQuery = new IntegralLog(); integralLogQuery.setUid(user.getId()); List integralLogList = integralLogService.selectIntegralLogList(integralLogQuery); // 7. 构建分页信息 PageInfo pageInfo = new PageInfo<>(integralLogList); // 8. 使用工具类处理数据格式化 List> formattedLogList = AppletControllerUtil.buildIntegralLogList(integralLogList); Map paginationData = AppletControllerUtil.buildPaginationResponse( pageInfo, formattedLogList, "https://www.huafurenjia.cn/api/integral/user/log/lst"); Map userData = AppletControllerUtil.buildUserDataInfo(user); // 9. 构建最终返回数据结构 Map responseData = new HashMap<>(); responseData.put("data", paginationData); responseData.put("user", userData); responseData.put("msg", "OK"); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { System.err.println("查询用户积分日志列表异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询积分日志列表失败:" + e.getMessage()); } } /** * 查询用户积分商城订单列表 * * @param params 请求参数,包含limit(每页数量)、page(页码)、status(订单状态) * @param request HTTP请求对象 * @return 返回分页的积分商城订单列表 */ @PostMapping("/api/integral/user/order") public AjaxResult getUserIntegralOrderList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 获取分页参数 int page = params.get("page") != null ? (Integer) params.get("page") : 1; int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; String status = params.get("status") != null ? params.get("status").toString() : null; // 2. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 3. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 5. 设置分页参数 PageHelper.startPage(page, limit); // 6. 构建查询条件并查询 IntegralOrder integralOrderQuery = new IntegralOrder(); integralOrderQuery.setUid(user.getId()); if (status != null && !status.trim().isEmpty()) { integralOrderQuery.setStatus(status.trim()); } List integralOrderList = integralOrderService.selectIntegralOrderList(integralOrderQuery); // 7. 构建分页信息 PageInfo pageInfo = new PageInfo<>(integralOrderList); // 8. 使用工具类处理数据格式化 List> formattedOrderList = AppletControllerUtil.buildIntegralOrderList( integralOrderList, integralProductService); Map responseData = AppletControllerUtil.buildPaginationResponse( pageInfo, formattedOrderList, "https://www.huafurenjia.cn/api/integral/user/order"); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { System.err.println("查询用户积分商城订单列表异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询积分商城订单列表失败:" + e.getMessage()); } } /** * 查询积分订单详情 * * @param id 订单ID * @param request HTTP请求对象 * @return 返回积分订单详细信息 */ @GetMapping("/api/integral/user/order/info/{id}") public AjaxResult getIntegralOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 1. 参数验证 if (id == null || id <= 0) { return AppletControllerUtil.appletWarning("订单ID无效"); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 查询积分订单信息 IntegralOrder integralOrder = integralOrderService.selectIntegralOrderById(id); if (integralOrder == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 5. 验证订单归属权 if (!integralOrder.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权访问该订单信息"); } // 6. 使用工具类构建订单详情数据 Map orderData = AppletControllerUtil.buildIntegralOrderDetail( integralOrder, integralProductService, integralOrderLogService); return AppletControllerUtil.appletSuccess(orderData); } catch (Exception e) { System.err.println("查询积分订单详情异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询订单详情失败:" + e.getMessage()); } } /** * 查询积分商品分类列表 * * @param request HTTP请求对象 * @return 返回积分商品分类列表 *

* 功能说明: * - 获取所有启用状态的积分商品分类 * - 返回分类的ID和名称 * - 用于积分商城分类展示 */ @GetMapping("/api/integral/product/cate") public AjaxResult getIntegralProductCateList(HttpServletRequest request) { try { // 1. 构建查询条件:查询启用状态的积分商品分类 IntegralCate integralCateQuery = new IntegralCate(); integralCateQuery.setStatus(1L); // 启用状态 // 2. 查询积分商品分类列表 List integralCateList = integralCateService.selectIntegralCateList(integralCateQuery); // 3. 构建返回数据格式 List> resultList = new ArrayList<>(); for (IntegralCate integralCate : integralCateList) { Map cateData = new HashMap<>(); cateData.put("id", integralCate.getId()); cateData.put("title", integralCate.getTitle()); resultList.add(cateData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { System.err.println("查询积分商品分类列表异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询分类列表失败:" + e.getMessage()); } } /** * 查询积分商品列表 * * @param params 请求参数,包含limit(每页数量)、page(页码)、type(分类ID) * @param request HTTP请求对象 * @return 返回分页的积分商品列表 *

* 功能说明: * - 获取积分商品列表,支持分页 * - 支持按分类筛选 * - 返回商品详细信息和分页信息 * - 按创建时间倒序排列 */ @PostMapping("/api/integral/product/lst") public AjaxResult getIntegralProductList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 获取分页参数 int page = params.get("page") != null ? (Integer) params.get("page") : 1; int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; String type = params.get("type") != null ? params.get("type").toString() : null; // 2. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 3. 设置分页参数 PageHelper.startPage(page, limit); // 4. 构建查询条件 IntegralProduct integralProductQuery = new IntegralProduct(); integralProductQuery.setStatus(1L); // 只查询启用状态的商品 // 如果有分类参数,添加分类筛选 if (type != null && !type.trim().isEmpty()) { try { Long cateId = Long.parseLong(type.trim()); integralProductQuery.setCateId(cateId); } catch (NumberFormatException e) { return AppletControllerUtil.appletWarning("分类参数格式错误"); } } // 5. 查询积分商品列表 List integralProductList = integralProductService.selectIntegralProductList(integralProductQuery); // 6. 构建分页信息 PageInfo pageInfo = new PageInfo<>(integralProductList); // 7. 使用工具类处理数据格式化 List> formattedProductList = AppletControllerUtil.buildIntegralProductList(integralProductList); Map responseData = AppletControllerUtil.buildPaginationResponse( pageInfo, formattedProductList, "https://www.huafurenjia.cn/api/integral/product/lst"); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { System.err.println("查询积分商品列表异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询积分商品列表失败:" + e.getMessage()); } } /** * 查询积分商品详情 * * @param id 商品ID * @param request HTTP请求对象 * @return 返回积分商品详细信息 *

* 功能说明: * - 根据商品ID获取积分商品详细信息 * - 返回完整的商品数据包括图片、规格、库存等 * - 自动处理图片URL添加CDN前缀 * - 格式化轮播图和标签为数组格式 *

*/ @GetMapping("/api/integral/product/info/{id}") public AjaxResult getIntegralProductInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 1. 参数验证 if (id == null || id <= 0) { return AppletControllerUtil.appletWarning("商品ID无效"); } // 2. 查询积分商品信息 IntegralProduct integralProduct = integralProductService.selectIntegralProductById(id); if (integralProduct == null) { return AppletControllerUtil.appletWarning("商品不存在"); } // 3. 验证商品状态(只返回启用状态的商品) if (integralProduct.getStatus() == null || integralProduct.getStatus() != 1) { return AppletControllerUtil.appletWarning("商品已下架或不可用"); } // 4. 使用工具类构建商品详情数据 Map productDetail = AppletControllerUtil.buildIntegralProductDetail(integralProduct); return AppletControllerUtil.appletSuccess(productDetail); } catch (Exception e) { System.err.println("查询积分商品详情异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询商品详情失败:" + e.getMessage()); } } /** * 获取用户默认收货地址 * * @param request HTTP请求对象 * @return 默认地址信息 *

* 接口说明: * - 查询用户的默认收货地址(is_default = 1) * - 如果没有默认地址,返回用户地址列表的第一条数据 * - 验证用户登录状态和地址归属权 * - 返回AddressApple格式的地址数据 *

*/ @GetMapping("/api/user/address/default") public AjaxResult getUserDefaultAddress(HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 首先查询用户的默认地址 UserAddress userAddressQuery = new UserAddress(); userAddressQuery.setUid(user.getId()); userAddressQuery.setIsDefault(1L); // 查询默认地址 List defaultAddressList = userAddressService.selectUserAddressList(userAddressQuery); UserAddress targetAddress = null; if (!defaultAddressList.isEmpty()) { // 找到默认地址 targetAddress = defaultAddressList.get(0); } else { // 没有默认地址,查询用户的第一条地址 UserAddress allAddressQuery = new UserAddress(); allAddressQuery.setUid(user.getId()); List allAddressList = userAddressService.selectUserAddressList(allAddressQuery); if (!allAddressList.isEmpty()) { targetAddress = allAddressList.get(0); } else { return AppletControllerUtil.appletSuccess("用户暂无收货地址"); } } // 4. 转换为AddressApple格式并返回 AddressApple addressApple = AddressApple.fromUserAddress(targetAddress); return AppletControllerUtil.appletSuccess(addressApple); } catch (Exception e) { System.err.println("查询用户默认地址异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询默认地址失败:" + e.getMessage()); } } /** * 获取用户小程序通知订阅状态 * * @param request HTTP请求对象 * @return 用户通知订阅状态 *

* 接口说明: * - 查询用户对小程序消息模板的订阅状态 * - 返回三个消息模板的订阅配置信息 * - 支持不同业务场景的消息通知配置 * - 验证用户登录状态 */ @GetMapping("/api/user/notification/status") public AjaxResult getUserNotificationStatus(HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 直接返回固定的消息模板配置数据 Map notificationStatus = AppletControllerUtil.buildMiniProgramNotificationStatus(user); return AppletControllerUtil.appletSuccess(notificationStatus); } catch (Exception e) { System.err.println("查询用户通知订阅状态异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("查询通知订阅状态失败:" + e.getMessage()); } } /** * 用户订阅消息授权接口 * * @param params 请求参数,包含tmplIds(模板ID数组) * @param request HTTP请求对象 * @return 授权结果 */ @PostMapping("/api/user/notification/subscribe") public AjaxResult subscribeNotification(@RequestBody Map params, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取模板ID列表 List tmplIds = (List) params.get("tmplIds"); if (tmplIds == null || tmplIds.isEmpty()) { return AppletControllerUtil.appletWarning("模板ID列表不能为空"); } // 4. 验证模板ID的有效性 List validTemplateIds = new ArrayList<>(); validTemplateIds.add("pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M"); validTemplateIds.add("YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8"); validTemplateIds.add("5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU"); for (String tmplId : tmplIds) { if (!validTemplateIds.contains(tmplId)) { return AppletControllerUtil.appletWarning("无效的模板ID:" + tmplId); } } // 5. 处理订阅逻辑(这里可以记录到数据库或调用微信API) Map subscribeResult = new HashMap<>(); subscribeResult.put("user_id", user.getId()); subscribeResult.put("template_ids", tmplIds); subscribeResult.put("subscribe_time", new Date()); subscribeResult.put("status", "success"); // 6. 这里可以将订阅状态保存到数据库 // 例如:userNotificationService.saveSubscribeStatus(user.getId(), tmplIds); return AppletControllerUtil.appletSuccess(subscribeResult); } catch (Exception e) { System.err.println("用户订阅消息异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("订阅消息失败:" + e.getMessage()); } } /** * 小程序下单时用户订阅消息推送接口(前端不传值,后端返回固定结构) * * @return 订阅消息推送ID分类结果 */ @GetMapping("/api/public/massge/notice") public Map subscribeMessageNotice() { Map data = new HashMap<>(); data.put("make_success", Arrays.asList( "YKnuTCAD-oEEhNGoI3LUVkAqNsykOMTcyrf71S9vev8", "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" )); data.put("pay_success", Arrays.asList( "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M" )); data.put("integral", Arrays.asList( "pv3cba-wPoinUbBZSskp0KpDNnJwrHqS0rvGBfDNQ1M" )); data.put("worker", Arrays.asList( "5lA-snytEPl25fBS7rf6rQi8Y0i5HOSdG0JMVdUnMcU" )); Map result = new HashMap<>(); result.put("code", 200); result.put("msg", "OK"); result.put("data", data); return result; } /** * 积分商品兑换接口 * * @param params 请求参数,包含id(积分商品ID)、address_id(收货地址ID)、num(购买数量)、sku(规格)、mark(备注) * @param request HTTP请求对象 * @return 兑换结果 */ @PostMapping("/api/integral/user/exchange") public AjaxResult exchangeIntegralProduct(@RequestBody Map params, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 验证请求参数 String validationResult = AppletControllerUtil.validateIntegralExchangeParams(params); if (validationResult != null) { return AppletControllerUtil.appletWarning(validationResult); } // 4. 获取并验证积分商品信息 Long productId = Long.valueOf(params.get("id").toString()); IntegralProduct product = integralProductService.selectIntegralProductById(productId); if (product == null) { return AppletControllerUtil.appletWarning("积分商品不存在"); } if (product.getStatus() == null || product.getStatus() != 1) { return AppletControllerUtil.appletWarning("积分商品已下架或不可用"); } // 5. 获取并验证收货地址信息 Long addressId = Long.valueOf(params.get("address_id").toString()); UserAddress address = userAddressService.selectUserAddressById(addressId); if (address == null) { return AppletControllerUtil.appletWarning("收货地址不存在"); } if (!address.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权使用该收货地址"); } // 6. 计算所需积分并验证库存 Integer num = Integer.valueOf(params.get("num").toString()); if (product.getStock() != null && product.getStock() < num) { return AppletControllerUtil.appletWarning("商品库存不足"); } Long totalIntegral = product.getNum() * num; // 7. 验证用户积分是否足够 if (!AppletControllerUtil.checkUserIntegralSufficient(user, totalIntegral)) { // 积分不足,返回422状态码 return AppletControllerUtil.appletWarning("积分不足"); } // 8. 创建积分订单 IntegralOrder order = AppletControllerUtil.buildIntegralOrder(params, user, product, address); int orderResult = integralOrderService.insertIntegralOrder(order); if (orderResult <= 0) { return AppletControllerUtil.appletWarning("订单创建失败"); } // 9. 扣除用户积分 Users updateUser = new Users(); updateUser.setId(user.getId()); updateUser.setIntegral(user.getIntegral() - totalIntegral); int updateResult = usersService.updateUsers(updateUser); if (updateResult <= 0) { return AppletControllerUtil.appletWarning("扣除积分失败"); } // 10. 记录积分变动日志 IntegralLog integralLog = AppletControllerUtil.buildIntegralLog( user, -totalIntegral, order.getOrderId(), product.getTitle()); integralLogService.insertIntegralLog(integralLog); // 11. 更新商品库存(如果有库存管理) if (product.getStock() != null) { IntegralProduct updateProduct = new IntegralProduct(); updateProduct.setId(product.getId()); updateProduct.setStock(product.getStock() - num); updateProduct.setSales(product.getSales() != null ? product.getSales() + num : num.longValue()); integralProductService.updateIntegralProduct(updateProduct); } // 12. 构建返回结果 return AppletControllerUtil.appletSuccess("兑换成功"); } catch (Exception e) { System.err.println("积分商品兑换异常:" + e.getMessage()); return AppletControllerUtil.appletError("积分商品兑换失败:" + e.getMessage()); } } /** * 获取服务订单详情 * * @param id 订单ID * @param request HTTP请求对象 * @return 服务订单详细信息 *

* 接口说明: * - 根据订单ID获取服务订单完整信息 * - 包含订单基本信息、订单日志和商品信息 * - 验证用户登录状态和订单归属权 * - 返回完整的订单详情数据 *

*/ @GetMapping("/api/service/order/info/{id}") public AjaxResult getServiceOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 1. 参数验证 if (id == null || id <= 0) { return AppletControllerUtil.appletWarning("订单ID无效"); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 查询订单信息并验证归属权 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 5. 验证订单归属权 if (!order.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权访问该订单信息"); } // 6. 使用工具类构建订单详情数据 Map orderDetail = AppletControllerUtil.buildServiceOrderDetail( order, orderLogService, serviceGoodsService); return AppletControllerUtil.appletSuccess(orderDetail); } catch (Exception e) { System.err.println("查询服务订单详情异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); } } /** * 获取城市列表接口 * * @param request HTTP请求对象 * @return 城市列表数据 *

* 接口说明: * - 获取所有启用状态的城市列表 * - 返回城市的ID、名称和父级ID * - 用于小程序城市选择功能 * - 无需用户登录验证 *

*/ @GetMapping(value = "/api/public/diy/city") public AjaxResult getDiyCityList(HttpServletRequest request) { try { // 查询所有城市列表 List cityList = diyCityService.selectDiyCityList(null); // 构建树状结构数据 List> resultList = AppletControllerUtil.buildCityTree(cityList); return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { System.err.println("获取城市列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("获取城市列表失败:" + e.getMessage()); } } /** * 获取技能列表接口 * * @param request HTTP请求对象 * @return 技能列表数据 *

* 接口说明: * - 获取所有技能列表数据 * - 返回技能的ID、名称、排序、状态等信息 * - 用于小程序技能选择功能 * - 无需用户登录验证 *

*/ @GetMapping(value = "/api/form/skill/lst") public AjaxResult getSkillList(HttpServletRequest request) { try { // 查询技能列表 List skillList = siteSkillService.selectSiteSkillList(null); // 构建返回数据格式 List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (SiteSkill skill : skillList) { Map skillData = new HashMap<>(); skillData.put("id", skill.getId()); skillData.put("title", skill.getTitle()); skillData.put("sort", skill.getSort()); skillData.put("status", skill.getStatus()); // 格式化时间字段 if (skill.getCreatedAt() != null) { skillData.put("created_at", sdf.format(skill.getCreatedAt())); } else { skillData.put("created_at", null); } if (skill.getUpdatedAt() != null) { skillData.put("updated_at", sdf.format(skill.getUpdatedAt())); } else { skillData.put("updated_at", null); } resultList.add(skillData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { System.err.println("获取技能列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("获取技能列表失败:" + e.getMessage()); } } /** * 文件上传接口 * * @param file 上传的文件 * @param request HTTP请求对象 * @return 上传结果 *

* 接口说明: * - 支持图片和视频文件上传 * - 优先使用七牛云上传,未启用时使用本地上传 * - 自动验证文件格式和大小 * - 无需用户登录验证(public 接口) */ @PostMapping(value = "/api/public/upload/file") public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) { try { // 1. 验证文件是否为空 if (file == null || file.isEmpty()) { return AppletControllerUtil.appletWarning("上传文件不能为空"); } // 2. 只允许图片和视频格式 String[] allowedTypes = { // 图片格式 "jpg", "jpeg", "png", "gif", "bmp", "webp", "svg", // 视频格式 "mp4", "avi", "mov", "wmv", "flv", "m4v", "3gp", "rmvb", "mkv" }; if (!QiniuUploadUtil.isValidFileType(file.getOriginalFilename(), allowedTypes)) { return AppletControllerUtil.appletWarning("只允许上传图片或视频文件"); } // 3. 验证文件大小(10MB) long maxSize = 10 * 1024 * 1024; if (!QiniuUploadUtil.isFileSizeValid(file.getSize(), maxSize)) { return AppletControllerUtil.appletWarning("文件大小不能超过10MB"); } String fileUrl; String filePath; // 4. 检查是否启用七牛云上传 if (qiniuConfig.isEnabled()) { // 使用七牛云上传 fileUrl = QiniuUploadUtil.uploadFile(file); // 从完整URL中提取路径部分 filePath = AppletControllerUtil.extractPathFromUrl(fileUrl, "https://" + qiniuConfig.getDomain() + "/"); } else { // 使用本地上传(这里需要集成本地上传逻辑) return AppletControllerUtil.appletError("本地上传功能暂未在此接口中实现,请启用七牛云上传"); } // 5. 构建返回数据 Map uploadResult = new HashMap<>(); uploadResult.put("path", filePath); uploadResult.put("full_path", fileUrl); return AppletControllerUtil.appletSuccess(uploadResult); } catch (Exception e) { System.err.println("文件上传异常:" + e.getMessage()); return AppletControllerUtil.appletError("文件上传失败:" + e.getMessage()); } } // /** // * 获取服务预约时间段接口 // * // * @param params 请求参数,包含day(预约日期) // * @param request HTTP请求对象 // * @return 时间段列表数据 // *

// * 接口说明: // * - 根据指定日期获取可预约的时间段列表 // * - 返回每个时间段的可用状态和剩余数量 // * - 支持动态时间段配置 // * - 无需用户登录验证 // *

// */ // @PostMapping(value = "/api/service/make/time") // public AjaxResult getServiceMakeTime(@RequestBody Map params, HttpServletRequest request) { // try { // // 1. 参数验证 // if (params == null || params.get("day") == null) { // return AppletControllerUtil.appletWarning("日期参数不能为空"); // } // String day = params.get("day").toString().trim(); // if (day.isEmpty()) { // return AppletControllerUtil.appletWarning("日期参数不能为空"); // } // // 2. 验证日期格式 // if (!AppletControllerUtil.isValidDateFormat(day)) { // return AppletControllerUtil.appletWarning("日期格式错误,请使用yyyy-MM-dd格式"); // } // // 3. 检查日期是否为过去时间 // if (AppletControllerUtil.isPastDate(day)) { // return AppletControllerUtil.appletWarning("不能预约过去的日期"); // } // // 4. 构建时间段列表 // List> timeSlotList = AppletControllerUtil.buildTimeSlotList(day); // // return AppletControllerUtil.appletSuccess(timeSlotList); // // } catch (Exception e) { // System.err.println("获取服务预约时间段异常:" + e.getMessage()); // return AppletControllerUtil.appletError("获取时间段失败:" + e.getMessage()); // } // } /** * 预约时间选择接口 * * @param request HTTP请求对象 * @return 可预约时间段列表 * * 接口说明: * - day=1:今天 * - day=2:不是今天 * - 返回每个时间段的预约状态和剩余数量 */ @PostMapping(value = "/api/service/make/time") public AjaxResult orderMakeTime(@RequestBody Map params, HttpServletRequest request) { try { // 参数验证 if (params == null || params.get("day") == null) { return AppletControllerUtil.appletWarning("日期参数不能为空"); } String day = params.get("day").toString().trim(); // 获取当前时间 Calendar now = Calendar.getInstance(); String nowDay = new SimpleDateFormat("yyyy-MM-dd").format(now.getTime()); int nowHour = now.get(Calendar.HOUR_OF_DAY); int nowMinute = now.get(Calendar.MINUTE); int nowSecond = now.get(Calendar.SECOND); int nowTimeInSeconds = nowHour * 3600 + nowMinute * 60 + nowSecond; // 解析目标日期 long targetDayTime = 0; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date targetDate = sdf.parse(day); targetDayTime = targetDate.getTime() / 1000; // 转换为秒 } catch (Exception e) { return AppletControllerUtil.appletError("日期格式错误,请使用yyyy-MM-dd格式"); } // 获取预约时间配置 List> timeConfig = getTimeConfigFromDatabase(); if (timeConfig == null || timeConfig.isEmpty()) { return AppletControllerUtil.appletError("未找到预约时间配置"); } List> result = new ArrayList<>(); for (Map timeSlot : timeConfig) { String timeKey = (String) timeSlot.get("key"); Integer maxNum = (Integer) timeSlot.get("num"); if (timeKey == null || maxNum == null) { continue; // 跳过无效配置 } boolean click = true; String prove = "可预约"; Integer residueNum = null; // 判断是否是今天 if (nowDay.equals(day)) { // 解析时间段 String[] timeParts = timeKey.split("-"); if (timeParts.length == 2) { String endTime = timeParts[1]; String[] timeArr = endTime.split(":"); if (timeArr.length == 2) { try { int hour = Integer.parseInt(timeArr[0]); int minute = Integer.parseInt(timeArr[1]); int timeInSeconds = hour * 3600 + minute * 60; // 如果当前时间已经超过这个时间段,则不可预约 if (nowTimeInSeconds > timeInSeconds) { click = false; prove = "时间已过"; } } catch (NumberFormatException e) { // 时间格式错误,跳过这个时间段 continue; } } } } // 如果时间段可用,检查预约数量 if (click) { try { // 使用精确的查询方法获取预约数量 Map queryParams = new HashMap<>(); queryParams.put("makeTime", targetDayTime); queryParams.put("makeHour", timeKey); // 查询当前时间段的预约数量 Integer makeCount = 0; if (makeCount == null) { makeCount = 0; } if (makeCount >= maxNum) { click = false; prove = "该时间段已约满"; } else { residueNum = maxNum - makeCount; } } catch (Exception e) { // 查询失败,标记为不可预约 click = false; prove = "查询失败"; logger.error("查询预约数量失败: " + e.getMessage()); } } // 构建返回数据 Map timeData = new HashMap<>(); timeData.put("click", click); timeData.put("value", timeKey); timeData.put("prove", prove); timeData.put("residue_num", residueNum); result.add(timeData); } return AppletControllerUtil.appletSuccess(result); } catch (Exception e) { return AppletControllerUtil.appletError("获取预约时间失败:" + e.getMessage()); } } /** * 从数据库获取预约时间配置 * * @return 时间配置列表 */ private List> getTimeConfigFromDatabase() { try { // 从数据库查询配置,对应PHP代码中的SiteConfig::where(['name'=>'config_three']) SiteConfig siteConfig = siteConfigService.selectSiteConfigByName("config_three"); if (siteConfig == null || siteConfig.getValue() == null || siteConfig.getValue().trim().isEmpty()) { // 如果数据库中没有配置,返回默认配置 return getDefaultTimeConfig(); } // 解析JSON配置,对应PHP代码中的json_decode($site_time['value'], true) try { com.alibaba.fastjson.JSONObject configJson = com.alibaba.fastjson.JSONObject.parseObject(siteConfig.getValue()); com.alibaba.fastjson.JSONArray timeArray = configJson.getJSONArray("time"); if (timeArray == null || timeArray.isEmpty()) { return getDefaultTimeConfig(); } List> config = new ArrayList<>(); for (int i = 0; i < timeArray.size(); i++) { com.alibaba.fastjson.JSONObject timeSlot = timeArray.getJSONObject(i); Map slot = new HashMap<>(); slot.put("key", timeSlot.getString("key")); slot.put("num", timeSlot.getInteger("num")); config.add(slot); } return config; } catch (Exception e) { // JSON解析失败,返回默认配置 System.err.println("解析预约时间配置JSON失败: " + e.getMessage()); return getDefaultTimeConfig(); } } catch (Exception e) { // 数据库查询失败,返回默认配置 System.err.println("查询预约时间配置失败: " + e.getMessage()); return getDefaultTimeConfig(); } } /** * 获取默认时间配置 * * @return 默认时间配置列表 */ private List> getDefaultTimeConfig() { List> config = new ArrayList<>(); // 默认的时间段配置 String[] timeSlots = { "08:00-09:00", "09:00-10:00", "10:00-11:00", "11:00-12:00", "13:00-14:00", "14:00-15:00", "15:00-16:00", "16:00-17:00", "17:00-18:00", "18:00-19:00", "19:00-20:00" }; for (String timeSlot : timeSlots) { Map slot = new HashMap<>(); slot.put("key", timeSlot); slot.put("num", 5); // 每个时间段最多5个预约 config.add(slot); } return config; } /** * 添加商品到购物车接口 * * @param params 请求参数,包含good_id(商品ID)、sku(商品规格) * @param request HTTP请求对象 * @return 添加结果 *

* 接口说明: * - 将指定商品添加到用户购物车 * - 验证商品是否存在和可用 * - 支持商品规格选择 * - 需要用户登录验证 *

*/ @PostMapping(value = "/api/cart/add") public AjaxResult addToCart(@RequestBody Map params, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 验证请求参数 if (params == null || params.get("good_id") == null) { return AppletControllerUtil.appletWarning("商品ID不能为空"); } Long goodId; try { goodId = Long.valueOf(params.get("good_id").toString()); if (goodId <= 0) { return AppletControllerUtil.appletWarning("商品ID无效"); } } catch (NumberFormatException e) { return AppletControllerUtil.appletWarning("商品ID格式错误"); } // 4. 获取商品规格参数 // String sku = params.get("sku") != null ? params.get("sku").toString().trim() : ""; String sku = null; if (params.get("sku") != null) { Object skuParam = params.get("sku"); if (skuParam instanceof Map) { // 如果前端传递的是Map对象,转换为JSON字符串 try { sku = JSON.toJSONString(skuParam); } catch (Exception e) { System.err.println("SKU转换JSON失败:" + e.getMessage()); sku = skuParam.toString(); } } else { // 如果前端传递的是字符串,直接使用 sku = skuParam.toString().trim(); } } else { sku = null; } // 5. 获取新增的三个参数:ordertype、fileData、remark Long ordertype = null; if (params.get("ordertype") != null) { try { ordertype = Long.valueOf(params.get("ordertype").toString()); } catch (NumberFormatException e) { // 如果转换失败,保持为null ordertype = null; } } // 处理fileData参数 - 可能是数组或字符串 String fileData = ""; if (params.get("fileData") != null) { Object fileDataObj = params.get("fileData"); if (fileDataObj instanceof String) { fileData = (String) fileDataObj; } else if (fileDataObj instanceof List) { try { @SuppressWarnings("unchecked") List attachmentList = (List) fileDataObj; if (attachmentList != null && !attachmentList.isEmpty()) { // 限制最多9个附件 if (attachmentList.size() > 9) { return AppletControllerUtil.appletWarning("附件数量不能超过9个"); } // 转换为JSON数组格式的字符串 fileData = JSONObject.toJSONString(attachmentList); } } catch (Exception e) { logger.warn("附件参数解析失败: " + e.getMessage()); fileData = ""; } } else { // 其他类型,尝试转换为字符串 fileData = fileDataObj.toString(); } } String reamk = null; if (params.get("reamk") != null) { reamk = params.get("reamk").toString(); } // 6. 查询商品信息并验证 ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodId); if (serviceGoods == null) { return AppletControllerUtil.appletWarning("商品不存在"); } // 7. 验证商品状态 // if (serviceGoods.getStatus() == null || !serviceGoods.getStatus().equals(1L)) { // return AppletControllerUtil.appletWarning("商品已下架或不可用"); // } // 8. 检查商品库存(如果有库存管理) // if (serviceGoods.getStock() != null && serviceGoods.getStock() <= 0L) { // return AppletControllerUtil.appletWarning("商品库存不足"); // } // 9. 检查购物车中是否已存在该商品 GoodsCart existingCartItem = AppletControllerUtil.findExistingCartItem(user.getId(), goodId, sku, goodsCartService); if (existingCartItem != null) { // 如果已存在,更新数量和新参数 return AppletControllerUtil.updateCartItemQuantity(existingCartItem, serviceGoods, goodsCartService, ordertype, fileData, reamk,sku); } else { // 如果不存在,新增购物车记录 return AppletControllerUtil.addNewCartItem(user, serviceGoods, sku, goodsCartService, ordertype, fileData, reamk); } } catch (Exception e) { System.err.println("添加购物车异常:" + e.getMessage()); return AppletControllerUtil.appletError("添加购物车失败:" + e.getMessage()); } } /** * 批量删除购物车商品接口(新版,参数为{"ids":[1,2,3]}) * @param param {"ids": [id1, id2, ...]} * @param request HTTP请求对象 * @return 删除结果 */ @PostMapping("/api/cart/delete") public AjaxResult deleteCartItems(@RequestBody Map> param, HttpServletRequest request) { try { // 1. 校验用户登录 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } if (param == null || !param.containsKey("ids") || param.get("ids") == null || param.get("ids").isEmpty()) { return AppletControllerUtil.appletWarning("请选择要删除的购物车商品"); } List idList = param.get("ids"); // 查询这些购物车项,确保归属当前用户 List cartList = goodsCartService.selectGoodsCartList(new GoodsCart()); List toDelete = new ArrayList<>(); for (GoodsCart cart : cartList) { if (idList.contains(cart.getId()) && cart.getUid().equals(user.getId())) { toDelete.add(cart.getId()); } } if (toDelete.isEmpty()) { return AppletControllerUtil.appletWarning("没有可删除的购物车商品"); } int result = goodsCartService.deleteGoodsCartByIds(toDelete.toArray(new Integer[0])); if (result > 0) { return AppletControllerUtil.appletSuccess("删除成功"); } else { return AppletControllerUtil.appletWarning("删除失败"); } } catch (Exception e) { System.err.println("删除购物车商品异常:" + e.getMessage()); return AppletControllerUtil.appletError("删除购物车商品失败:" + e.getMessage()); } } /** * 批量删除购物车商品接口(新版,参数为{"ids":[1,2,3]}) * @param param {"ids": [id1, id2, ...]} * @param request HTTP请求对象 * @return 删除结果 */ @PostMapping("/api/cart/info") public AjaxResult apicartinfo(@RequestBody Map> param, HttpServletRequest request) { try { // 1. 校验用户登录 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } if (param == null || !param.containsKey("ids") || param.get("ids") == null || param.get("ids").isEmpty()) { return AppletControllerUtil.appletWarning("请选择要查询的购物车商品"); } List idList = param.get("ids"); List> cartList = new ArrayList<>(); for (Integer id : idList) { GoodsCart cart = goodsCartService.selectGoodsCartById(id); if (cart != null) { Map cartMap = new HashMap<>(); cartMap.put("id", cart.getId()); cartMap.put("uid", cart.getUid()); cartMap.put("goodId", cart.getGoodId()); cartMap.put("goodNum", cart.getGoodNum()); if (StringUtils.isNotBlank(cart.getSku())){ cartMap.put("sku",JSONObject.parseObject(cart.getSku())); }else{ cartMap.put("sku", ""); } cartMap.put("reamk", cart.getReamk()); if (StringUtils.isNotBlank(cart.getFileData())){ //cartMap.put("fileData",AppletControllerUtil.parseImagesStringToArray(cart.getFileData())); cartMap.put("fileData", JSONArray.parseArray(cart.getFileData())); }else{ cartMap.put("fileData", JSONArray.parseArray("[]")); } // cartMap.put("fileData", cart.getFileData()); cartMap.put("ordertype", cart.getOrdertype()); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(cart.getGoodId()); if (serviceGoods != null){ Map serviceGoodsMap = new HashMap<>(); serviceGoodsMap.put("id", serviceGoods.getId()); serviceGoodsMap.put("name", serviceGoods.getTitle()); serviceGoodsMap.put("icon",AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); serviceGoodsMap.put("price", serviceGoods.getPrice()); cartMap.put("serviceGoods", serviceGoodsMap); } // //服务 // if(cart.getGoodstype()==1){ // // } // if(cart.getGoodstype()==2){ // // } // cartMap.put("goodstype", cart.getg); cartList.add(cartMap); } } return AppletControllerUtil.appletSuccess(cartList); } catch (Exception e) { System.err.println("查询购物车商品异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询购物车商品失败:" + e.getMessage()); } } // /** // * 查看购物车详情接口 // * @param id 购物车ID // * @param request HTTP请求对象 // * @return 购物车详情 // */ // @GetMapping("/api/cart/info/{id}") // public AjaxResult getCartInfo(@PathVariable("id") Long id, HttpServletRequest request) { // try { // // 校验用户登录 // String token = request.getHeader("token"); // Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); // if (!(Boolean) userValidation.get("valid")) { // return AppletControllerUtil.appletUnauthorized(); // } // Users user = (Users) userValidation.get("user"); // if (user == null) { // return AppletControllerUtil.appletWarning("用户信息获取失败"); // } // if (id == null) { // return AppletControllerUtil.appletWarning("购物车ID不能为空"); // } // GoodsCart cart = goodsCartService.selectGoodsCartById(Math.toIntExact(id)); // if (cart == null || !cart.getUid().equals(user.getId())) { // return AppletControllerUtil.appletWarning("购物车不存在或无权查看"); // } // return AppletControllerUtil.appletSuccess(cart); // } catch (Exception e) { // return AppletControllerUtil.appletError("查询购物车详情失败:" + e.getMessage()); // } // } /** * 修改购物车接口 * @param params 前端传递的需要修改的字段,必须包含id * @param request HTTP请求对象 * @return 修改结果 */ @PostMapping("/api/cart/edit") public AjaxResult editCart(@RequestBody Map params, HttpServletRequest request) { try { // 校验用户登录 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } if (params == null || params.get("id") == null) { return AppletControllerUtil.appletWarning("购物车ID不能为空"); } Long id = Long.valueOf(params.get("id").toString()); GoodsCart cart = goodsCartService.selectGoodsCartById(Math.toIntExact(id)); if (cart == null || !cart.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("购物车不存在或无权修改"); } // 只更新前端传递的字段 if (params.containsKey("num")) { cart.setGoodNum(Long.valueOf(params.get("num").toString())); } // if (params.containsKey("sku")) { // cart.setSku(params.get("sku") != null ? params.get("sku").toString() : null); // } String sku = null; if (params.get("sku") != null) { Object skuParam = params.get("sku"); if (skuParam instanceof Map) { // 如果前端传递的是Map对象,转换为JSON字符串 try { sku = JSON.toJSONString(skuParam); } catch (Exception e) { System.err.println("SKU转换JSON失败:" + e.getMessage()); sku = skuParam.toString(); } } else { // 如果前端传递的是字符串,直接使用 sku = skuParam.toString().trim(); } } else { sku = null; } cart.setSku(sku); if (params.containsKey("ordertype")) { cart.setOrdertype(params.get("ordertype") != null ? Long.valueOf(params.get("ordertype").toString()) : null); } // 处理fileData参数 - 可能是数组或字符串 String fileData = ""; if (params.get("fileData") != null) { Object fileDataObj = params.get("fileData"); if (fileDataObj instanceof String) { fileData = (String) fileDataObj; } else if (fileDataObj instanceof List) { try { @SuppressWarnings("unchecked") List attachmentList = (List) fileDataObj; if (attachmentList != null && !attachmentList.isEmpty()) { // 限制最多9个附件 if (attachmentList.size() > 9) { return AppletControllerUtil.appletWarning("附件数量不能超过9个"); } // 转换为JSON数组格式的字符串 fileData = JSONObject.toJSONString(attachmentList); } } catch (Exception e) { logger.warn("附件参数解析失败: " + e.getMessage()); fileData = ""; } } else { // 其他类型,尝试转换为字符串 fileData = fileDataObj.toString(); } } cart.setFileData(fileData); // if (params.containsKey("fileData")) { // cart.setFileData(params.get("fileData") != null ? params.get("fileData").toString() : null); // } if (params.containsKey("reamk")) { cart.setReamk(params.get("reamk") != null ? params.get("reamk").toString() : null); } // 其他字段可按需补充 cart.setUpdatedAt(new Date()); int result = goodsCartService.updateGoodsCart(cart); if (result > 0) { return AppletControllerUtil.appletSuccess("修改成功"); } else { return AppletControllerUtil.appletWarning("修改失败"); } } catch (Exception e) { return AppletControllerUtil.appletError("修改购物车失败:" + e.getMessage()); } } /** * 查询用户购物车数据,按商品类型分为商城类和服务类(不分页) * * @param request HTTP请求对象 * @return { mallList: [...], serviceList: [...] } *

* 接口说明: * - 查询当前登录用户的全部购物车数据(不分页) * - 根据商品的 type 字段分为商城类(type=2)和服务类(type=1) * - 每个列表的封装方式参考 /api/cart/lst * - 需要用户登录验证 *

*/ @GetMapping("/api/cart/pluslst") public AjaxResult getCartPlusList(HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 查询全部购物车数据(不分页) GoodsCart queryCart = new GoodsCart(); queryCart.setUid(user.getId()); List cartList = goodsCartService.selectGoodsCartList(queryCart); // 4. 按商品类型分组 List> goodsList = new ArrayList<>(); List> serviceList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (GoodsCart cart : cartList) { Map cartData = new HashMap<>(); cartData.put("id", cart.getId()); cartData.put("uid", cart.getUid()); cartData.put("good_id", cart.getGoodId()); cartData.put("good_num", cart.getGoodNum()); if (cart.getSku() != null && !cart.getSku().isEmpty()) { try { cartData.put("sku", com.alibaba.fastjson2.JSONObject.parseObject(cart.getSku())); } catch (Exception e) { cartData.put("sku", cart.getSku()); } } else { cartData.put("sku", null); } cartData.put("ordertype", cart.getOrdertype()); cartData.put("fileData", cart.getFileData()); cartData.put("remark", cart.getReamk()); cartData.put("created_at", cart.getCreatedAt() != null ? sdf.format(cart.getCreatedAt()) : null); cartData.put("updated_at", cart.getUpdatedAt() != null ? sdf.format(cart.getUpdatedAt()) : null); // 查询商品详细信息 Map goodInfo = AppletControllerUtil.getGoodDetailForCart(cart.getGoodId(), serviceGoodsService); cartData.put("good", goodInfo); // 判断商品类型 Integer type = null; if (goodInfo.get("type") != null) { try { type = Integer.valueOf(goodInfo.get("type").toString()); } catch (Exception ignore) {} } if (type != null && type == 2) { goodsList.add(cartData); } else { // 默认都归为服务类(type=1) serviceList.add(cartData); } } // 5. 返回结构 Map result = new HashMap<>(); result.put("goodsList", goodsList); result.put("serviceList", serviceList); return AppletControllerUtil.appletSuccess(result); } catch (Exception e) { System.err.println("查询购物车plus列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询购物车plus列表失败:" + e.getMessage()); } } /** * 查询购物车列表接口 * * @param params 请求参数,包含limit(每页数量)、page(页码) * @param request HTTP请求对象 * @return 购物车列表数据 *

* 接口说明: * - 获取当前登录用户的购物车商品列表 * - 支持分页查询 * - 返回完整的商品信息 * - 需要用户登录验证 *

*/ @PostMapping(value = "/api/cart/lst") public AjaxResult getCartList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取分页参数 int page = params.get("page") != null ? (Integer) params.get("page") : 1; int limit = params.get("limit") != null ? (Integer) params.get("limit") : 15; // 4. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 5. 设置分页参数 PageHelper.startPage(page, limit); // 6. 构建查询条件 GoodsCart queryCart = new GoodsCart(); queryCart.setUid(user.getId()); // 7. 查询购物车列表 List cartList = goodsCartService.selectGoodsCartList(queryCart); // 8. 为每个购物车项目填充商品信息 List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (GoodsCart cart : cartList) { Map cartData = new HashMap<>(); // 基本购物车信息 cartData.put("id", cart.getId()); cartData.put("uid", cart.getUid()); cartData.put("good_id", cart.getGoodId()); cartData.put("good_num", cart.getGoodNum()); if (cart.getSku() != null || cart.getSku() != "") { cartData.put("sku", JSONObject.parseObject(cart.getSku())); } else { cartData.put("sku", null); } // 格式化时间字段 cartData.put("created_at", cart.getCreatedAt() != null ? sdf.format(cart.getCreatedAt()) : null); cartData.put("updated_at", cart.getUpdatedAt() != null ? sdf.format(cart.getUpdatedAt()) : null); // 查询并添加商品详细信息 Map goodInfo = AppletControllerUtil.getGoodDetailForCart(cart.getGoodId(), serviceGoodsService); cartData.put("good", goodInfo); resultList.add(cartData); } // 9. 构建分页信息 PageInfo pageInfo = new PageInfo<>(cartList); // 10. 构建返回数据格式 Map responseData = new HashMap<>(); responseData.put("current_page", pageInfo.getPageNum()); responseData.put("data", resultList); responseData.put("from", pageInfo.getStartRow()); responseData.put("last_page", pageInfo.getPages()); responseData.put("per_page", pageInfo.getPageSize()); responseData.put("to", pageInfo.getEndRow()); responseData.put("total", pageInfo.getTotal()); // 构建分页链接信息 String baseUrl = "https://www.huafurenjia.cn/api/cart/lst"; responseData.put("first_page_url", baseUrl + "?page=1"); responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); responseData.put("next_page_url", pageInfo.isHasNextPage() ? baseUrl + "?page=" + pageInfo.getNextPage() : null); responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? baseUrl + "?page=" + pageInfo.getPrePage() : null); responseData.put("path", baseUrl); // 构建links数组 List> links = new ArrayList<>(); Map prevLink = new HashMap<>(); prevLink.put("url", pageInfo.isHasPreviousPage() ? baseUrl + "?page=" + pageInfo.getPrePage() : null); prevLink.put("label", "« Previous"); prevLink.put("active", false); links.add(prevLink); Map nextLink = new HashMap<>(); nextLink.put("url", pageInfo.isHasNextPage() ? baseUrl + "?page=" + pageInfo.getNextPage() : null); nextLink.put("label", "Next »"); nextLink.put("active", false); links.add(nextLink); responseData.put("links", links); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { System.err.println("查询购物车列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询购物车列表失败:" + e.getMessage()); } } /** * 获取商品订单详情接口 * * @param id 订单ID * @param request HTTP请求对象 * @return 订单详细信息 *

* 接口说明: * - 根据订单ID获取商品订单完整信息 * - 包含订单基本信息、用户地址、商品信息等 * - 验证用户登录状态和订单归属权 * - 返回完整的订单详情数据 *

*/ @GetMapping("/api/goods/order/info/{id}") public AjaxResult getGoodsOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 1. 参数验证 if (id == null || id <= 0) { return AppletControllerUtil.appletWarning("订单ID无效"); } // 2. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 4. 查询订单信息并验证归属权 GoodsOrder order = goodsOrderService.selectGoodsOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 5. 验证订单归属权 if (!order.getUid().equals(user.getId())) { return AppletControllerUtil.appletWarning("无权访问该订单信息"); } // 6. 构建订单详情数据 Map orderDetail = buildGoodsOrderDetail(order); return AppletControllerUtil.appletSuccess(orderDetail); } catch (Exception e) { System.err.println("查询商品订单详情异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); } } /** * 构建商品订单详情数据 * * @param order 订单信息 * @return 格式化的订单详情 */ private Map buildGoodsOrderDetail(GoodsOrder order) { Map orderDetail = new HashMap<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 订单基本信息 orderDetail.put("id", order.getId()); orderDetail.put("type", order.getType()); orderDetail.put("main_order_id", order.getMainOrderId()); orderDetail.put("order_id", order.getOrderId()); orderDetail.put("transaction_id", order.getTransactionId() != null ? order.getTransactionId() : ""); orderDetail.put("uid", order.getUid()); orderDetail.put("product_id", order.getProductId()); orderDetail.put("name", order.getName()); orderDetail.put("phone", order.getPhone()); orderDetail.put("num", order.getNum()); orderDetail.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); orderDetail.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); orderDetail.put("service_price", order.getServicePrice()); orderDetail.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); orderDetail.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); orderDetail.put("postage", order.getPostage()); orderDetail.put("pay_time", order.getPayTime() != null ? sdf.format(order.getPayTime()) : null); orderDetail.put("status", order.getStatus()); orderDetail.put("delivery_id", order.getDeliveryId()); orderDetail.put("delivery_num", order.getDeliveryNum() != null ? order.getDeliveryNum() : ""); orderDetail.put("send_time", order.getSendTime() != null ? sdf.format(order.getSendTime()) : null); orderDetail.put("mark", order.getMark()); orderDetail.put("address_id", order.getAddressId()); orderDetail.put("sku", order.getSku()); // 时间字段格式化 orderDetail.put("created_at", order.getCreatedAt() != null ? sdf.format(order.getCreatedAt()) : null); orderDetail.put("updated_at", order.getUpdatedAt() != null ? sdf.format(order.getUpdatedAt()) : null); orderDetail.put("deleted_at", order.getDeletedAt() != null ? sdf.format(order.getDeletedAt()) : null); // 查询并添加地址信息 if (order.getAddressId() != null) { UserAddress address = userAddressService.selectUserAddressById(order.getAddressId()); if (address != null) { Map addressInfo = new HashMap<>(); addressInfo.put("id", address.getId()); addressInfo.put("uid", address.getUid()); addressInfo.put("name", address.getName()); addressInfo.put("phone", address.getPhone()); addressInfo.put("latitude", address.getLatitude()); addressInfo.put("longitude", address.getLongitude()); addressInfo.put("address_name", address.getAddressName()); addressInfo.put("address_info", address.getAddressInfo()); addressInfo.put("info", address.getInfo()); addressInfo.put("is_default", address.getIsDefault()); addressInfo.put("created_at", address.getCreatedAt() != null ? sdf.format(address.getCreatedAt()) : null); addressInfo.put("updated_at", address.getUpdatedAt() != null ? sdf.format(address.getUpdatedAt()) : null); addressInfo.put("deleted_at", null); // UserAddress可能没有deletedAt字段 orderDetail.put("address", addressInfo); } } // 查询并添加商品信息 if (order.getProductId() != null) { ServiceGoods product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); if (product != null) { Map productInfo = new HashMap<>(); productInfo.put("id", product.getId()); productInfo.put("title", product.getTitle()); productInfo.put("sub_title", product.getSubTitle()); productInfo.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); orderDetail.put("product", productInfo); } } // 添加评论和配送信息(暂时为空数组,后续可以扩展) orderDetail.put("comment", new ArrayList<>()); orderDetail.put("delivery", new ArrayList<>()); return orderDetail; } /** * 获取用户优惠券数量统计接口 * * @param request HTTP请求对象 * @return 优惠券数量统计信息 *

* 接口说明: * - 统计当前登录用户的优惠券数量 * - 包含未使用、已使用、已过期、待领取数量 * - 需要用户登录验证 *

*/ @GetMapping("/api/coupon/my/count") public AjaxResult getMyCouponCount(HttpServletRequest request) { try { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 6. 构建返回数据 Map countData = new HashMap<>(); countData.put("one", couponUserService.selectCountCouponsByUid(user.getId(), 1L)); // 未使用数量 countData.put("two",couponUserService.selectCountCouponsByUid(user.getId(), 3L)); // 已使用数量 countData.put("three",couponUserService.selectCountCouponsByUid(user.getId(), 2L)); // 已过期数量 countData.put("four", CouponUtil.iscoupon(user.getId(), couponsService, couponUserService).size()); // 待领取数量 return AppletControllerUtil.appletSuccess(countData); } catch (Exception e) { System.err.println("查询用户优惠券数量统计异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询优惠券数量统计失败:" + e.getMessage()); } } /** * 判断优惠券是否已过期 * * @param couponUser 用户优惠券 * @param currentTime 当前时间戳(秒) * @return 是否过期 */ private boolean isExpired(CouponUser couponUser, long currentTime) { // 检查lose_time字段(失效时间),这是一个字符串时间戳 if (couponUser.getLoseTime() != null && !couponUser.getLoseTime().isEmpty()) { try { long loseTimeStamp = Long.parseLong(couponUser.getLoseTime()); return currentTime > loseTimeStamp; } catch (NumberFormatException e) { // 如果解析失败,假设为日期格式,暂时认为未过期 System.err.println("解析失效时间失败:" + couponUser.getLoseTime()); } } // 如果状态为3,表示已失效 if (couponUser.getStatus() != null && couponUser.getStatus() == 3L) { return true; } // 如果都没有设置,认为未过期 return false; } /** * 取消服务订单 * * @param params 请求参数,包含订单ID和取消原因 * @param request HTTP请求对象 * @return 返回取消结果 */ @PostMapping("/api/service/cancel/order") public AjaxResult cancelServiceOrder(@RequestBody Map params, HttpServletRequest request) { try { RefundUtil refundUtil = new RefundUtil(); // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户未登录或token无效"); } // 2. 获取用户信息 AppletControllerUtil.appletdengluWarning("用户信息获取失败"); Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 3. 验证必要参数 if (params == null || params.get("id") == null || params.get("content") == null) { return AppletControllerUtil.appletWarning("参数不能为空"); } Long orderId = Long.valueOf(params.get("id").toString()); String cancelReason = params.get("content").toString(); // 4. 查询订单信息 Order order = orderService.selectOrderById(orderId); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } //如果是次卡就要做额外处理 if(StringUtils.isNotBlank(order.getCartid())){ //首先将订单中的次卡id抹除 orderService.updateOrderCika(order.getId()); //接下来查询次卡信息,然后修改次卡可用次数+1 UserUseSecondaryCard userUseSecondaryCard = userUseSecondaryCardService.selectUserUseSecondaryCardByorderId(order.getCartid()); if(userUseSecondaryCard!=null){ userUseSecondaryCard.setUsenum(userUseSecondaryCard.getUsenum()-1); userUseSecondaryCardService.updateUserUseSecondaryCard(userUseSecondaryCard); } } // 6. 更新订单状态为已取消(5) Order updateOrder = new Order(); updateOrder.setId(orderId); //设置订单支付的金额为0,防止开票 updateOrder.setPayPrice(new BigDecimal(0)); updateOrder.setStatus(5L); int result = orderService.updateOrder(updateOrder); if (result > 0) { // 7. 添加订单日志 OrderLog orderLog = new OrderLog(); orderLog.setOid(orderId); orderLog.setOrderId(order.getOrderId()); orderLog.setTitle("订单取消"); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "用户取消订单,原因:" + cancelReason); orderLog.setType(new BigDecimal(9.0)); orderLog.setContent(jsonObject.toString()); orderLogService.insertOrderLog(orderLog); //解绑虚拟号码 //需要解绑原订单上原师傅和客户的虚拟号 VoiceResponseResult resultObj = YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone(), order.getId()); if (resultObj.getResult().equals("000000")) { orderService.updateOrderPhone(order.getId()); } UsersPayBefor usersPayBefor = usersPayBeforService.selectUsersPayBeforByOrderId(order.getOrderId()); //如果有支付信息就要进行退款 System.out.println("=== 开始退款处理,订单号: " + order.getOrderId() + " ==="); if (usersPayBefor != null) { //退回其他对应支付时产生的金额和积分 int flg= BenefitPointsUtil.refundServerOrderData(usersPayBefor); if(flg==0){ UsersPayBefor newusersPayBefor = usersPayBeforService.selectUsersPayBeforByOrderId(order.getOrderId()); //退款里面金额退款结束,就开始回滚订单状态,添加日志 newusersPayBefor.setStatus(3L); // 设置为已退款状态 usersPayBeforService.updateUsersPayBefor(newusersPayBefor); } // BenefitPointsUtil.refundServiceAndConsumption(order.getId(), user, usersPayBefor.getServicemoney(),usersPayBefor.getShopmoney()); // System.out.println("=== 开始退款处理,2222222222订单号: " + usersPayBefor.getStatus() + " ==="); // // if (usersPayBefor.getStatus() == 2){ // System.out.println("=== 开始退款处理,2222222222订单号: " + order.getOrderId() + " ==="); // refundUtil.refundOrder(order.getOrderId()); // // } } return AppletControllerUtil.appletSuccess("取消成功"); } else { return AppletControllerUtil.appletWarning("取消失败,请稍后重试"); } } catch (Exception e) { return AppletControllerUtil.appletWarning("取消失败:" + e.getMessage()); } } //接单 @GetMapping("/api/worker/accept/order/{id}") public AjaxResult workerAcceptOrder(@PathVariable("id") Long id, HttpServletRequest request) { try { // 1. 校验token并获取师傅信息 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users worker = (Users) userValidation.get("user"); if (worker == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 查询订单 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // // 3. 仅允许待服务状态接单 // if (order.getStatus() == null || order.getStatus() != 2L) { // return AppletControllerUtil.appletWarning("当前订单状态不可接单"); // } // 4. 设置接单相关字段 order.setWorkerId(worker.getId()); order.setWorkerPhone(worker.getPhone()); order.setIsPause(1); // 1:未暂停 order.setReceiveType(3L); // 3:平台派单 order.setReceiveTime(new Date()); order.setIsAccept(1); // 1:已接单 order.setJsonStatus(2); // 服务进度:2=接单 order.setStatus(2L); order.setLogStatus(9); JSONObject json = new JSONObject(); json.put("type", 1); order.setLogJson(json.toJSONString()); orderService.updateOrder(order); // 5. 写入日志 OrderLog orderLog = new OrderLog(); orderLog.setOid(order.getId()); orderLog.setOrderId(order.getOrderId()); orderLog.setTitle("师傅接单"); orderLog.setType(new BigDecimal(2.0)); JSONObject js = new JSONObject(); js.put("name", "同意系统配单"); orderLog.setContent(js.toJSONString()); orderLog.setWorkerId(order.getWorkerId()); orderLog.setWorkerLogId(order.getWorkerId()); orderLogService.insertOrderLog(orderLog); // OrderUtil orderUtil = new OrderUtil(); // orderUtil.SaveOrderLog(order); //如果没有绑定虚拟号就要绑定绑定号码 if (StringUtils.isBlank(order.getMiddlePhone())){ Map bindmap = OrderBindWorkerUtil.getOrderBindWorker(order.getId()); } //发送微信推送通知客户师傅已接单 // 6. 返回成功 return AjaxResult.success("接单成功"); } catch (Exception e) { return AppletControllerUtil.appletError("师傅接单失败:" + e.getMessage()); } } /** * 师傅端订单列表接口 * 查询worker_id为当前师傅的订单,支持状态和预约日期筛选 * * @param params {"limit":10,"page":1,"status":0,"day":""} * @param request HttpServletRequest * @return AjaxResult 带分页的订单列表,结构与json.txt一致 */ @PostMapping("/api/worker/order/lst") public AjaxResult getWorkerOrderList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 校验token并获取师傅信息 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 解析分页和筛选参数 int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 10; int status = params.get("status") != null ? Integer.parseInt(params.get("status").toString()) : 0; String day = params.get("day") != null ? params.get("day").toString() : ""; // 3. 构建查询条件 Order query = new Order(); query.setWorkerId(user.getId()); // 状态筛选 if (status == 2) { query.setStatus(2L); // 待服务 } else if (status == 3) { query.setStatus(3L); // 服务中 } else if (status == 4) { query.setStatus(5L); // 已结束 } else if (status == 5) { query.setStatus(6L); // 已取消 } // status=0查全部 PageHelper.startPage(page, limit); List orderList = orderService.selectOrderList(query); List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdfFull = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date today = new Date(); Date tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000); int todayCount = 0; int tomorrowCount = 0; for (Order order : orderList) { // day筛选逻辑 if (status == 2 && day != null && !day.isEmpty()) { String orderDay = order.getMakeTime() != null ? sdf.format(new Date(order.getMakeTime() * 1000)) : ""; if ("today".equals(day) && !orderDay.equals(sdf.format(today))) continue; if ("tomorrow".equals(day) && !orderDay.equals(sdf.format(tomorrow))) continue; } // 统计今日/明日待服务订单数 if (order.getStatus() != null && order.getStatus() == 2L && order.getMakeTime() != null) { String orderDay = sdf.format(new Date(order.getMakeTime() * 1000)); if (orderDay.equals(sdf.format(today))) todayCount++; if (orderDay.equals(sdf.format(tomorrow))) tomorrowCount++; } Map map = new HashMap<>(); map.put("id", order.getId()); map.put("type", order.getType()); map.put("main_order_id", order.getMainOrderId()); map.put("order_id", order.getOrderId()); map.put("transaction_id", order.getTransactionId()); map.put("create_type", order.getCreateType()); map.put("create_phone", order.getCreatePhone()); map.put("uid", order.getUid()); map.put("product_id", order.getProductId()); map.put("name", order.getName()); map.put("phone", order.getPhone()); // make_time格式化 if (order.getMakeTime() != null && order.getMakeHour() != null) { map.put("make_time", sdf.format(new Date(order.getMakeTime() * 1000)) + " " + order.getMakeHour()); } else { map.put("make_time", null); } map.put("make_hour", order.getMakeHour()); map.put("num", order.getNum()); map.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); map.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); map.put("service_price", order.getServicePrice()); map.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); map.put("coupon_id", order.getCouponId()); map.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); map.put("pay_time", order.getPayTime()); map.put("status", order.getStatus()); map.put("is_pause", order.getIsPause()); map.put("mark", order.getMark()); map.put("address_id", order.getAddressId()); map.put("sku", order.getSku()); map.put("worker_id", order.getWorkerId()); map.put("first_worker_id", order.getFirstWorkerId()); map.put("receive_time", order.getReceiveTime()); map.put("is_comment", order.getIsComment()); map.put("receive_type", order.getReceiveType()); map.put("is_accept", order.getIsAccept()); map.put("middle_phone", order.getMiddlePhone()); map.put("user_phone", order.getUserPhone()); map.put("worker_phone", order.getWorkerPhone()); map.put("address_en", order.getAddressEn()); map.put("uid_admin", order.getUidAdmin()); map.put("address_admin", order.getAddressAdmin()); map.put("log_status", order.getLogStatus()); map.put("log_json", order.getLogJson()); map.put("json_status", order.getJsonStatus()); map.put("log_images", order.getLogImages()); map.put("created_at", order.getCreatedAt() != null ? sdfFull.format(order.getCreatedAt()) : null); map.put("updated_at", order.getUpdatedAt() != null ? sdfFull.format(order.getUpdatedAt()) : null); map.put("deleted_at", order.getDeletedAt()); //map.put("log_type", 1.1); // 兼容log_type // address/address_has UserAddress address = null; if (order.getAddressId() != null) { address = userAddressService.selectUserAddressById(order.getAddressId()); } map.put("address", address); map.put("address_has", address); // product ServiceGoods product = null; if (order.getProductId() != null) { product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); } if (product != null) { Map productMap = new HashMap<>(); productMap.put("id", product.getId()); productMap.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); productMap.put("title", product.getTitle()); productMap.put("price", product.getPrice() != null ? product.getPrice().toString() : "0.00"); productMap.put("sku_type", product.getSkuType()); productMap.put("price_zn", product.getPriceZn()); map.put("product", productMap); } else { map.put("product", null); } resultList.add(map); } PageInfo pageInfo = new PageInfo<>(orderList); Map dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, "/api/worker/order/lst"); // 外层data结构 Map outerData = new HashMap<>(); outerData.put("data", dataPage); Map totalMap = new HashMap<>(); totalMap.put("today", todayCount); totalMap.put("tomorrow", tomorrowCount); outerData.put("total", totalMap); return AjaxResult.success(outerData); } catch (Exception e) { return AppletControllerUtil.appletError("查询师傅订单列表失败:" + e.getMessage()); } } /** * 师傅签到 */ @GetMapping("/api/worker/sign/") public AjaxResult workerSign(HttpServletRequest request) { try { // 1. 校验用户登录 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 判断是否为师傅 if (user.getType() == null || user.getType().equals(2)) { return AppletControllerUtil.appletWarning("您还不是师傅"); } // 3. 更新worker_time user.setWorkerTime(new Date()); int updateResult = usersService.updateUsers(user); // 4. 插入签到记录 WorkerSign workerSign = new WorkerSign(); workerSign.setUid(String.valueOf(user.getId())); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); workerSign.setTime(new Date()); workerSign.setCreatedAt(new Date()); workerSign.setUpdatedAt(new Date()); workerSignService.insertWorkerSign(workerSign); // 5. 返回 if (updateResult > 0) { return AppletControllerUtil.appletSuccess("签到成功"); } else { return AppletControllerUtil.appletWarning("签到失败"); } } catch (Exception e) { return AppletControllerUtil.appletError("签到异常:" + e.getMessage()); } } @PostMapping("/api/worker/stop") public AjaxResult stopWorker(@RequestBody Map params, HttpServletRequest request) { try { // 1. 校验用户登录 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 获取参数 is_stop Object isStopObj = params.get("is_stop"); int isStop = (isStopObj != null && ("1".equals(isStopObj.toString()) || "true".equalsIgnoreCase(isStopObj.toString()))) ? 1 : 0; // 3. 更新用户 is_stop 字段 user.setIsStop(isStop); int result = usersService.updateUsers(user); // 4. 返回 if (result > 0) { return AppletControllerUtil.appletSuccess("成功"); } else { return AppletControllerUtil.appletError("失败"); } } catch (Exception e) { return AppletControllerUtil.appletError("操作异常:" + e.getMessage()); } } /** * 师傅端订单详情接口 * 返回结构见json.txt */ @GetMapping("/api/users/order/info/{id}") public AjaxResult getusersOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 4. 处理时间字段 java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 1. 校验token并获取师傅信息 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users worker = (Users) userValidation.get("user"); if (worker == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 查询订单 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 3. 查询用户信息 Users user = usersService.selectUsersById(order.getUid()); // 4. 查询地址信息 UserAddress address = null; if (order.getAddressId() != null) { address = userAddressService.selectUserAddressById(order.getAddressId()); } // 5. 查询商品信息 ServiceGoods product = null; if (order.getProductId() != null) { product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); } // 6. 查询订单日志 OrderLog logQuery = new OrderLog(); logQuery.setOrderId(order.getOrderId()); List logList = orderLogService.selectOrderLogList(logQuery); List> logArr = new ArrayList<>(); for (OrderLog log : logList) { Map logMap = new HashMap<>(); logMap.put("id", log.getId()); logMap.put("oid", log.getOid()); logMap.put("order_id", log.getOrderId()); logMap.put("log_order_id", log.getLogOrderId()); logMap.put("title", log.getTitle()); logMap.put("type", log.getType()); Object contentObj = null; // content字段为json字符串,需转为对象 if (log.getTitle().equals("订单评价")) { OrderComment comment = new OrderComment(); comment.setOid(log.getOid()); List commentList = orderCommentService.selectOrderCommentList(comment); if(!commentList.isEmpty()){ OrderComment commentDATA = commentList.getFirst(); JSONObject jsonObject = new JSONObject(); jsonObject.put("num",commentDATA.getNum()); jsonObject.put("status",commentDATA.getStatus()); jsonObject.put("text",commentDATA.getContent()); if (org.apache.commons.lang3.StringUtils.isNotBlank(commentDATA.getAdminhf())){ jsonObject.put("admin",commentDATA.getAdminhf()); }else{ jsonObject.put("admin",null); } if (commentDATA.getImages()!=null){ jsonObject.put("image",JSONArray.parseArray(commentDATA.getImages())); } if (commentDATA.getLabels()!=null){ jsonObject.put("labels",JSONArray.parseArray(commentDATA.getLabels())); } contentObj=jsonObject; }else{ JSONObject jsonObject = new JSONObject(); jsonObject.put("status",0); contentObj=jsonObject; } }else if (log.getTitle().equals("已检查评估报价")){ JSONObject jsonObject = JSONObject.from(OrderUtil.getbaojiajson(log.getContent())); contentObj = jsonObject; }else{ try { if (log.getContent() != null) { contentObj = JSONObject.parse(log.getContent()); } } catch (Exception e) { if (AppletControllerUtil.canParseToJSONArray(log.getContent())) { contentObj = JSONArray.parseArray(log.getContent()); } else { contentObj = log.getContent(); } } } logMap.put("content", contentObj); logMap.put("deposit", log.getDeposit()); logMap.put("dep_paid", log.getDepPaid()); logMap.put("dep_pay_time", log.getDepPayTime()); logMap.put("dep_log_id", log.getDepLogId()); logMap.put("cj_money", log.getCjMoney()); logMap.put("cj_paid", log.getCjPaid()); logMap.put("price", log.getPrice()); logMap.put("paid", log.getPaid()); logMap.put("pay_time", log.getPayTime()); logMap.put("log_id", log.getLogId()); logMap.put("worker_id", log.getWorkerId()); logMap.put("first_worker_id", log.getFirstWorkerId()); logMap.put("give_up", log.getGiveUp()); logMap.put("worker_cost", log.getWorkerCost()); logMap.put("reduction_price", log.getReductionPrice()); logMap.put("is_pause", log.getIsPause()); logMap.put("coupon_id", log.getCouponId()); logMap.put("deduction", log.getDeduction()); logMap.put("worker_log_id", log.getWorkerLogId()); logMap.put("created_at", log.getCreatedAt() != null ? dateFormat.format(log.getCreatedAt()) : null); logMap.put("updated_at", log.getUpdatedAt() != null ? dateFormat.format(log.getUpdatedAt()) : null); logMap.put("deleted_at", log.getDeletedAt()); //报价倒计时 logMap.put("orderstatus", order.getStatus()); logMap.put("ordertype", order.getType()); if (!log.getTitle().equals("师傅跟单")) { logArr.add(logMap); } } // 7. 构建返回数据 Map data = new HashMap<>(); Map orderdata = new HashMap<>(); Map yuyuedata = new HashMap<>(); Map baojiadata = new HashMap<>(); if (product != null) { yuyuedata.put("fuwumingcheng", product.getTitle()); yuyuedata.put("fuwutupian", AppletControllerUtil.buildImageUrl(product.getIcon())); } yuyuedata.put("service", order.getProductId()); yuyuedata.put("shuliang", order.getNum()); yuyuedata.put("sku",AppletControllerUtil.parseSkuStringToObject(order.getSku())); if (order.getFileData() != null){ yuyuedata.put("file_data", JSON.parseArray(order.getFileData())); }else{ yuyuedata.put("file_data",JSONArray.parseArray("[]")); } yuyuedata.put("beizhu", order.getReamk()); orderdata.put("yuyueshijian", AppletControllerUtil.timeStamp2Date(order)); orderdata.put("id", order.getId()); orderdata.put("shifupingjia", order.getIsComment()); orderdata.put("shifuzanting", order.getIsPause()); orderdata.put("status", order.getStatus()); orderdata.put("ordertype", order.getOdertype()); if (order.getWorkerId()!=null) { if (Objects.equals(order.getWorkerId(), worker.getId())){ orderdata.put("shifushifubenren","1"); }else{ orderdata.put("shifushifubenren","2"); } }else{ orderdata.put("shifushifubenren","2"); } if (order.getStatus() == 8 && order.getCreatedAt() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(order.getCreatedAt()); calendar.add(Calendar.DAY_OF_MONTH, 3); long deadlineTime = calendar.getTimeInMillis(); orderdata.put("daojishi", deadlineTime); }else{ orderdata.put("daojishi", 0L); } orderdata.put("fuwudizhi", address); orderdata.put("orderStatus", order.getJsonStatus()); orderdata.put("userPhone",order.getUserPhone()); orderdata.put("middlePhone",order.getMiddlePhone()); orderdata.put("zongjia",order.getTotalPrice()); orderdata.put("dingdanbianhao", order.getOrderId()); UserGroupBuying groupBuying =userGroupBuyingService.selectUserGroupBuyingByptorderid(order.getOrderId()); if (groupBuying != null){ orderdata.put("groupid", groupBuying.getOrderid()); } orderdata.put("goodsid", order.getProductId()); orderdata.put("xiadanshijian",order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); Map shifuMap = new HashMap<>(); if (order.getWorkerId() != null&&order.getIsAccept()==1){ Users workerInfo = usersService.selectUsersById(order.getWorkerId()); shifuMap.put("worker_image", AppletControllerUtil.buildImageUrl(workerInfo.getAvatar())); shifuMap.put("worker_name", workerInfo.getName()); shifuMap.put("worker_id", workerInfo.getId()); shifuMap.put("worker_phone", workerInfo.getPhone()); shifuMap.put("isworker", 1); }else{ shifuMap.put("isworker", 2); } data.put("shifuMap", shifuMap); data.put("yuyue", yuyuedata); data.put("dingdan", orderdata); data.put("log", logArr); // Map baojiadingdan = new HashMap<>(); // if (order.getStatus() == 8) { // UserDemandQuotation demandQuotation = new UserDemandQuotation(); // demandQuotation.setOid(order.getId()); // List demandQuotationList = userDemandQuotationService.selectUserDemandQuotationList(demandQuotation); // baojiadingdan.put("baojiashuliang", demandQuotationList.size()); // baojiadingdan.put("zhaungtai", 1); // }else{ // baojiadingdan.put("zhaungtai", 2); // } // data.put("shifubaojia", baojiadingdan); // IUserDemandQuotationService // UserDemandQuotation demandQuotation =new UserDemandQuotation(); // demandQuotation.setWorkerid(order.getWorkerId()); // demandQuotation.setOrderid(order.getOrderId()); // List demandQuotationList = userDemandQuotationService.selectUserDemandQuotationList(demandQuotation); if (order.getOdertype()==4) { baojiadata.put("isbaojia", "1"); //UserDemandQuotation demandQuotationdata=demandQuotationList.getFirst(); // demandQuotationdata.setWorkerimage(AppletControllerUtil.buildImageUrl(demandQuotationdata.getWorkerimage())); // baojiadata.put("baojia", demandQuotationdata); if (order.getStatus() == 8) { UserDemandQuotation demandQuotation3 = new UserDemandQuotation(); demandQuotation3.setOid(order.getId()); List demandQuotationList3 = userDemandQuotationService.selectUserDemandQuotationList(demandQuotation3); baojiadata.put("baojiashuliang", demandQuotationList3.size()); baojiadata.put("zhaungtai", 1); }else{ baojiadata.put("zhaungtai", 2); } }else{ baojiadata.put("isbaojia", "2"); } data.put("baojia", baojiadata); return AjaxResult.success(data); } catch (Exception e) { return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage()); } } /** * 师傅端订单详情接口 * 返回结构见json.txt */ @GetMapping("/api/worker/order/info/{id}") public AjaxResult getWorkerOrderInfo(@PathVariable("id") Long id, HttpServletRequest request) { try { // 4. 处理时间字段 java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 1. 校验token并获取师傅信息 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users worker = (Users) userValidation.get("user"); if (worker == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 查询订单 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 3. 查询用户信息 Users user = usersService.selectUsersById(order.getUid()); // 4. 查询地址信息 UserAddress address = null; if (order.getAddressId() != null) { address = userAddressService.selectUserAddressById(order.getAddressId()); } // else{ // address.setAddressName(); // address. // } // 5. 查询商品信息 ServiceGoods product = null; if (order.getProductId() != null) { product = serviceGoodsService.selectServiceGoodsById(order.getProductId()); } // 6. 查询订单日志 OrderLog logQuery = new OrderLog(); logQuery.setOrderId(order.getOrderId()); List logList = orderLogService.selectOrderLogList(logQuery); List> logArr = new ArrayList<>(); for (OrderLog log : logList) { Map logMap = new HashMap<>(); logMap.put("id", log.getId()); logMap.put("oid", log.getOid()); logMap.put("order_id", log.getOrderId()); logMap.put("log_order_id", log.getLogOrderId()); logMap.put("title", log.getTitle()); logMap.put("type", log.getType()); // // logMap.put("content", contentObj); Object contentObj = null; // content字段为json字符串,需转为对象 if (log.getTitle().equals("订单评价")) { OrderComment comment = new OrderComment(); comment.setOid(log.getOid()); List commentList = orderCommentService.selectOrderCommentList(comment); if(!commentList.isEmpty()){ OrderComment commentDATA = commentList.getFirst(); JSONObject jsonObject = new JSONObject(); jsonObject.put("num",commentDATA.getNum()); jsonObject.put("status",commentDATA.getStatus()); jsonObject.put("text",commentDATA.getContent()); if (org.apache.commons.lang3.StringUtils.isNotBlank(commentDATA.getAdminhf())){ jsonObject.put("admin",commentDATA.getAdminhf()); }else{ jsonObject.put("admin",null); } if (commentDATA.getImages()!=null){ jsonObject.put("image",JSONArray.parseArray(commentDATA.getImages())); } if (commentDATA.getLabels()!=null){ jsonObject.put("labels",JSONArray.parseArray(commentDATA.getLabels())); } contentObj=jsonObject; }else{ JSONObject jsonObject = new JSONObject(); jsonObject.put("status",0); contentObj=jsonObject; } }else if (log.getTitle().equals("已检查评估报价")){ JSONObject jsonObject = JSONObject.from(OrderUtil.getbaojiajson(log.getContent())); contentObj = jsonObject; }else{ try { if (log.getContent() != null) { contentObj = JSONObject.parse(log.getContent()); } } catch (Exception e) { if (AppletControllerUtil.canParseToJSONArray(log.getContent())) { contentObj = JSONArray.parseArray(log.getContent()); } else { contentObj = log.getContent(); } } } logMap.put("content", contentObj); logMap.put("deposit", log.getDeposit()); logMap.put("dep_paid", log.getDepPaid()); logMap.put("dep_pay_time", log.getDepPayTime()); logMap.put("dep_log_id", log.getDepLogId()); logMap.put("cj_money", log.getCjMoney()); logMap.put("cj_paid", log.getCjPaid()); logMap.put("price", log.getPrice()); logMap.put("paid", log.getPaid()); logMap.put("pay_time", log.getPayTime()); logMap.put("log_id", log.getLogId()); logMap.put("worker_id", log.getWorkerId()); logMap.put("first_worker_id", log.getFirstWorkerId()); logMap.put("give_up", log.getGiveUp()); logMap.put("worker_cost", log.getWorkerCost()); logMap.put("reduction_price", log.getReductionPrice()); logMap.put("is_pause", log.getIsPause()); logMap.put("coupon_id", log.getCouponId()); logMap.put("deduction", log.getDeduction()); logMap.put("worker_log_id", log.getWorkerLogId()); logMap.put("created_at", log.getCreatedAt() != null ? dateFormat.format(log.getCreatedAt()) : null); logMap.put("updated_at", log.getUpdatedAt() != null ? dateFormat.format(log.getUpdatedAt()) : null); logMap.put("deleted_at", log.getDeletedAt()); //报价倒计时 logMap.put("orderstatus", order.getStatus()); logMap.put("ordertype", order.getType()); logArr.add(logMap); } // 7. 构建返回数据 Map data = new HashMap<>(); Map orderdata = new HashMap<>(); Map yuyuedata = new HashMap<>(); Map baojiadata = new HashMap<>(); if (product != null) { yuyuedata.put("fuwumingcheng", product.getTitle()); yuyuedata.put("fuwutupian", AppletControllerUtil.buildImageUrl(product.getIcon())); } yuyuedata.put("service", order.getProductId()); yuyuedata.put("shuliang", order.getNum()); yuyuedata.put("sku",AppletControllerUtil.parseSkuStringToObject(order.getSku())); if (order.getFileData() != null){ yuyuedata.put("file_data", JSON.parseArray(order.getFileData())); }else{ yuyuedata.put("file_data",JSONArray.parseArray("[]")); } yuyuedata.put("beizhu", order.getReamk()); orderdata.put("yuyueshijian", AppletControllerUtil.timeStamp2Date(order)); orderdata.put("id", order.getId()); orderdata.put("shifuzanting", order.getIsPause()); orderdata.put("status", order.getStatus()); orderdata.put("ordertype", order.getOdertype()); if (order.getWorkerId()!=null) { System.out.println("订单中的用户id"+order.getWorkerId()); System.out.println("当前登录用户用户id"+user.getId()); if (Objects.equals(order.getWorkerId(), worker.getId())){ orderdata.put("shifushifubenren","1"); }else{ orderdata.put("shifushifubenren","2"); } }else{ orderdata.put("shifushifubenren","2"); } if (order.getStatus() == 8 && order.getCreatedAt() != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(order.getCreatedAt()); calendar.add(Calendar.DAY_OF_MONTH, 3); long deadlineTime = calendar.getTimeInMillis(); orderdata.put("daojishi", deadlineTime); }else{ orderdata.put("daojishi", 0L); } orderdata.put("fuwudizhi", address); orderdata.put("orderStatus", order.getJsonStatus()); orderdata.put("userPhone",order.getUserPhone()); orderdata.put("middlePhone",order.getMiddlePhone()); orderdata.put("zongjia",order.getTotalPrice()); orderdata.put("dingdanbianhao", order.getOrderId()); orderdata.put("xiadanshijian",order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); data.put("yuyue", yuyuedata); data.put("dingdan", orderdata); data.put("log", logArr); // IUserDemandQuotationService UserDemandQuotation demandQuotation =new UserDemandQuotation(); demandQuotation.setWorkerid(order.getWorkerId()); demandQuotation.setOrderid(order.getOrderId()); List demandQuotationList = userDemandQuotationService.selectUserDemandQuotationList(demandQuotation); if (demandQuotationList != null && !demandQuotationList.isEmpty() &&order.getOdertype()==4) { baojiadata.put("isbaojia", "1"); UserDemandQuotation demandQuotationdata=demandQuotationList.getFirst(); demandQuotationdata.setWorkerimage(AppletControllerUtil.buildImageUrl(demandQuotationdata.getWorkerimage())); baojiadata.put("baojia", demandQuotationdata); }else{ baojiadata.put("isbaojia", "2"); } data.put("baojia", baojiadata); // 添加上门标准数据 try { SiteConfig serviceStandardConfig = siteConfigService.selectSiteConfigByName("config_ten"); if (serviceStandardConfig != null && serviceStandardConfig.getValue() != null) { try { JSONObject configJson = JSONObject.parseObject(serviceStandardConfig.getValue()); if (configJson.containsKey("serviceStandard")) { data.put("serviceStandard", configJson.getString("serviceStandard")); } else { data.put("serviceStandard", ""); } } catch (Exception e) { logger.warn("解析上门标准配置失败: " + e.getMessage()); data.put("serviceStandard", ""); } } else { data.put("serviceStandard", ""); } } catch (Exception e) { logger.warn("获取上门标准配置失败: " + e.getMessage()); data.put("serviceStandard", ""); } return AjaxResult.success(data); } catch (Exception e) { return AppletControllerUtil.appletError("查询师傅订单详情失败:" + e.getMessage()); } } /** * 支付尾款回调到页面的数据 */ @PostMapping("/api/service/order/pay/total/price/info") public AjaxResult getOrderPayLastInfo(@RequestBody Map params) { try { String orderId = (String) params.get("order_id"); if (StringUtils.isEmpty(orderId)) { return AppletControllerUtil.appletWarning("订单号不能为空"); } // 1. 查询订单 Order order = orderService.selectOrderByOrderId(orderId); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 2. 查询订单日志(取type=5评估报价,或最新一条) List logList = orderLogService.selectOrderLogByOrderId(orderId); OrderLog log = null; for (OrderLog l : logList) { if (l.getType() != null && l.getType().intValue() == 5) { log = l; break; } } if (log == null && !logList.isEmpty()) { log = logList.get(0); } if (log == null) { return AppletControllerUtil.appletWarning("未找到订单日志"); } // 3. 组装content字段 JSONObject contentJson; try { contentJson = JSONObject.parseObject(log.getContent()); } catch (Exception e) { contentJson = new JSONObject(); } // 4. 组装返回数据 Map data = new HashMap<>(); data.put("id", log.getId()); data.put("oid", log.getOid()); data.put("order_id", log.getOrderId()); data.put("log_order_id", log.getLogOrderId()); data.put("title", log.getTitle()); data.put("type", log.getType() != null ? log.getType().intValue() : null); data.put("content", contentJson); data.put("deposit", log.getDeposit() != null ? log.getDeposit().toString() : "0.00"); data.put("dep_paid", log.getDepPaid()); data.put("dep_pay_time", log.getDepPayTime()); data.put("dep_log_id", log.getDepLogId()); data.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); data.put("paid", log.getPaid()); data.put("pay_time", log.getPayTime() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(log.getPayTime() * 1000)) : null); data.put("log_id", log.getLogId()); data.put("worker_id", log.getWorkerId()); data.put("first_worker_id", log.getFirstWorkerId()); data.put("give_up", log.getGiveUp()); data.put("worker_cost", log.getWorkerCost()); data.put("reduction_price", log.getReductionPrice() != null ? log.getReductionPrice().toString() : "0.00"); data.put("is_pause", log.getIsPause()); data.put("coupon_id", log.getCouponId()); data.put("deduction", log.getDeduction()); data.put("worker_log_id", log.getWorkerLogId()); data.put("created_at", log.getCreatedAt() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getCreatedAt()) : null); data.put("updated_at", log.getUpdatedAt() != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getUpdatedAt()) : null); data.put("deleted_at", log.getDeletedAt()); return AppletControllerUtil.appletSuccess(data); } catch (Exception e) { return AppletControllerUtil.appletWarning("查询失败:" + e.getMessage()); } } /** * 师傅列表接 */ @PostMapping("/api/worker/user/lst") public AjaxResult getWorkerUserList(@RequestBody Map params) { try { int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; String keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : null; // 查询type=2的师傅 Users query = new Users(); // 解析 area if (params.containsKey("area")) { Object areaObj = params.get("area"); if (areaObj instanceof List) { query.setAreaList((List) areaObj); } else if (areaObj instanceof String) { query.setAreaList(JSON.parseArray(areaObj.toString(), String.class)); } } // 解析 skill if (params.containsKey("skill")) { query.setSkill(params.get("skill").toString()); } query.setType("2"); if (keywords != null && !keywords.isEmpty()) { query.setName(keywords); } PageHelper.startPage(page, limit); List userList = usersService.selectUsersList(query); PageInfo pageInfo = new PageInfo<>(userList); List> resultList = new ArrayList<>(); for (Users user : userList) { Map map = new HashMap<>(); map.put("id", user.getId()); map.put("name", user.getName()); // 头像处理 String avatar = user.getAvatar(); if (avatar != null && !avatar.isEmpty()) { if (!avatar.startsWith("http")) { avatar = "https://img.huafurenjia.cn/" + avatar.replaceFirst("^/+", ""); } } else { avatar = "https://img.huafurenjia.cn//default/user_avatar.jpeg"; } map.put("avatar", avatar); map.put("phone", user.getPhone()); map.put("service_city_ids", user.getServiceCityIds()); map.put("skill_ids", user.getSkillIds()); // city名称数组 List cityNames = new ArrayList<>(); List cityIds = AppletControllerUtil.parseStringToList(user.getServiceCityIds()); for (String cityIdStr : cityIds) { try { if (cityIdStr != null && !cityIdStr.trim().isEmpty()) { Integer cityId = Integer.valueOf(cityIdStr); DiyCity city = diyCityService.selectDiyCityById(cityId); if (city != null && city.getTitle() != null) { cityNames.add(city.getTitle()); } } } catch (Exception ignore) { } } map.put("city", cityNames); // skill名称数组 List skillNames = new ArrayList<>(); List skillIds = AppletControllerUtil.parseStringToList(user.getSkillIds()); for (String skillIdStr : skillIds) { try { if (skillIdStr != null && !skillIdStr.trim().isEmpty()) { Long skillId = Long.valueOf(skillIdStr); SiteSkill skill = siteSkillService.selectSiteSkillById(skillId); if (skill != null && skill.getTitle() != null) { skillNames.add(skill.getTitle()); } } } catch (Exception ignore) { } } map.put("skill", skillNames); resultList.add(map); } // 构建分页数据 Map data = new HashMap<>(); data.put("current_page", pageInfo.getPageNum()); data.put("data", resultList); data.put("first_page_url", "https://www.huafurenjia.cn/api/worker/user/lst?page=1"); data.put("from", pageInfo.getStartRow()); data.put("last_page", pageInfo.getPages()); data.put("last_page_url", "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPages()); // 构建links List> links = new ArrayList<>(); Map prevLink = new HashMap<>(); prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null); prevLink.put("label", "« Previous"); prevLink.put("active", false); links.add(prevLink); for (int i = 1; i <= pageInfo.getPages(); i++) { Map link = new HashMap<>(); link.put("url", "https://www.huafurenjia.cn/api/worker/user/lst?page=" + i); link.put("label", String.valueOf(i)); link.put("active", i == pageInfo.getPageNum()); links.add(link); } Map nextLink = new HashMap<>(); nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null); nextLink.put("label", "Next »"); nextLink.put("active", false); links.add(nextLink); data.put("links", links); data.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getNextPage() : null); data.put("path", "https://www.huafurenjia.cn/api/worker/user/lst"); data.put("per_page", pageInfo.getPageSize()); data.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/user/lst?page=" + pageInfo.getPrePage() : null); data.put("to", pageInfo.getEndRow()); data.put("total", pageInfo.getTotal()); return AjaxResult.success(data); } catch (Exception e) { return AjaxResult.error("查询师傅列表失败:" + e.getMessage()); } } /** * 用户申请师傅接口 */ @PostMapping("/api/form/apply/worker") public AjaxResult applyWorker(@RequestBody Map params, HttpServletRequest request) { try { // 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 构建WorkerApply对象 WorkerApply apply = new WorkerApply(); apply.setUid(user.getId()); apply.setName((String) params.getOrDefault("name", "")); apply.setPhone((String) params.getOrDefault("phone", "")); apply.setAddress((String) params.getOrDefault("address", "")); apply.setCardNo((String) params.getOrDefault("card_no", "")); // city_pid Object cityPidObj = params.get("city_pid"); if (cityPidObj != null) { try { apply.setCityPid(Long.valueOf(cityPidObj.toString())); } catch (Exception ignore) {} } // city_ids Object cityIdsObj = params.get("city_ids"); if (cityIdsObj instanceof List) { List cityIdsList = (List) cityIdsObj; apply.setCityIds(cityIdsList.toString().replace(" ","")); // 存字符串如[5,7,10,11] } else if (cityIdsObj != null) { apply.setCityIds(cityIdsObj.toString()); } // skill_id Object skillIdObj = params.get("skill_id"); if (skillIdObj instanceof List) { List skillIdList = (List) skillIdObj; apply.setSkillId(skillIdList.toString().replace(" ","")); } else if (skillIdObj != null) { apply.setSkillId(skillIdObj.toString()); } // 图片相关 apply.setSkill((String) params.getOrDefault("skill", "")); apply.setCriminal((String) params.getOrDefault("criminal", "")); apply.setDrive((String) params.getOrDefault("drive", "")); apply.setEducation((String) params.getOrDefault("education", "")); apply.setHealth((String) params.getOrDefault("health", "")); apply.setImage((String) params.getOrDefault("image", "")); // 其他字段可按需补充 int result = workerApplyService.insertWorkerApply(apply); if (result > 0) { return AppletControllerUtil.appletSuccess("申请已提交"); } else { return AppletControllerUtil.appletWarning("申请提交失败,请稍后重试"); } } catch (Exception e) { return AppletControllerUtil.appletError("申请失败:" + e.getMessage()); } } /** * 师傅转单接口 * * @param orderId 订单ID * @param newWorkerId 新师傅ID * @return 操作结果 */ @GetMapping("/api/worker/change/order/{orderId}") public AjaxResult changeWorkerOrder(@PathVariable("orderId") Long orderId, @RequestParam("id") Long newWorkerId) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 1. 查询订单 Order order = orderService.selectOrderById(orderId); if (order == null) { return AjaxResult.error("订单不存在"); } // 2. 查询新师傅信息 Users newWorker = usersService.selectUsersById(newWorkerId); if (newWorker == null) { return AjaxResult.error("新师傅不存在"); } // 3. 查询原师傅信息 Users oldWorker = null; if (order.getWorkerId() != null) { oldWorker = usersService.selectUsersById(order.getWorkerId()); } // 4. 修改订单的师傅id order.setWorkerId(newWorkerId); order.setStatus(1L); order.setIsAccept(0); int updateOrder = orderService.updateOrder(order); if (updateOrder <= 0) { return AjaxResult.error("订单更新失败"); } //查询最新的订单日志 OrderLog log = orderLogService.selectDataTheFirstNew(order.getId()); OrderLog log1 = new OrderLog(); log1.setOid(order.getId()); //原订单日志下所有师傅id需更换为新的师傅id List logList = orderLogService.selectOrderLogList(log1); if (!logList.isEmpty()) { for (OrderLog l : logList) { if (l.getWorkerId() != null) { l.setWorkerId(newWorkerId); orderLogService.updateOrderLog(l); } } } //如果订单状态为6就继续做 if (log.getType().compareTo(new BigDecimal("6.0")) == 0) { // 2. 组装日志内容为数组格式 Map logItem = new LinkedHashMap<>(); JSONArray jsonArray = JSONArray.parseArray(log.getContent()); logItem.put("name", "师傅" + newWorker.getName() + "将继续为您服务 不需要预约时间"); logItem.put("name", "暂停服务"); logItem.put("image", ""); logItem.put("reson", "由于订单师傅更换,自动暂停服务"); logItem.put("next_time", ""); logItem.put("type", 2); logItem.put("date", sdf.format(new Date())); jsonArray.add(logItem); if (log != null) { log.setIsPause(2); log.setContent(jsonArray.toJSONString()); orderLogService.updateOrderLog(log); order.setIsPause(2); order.setWorkerId(newWorkerId); orderService.updateOrder(order); } } else { // 5. 插入转单日志 OrderLog newlog = new OrderLog(); if (log.getType().compareTo(new BigDecimal("5.0")) == 0) { newlog.setType(new BigDecimal(6.0)); } else { newlog.setType(new BigDecimal(1.1)); } JSONObject jsonObjectnew = new JSONObject(); jsonObjectnew.put("name", "师傅" + newWorker.getName() + "将继续为您服务 不需要预约时间"); jsonObjectnew.put("convert", oldWorker.getName() + "将订单转给" + newWorker.getName()); newlog.setContent(jsonObjectnew.toJSONString()); newlog.setOid(order.getId()); newlog.setOrderId(order.getOrderId()); newlog.setWorkerId(newWorkerId); newlog.setWorkerLogId(newWorkerId); newlog.setTitle("转单"); newlog.setIsPause(2); orderLogService.insertOrderLog(newlog); //需要解绑原订单上原师傅和客户的虚拟号 VoiceResponseResult resultObj = YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone(), order.getId()); if (resultObj.getResult().equals("000000")) { orderService.updateOrderPhone(order.getId()); // orderService.updateOrder(order); } //绑定新师傅的虚拟号 //给新师傅进行电话通知 YunXinPhoneUtilAPI.httpsAxbTransfer(newWorker.getPhone(), order.getId()); } return AjaxResult.success("转单成功"); } catch (Exception e) { return AjaxResult.error("转单失败:" + e.getMessage()); } } /** * 师傅首页接口 * 返回结构见json.txt */ @PostMapping("/api/worker/index") public AjaxResult getWorkerdataIndex(@RequestBody Map params, HttpServletRequest request) { try { // 1. 校验token并获取师傅信息 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 6. 禁止接单剩余时间 if (user.getProhibitTime() != null && user.getProhibitTimeNum() != null) { long now = System.currentTimeMillis() / 1000; long prohibitStart = user.getProhibitTime().getTime() / 1000; long prohibitEnd = prohibitStart + user.getProhibitTimeNum() * 3600; if (prohibitStart < now && prohibitEnd > now) { long residue = prohibitEnd - now; long hours = residue / 3600; long minutes = (residue % 3600) / 60; long seconds = residue % 60; StringBuilder str = new StringBuilder(); if (hours > 0) str.append(hours).append("小时"); if (minutes > 0) str.append(minutes).append("分钟"); if (seconds > 0) str.append(seconds).append("秒"); user.setProhibit("因违反平台规定," + user.getProhibitTimeNum() + "小时内禁止接单,剩余" + str); } } // 2. 查询等级信息 Object levelInfo = null; String levelImg = null; if (user.getLevel() != null) { WorkerLevel level = workerLevelService.selectWorkerLevelById(Long.valueOf(user.getLevel())); if (level != null) { Map levelMap = new HashMap<>(); levelMap.put("id", level.getId()); levelMap.put("image", level.getImage()); levelImg = level.getImage(); levelMap.put("title", level.getTitle()); levelInfo = levelMap; } } // 3. 查询技能数组 List> skillArr = new ArrayList<>(); List skillIds = AppletControllerUtil.parseStringToList(user.getSkillIds()); for (String skillIdStr : skillIds) { try { if (skillIdStr != null && !skillIdStr.trim().isEmpty()) { Long skillId = Long.valueOf(skillIdStr); SiteSkill skill = siteSkillService.selectSiteSkillById(skillId); if (skill != null) { Map skillMap = new HashMap<>(); skillMap.put("id", skill.getId()); skillMap.put("title", skill.getTitle()); skillArr.add(skillMap); } } } catch (Exception ignore) { } } // 4. 查询服务城市数组 List> cityArr = new ArrayList<>(); List cityIds = AppletControllerUtil.parseStringToList(user.getServiceCityIds()); for (String cityIdStr : cityIds) { try { if (cityIdStr != null && !cityIdStr.trim().isEmpty()) { Integer cityId = Integer.valueOf(cityIdStr); DiyCity city = diyCityService.selectDiyCityById(cityId); if (city != null) { Map cityMap = new HashMap<>(); cityMap.put("id", city.getId()); cityMap.put("title", city.getTitle()); cityArr.add(cityMap); } } } catch (Exception ignore) { } } // 5. 统计评价 OrderComment commentQuery = new OrderComment(); commentQuery.setWorkerId(user.getId()); List commentList = orderCommentService.selectOrderCommentList(commentQuery); int one = 0, two = 0, three = 0; for (OrderComment c : commentList) { if (c.getNumType() != null) { if (c.getNumType() == 1L) one++; else if (c.getNumType() == 2L) two++; else if (c.getNumType() == 3L) three++; } } int total = commentList.size(); Map commentStat = new HashMap<>(); commentStat.put("one", one); commentStat.put("two", two); commentStat.put("three", three); commentStat.put("total", total); // 6. 构建user数据 Map userMap = buildUserInfoResponse(user); userMap.put("level_info", levelInfo); userMap.put("skill_arr", skillArr); userMap.put("service_city_arr", cityArr); userMap.put("level_img", levelImg); // 7. 处理分页和type筛选,默认参数 int page = 1; int limit = 15; int type = 0; List filteredList = new ArrayList<>(); if (params != null) { params = new HashMap<>(); page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; type = params.get("type") != null ? Integer.parseInt(params.get("type").toString()) : 0; // 过滤type for (OrderComment c : commentList) { if (type == 0 || (type == 1 && c.getNumType() != null && c.getNumType() == 1L) || (type == 2 && c.getNumType() != null && c.getNumType() == 2L) || (type == 3 && c.getNumType() != null && c.getNumType() == 3L)) { filteredList.add(c); } } } else { filteredList.addAll(commentList); } int totalCount = filteredList.size(); int from = (page - 1) * limit; int to = Math.min(from + limit, totalCount); List> commentArr = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日"); for (int i = from; i < to; i++) { OrderComment c = filteredList.get(i); Map cMap = new HashMap<>(); cMap.put("id", c.getId()); cMap.put("uid", c.getUid()); if (StringUtils.isNotBlank(c.getImages())){ cMap.put("images", JSONArray.parseArray(c.getImages())); }else{ cMap.put("images", JSONArray.parseArray("[]")); } cMap.put("content", c.getContent()); cMap.put("num", c.getNum()); cMap.put("created_at", c.getCreatedAt() != null ? sdf.format(c.getCreatedAt()) : null); cMap.put("time", c.getCreatedAt() != null ? sdf2.format(c.getCreatedAt()) : null); // 查询用户信息 Map uMap = new HashMap<>(); Users u = usersService.selectUsersById(c.getUid()); if (u != null) { uMap.put("id", u.getId()); uMap.put("name", u.getName()); String avatar = u.getAvatar(); if (avatar != null && !avatar.isEmpty()) { if (!avatar.startsWith("http")) { avatar = "https://img.huafurenjia.cn/" + avatar.replaceFirst("^/+", ""); } } else { avatar = "https://img.huafurenjia.cn//default/user_avatar.jpeg"; } uMap.put("avatar", avatar); } cMap.put("user", uMap); commentArr.add(cMap); } // 8. 构建分页结构 Map pageData = new HashMap<>(); pageData.put("current_page", page); pageData.put("data", commentArr); pageData.put("first_page_url", "https://www.huafurenjia.cn/api/worker/index?page=1"); pageData.put("from", totalCount == 0 ? null : from + 1); int lastPage = (int) Math.ceil((double) totalCount / limit); pageData.put("last_page", lastPage); pageData.put("last_page_url", "https://www.huafurenjia.cn/api/worker/index?page=" + lastPage); // links List> links = new ArrayList<>(); Map prevLink = new HashMap<>(); prevLink.put("url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null); prevLink.put("label", "« Previous"); prevLink.put("active", false); links.add(prevLink); for (int i = 1; i <= lastPage; i++) { Map link = new HashMap<>(); link.put("url", "https://www.huafurenjia.cn/api/worker/index?page=" + i); link.put("label", String.valueOf(i)); link.put("active", i == page); links.add(link); } Map nextLink = new HashMap<>(); nextLink.put("url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null); nextLink.put("label", "Next »"); nextLink.put("active", false); links.add(nextLink); pageData.put("links", links); pageData.put("next_page_url", page < lastPage ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page + 1) : null); pageData.put("path", "https://www.huafurenjia.cn/api/worker/index"); pageData.put("per_page", String.valueOf(limit)); pageData.put("prev_page_url", page > 1 ? "https://www.huafurenjia.cn/api/worker/index?page=" + (page - 1) : null); pageData.put("to", totalCount == 0 ? null : to); pageData.put("total", totalCount); // 9. 构建最终返回结构 Map data = new HashMap<>(); data.put("user", userMap); data.put("data", pageData); data.put("comment", commentStat); return AjaxResult.success(data); } catch (Exception e) { return AppletControllerUtil.appletError("获取师傅首页数据失败:" + e.getMessage()); } } /** * 师傅签到日志接口 * * @param request * @return 签到日志列表 */ @GetMapping("/api/form/worker/apply/check") public AjaxResult apiformworkerapplycheck(HttpServletRequest request) { try { // 校验token并获取用户 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } WorkerApply workerApply = new WorkerApply(); workerApply.setUid(user.getId()); List workerApplyList = workerApplyService.selectWorkerApplyList(workerApply); if (workerApplyList == null || workerApplyList.isEmpty()) { return AppletControllerUtil.appletSuccess(null); } return AjaxResult.success(workerApplyList.getFirst()); } catch (Exception e) { return AjaxResult.error("查询签到日志失败:" + e.getMessage()); } } /** * 师傅签到日志接口 * * @param params {year: "2025", month: "06"} * @param request * @return 签到日志列表 */ @PostMapping("/api/worker/sign/log") public AjaxResult getWorkerSignLog(@RequestBody Map params, HttpServletRequest request) { try { // 校验token并获取用户 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } if (params == null || !params.containsKey("year") || !params.containsKey("month")) { return AppletControllerUtil.appletWarning("参数year和month不能为空"); } String year = params.get("year").toString(); String month = params.get("month").toString(); // 构造当月起止日期 String startDate = year + "-" + month + "-01"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date start = sdf.parse(startDate); Calendar cal = Calendar.getInstance(); cal.setTime(start); cal.set(Calendar.DAY_OF_MONTH, 1); int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, maxDay); Date end = cal.getTime(); // 查询签到记录 WorkerSign query = new WorkerSign(); query.setUid(String.valueOf(user.getId())); List allList = workerSignService.selectWorkerSignList(query); List> result = new ArrayList<>(); for (WorkerSign sign : allList) { if (sign.getTime() != null && !sign.getTime().before(start) && !sign.getTime().after(end)) { Map map = new HashMap<>(); map.put("id", sign.getId()); map.put("date", sdf.format(sign.getTime())); map.put("info", "签到"); // Users u = usersService.selectUsersById(Long.valueOf(sign.getUid())); // if (u != null){ // map.put("info", u); // }else{ // map.put("info", ""); // } result.add(map); } } return AjaxResult.success(result); } catch (Exception e) { return AjaxResult.error("查询签到日志失败:" + e.getMessage()); } } /** * 师傅质保金日志接口 * * @param params {"limit":15,"page":1} * @param request * @return 质保金日志分页数据和师傅信息 */ @PostMapping("/api/worker/mergin/log") public AjaxResult getWorkerMarginLog(@RequestBody Map params, HttpServletRequest request) { try { // 校验token并获取用户 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; // 查询质保金日志 WorkerMarginLog query = new WorkerMarginLog(); query.setUid(user.getId()); PageHelper.startPage(page, limit); List logList = workerMarginLogService.selectWorkerMarginLogList(query); PageInfo pageInfo = new PageInfo<>(logList); List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (WorkerMarginLog log : logList) { Map map = new HashMap<>(); map.put("id", log.getId()); map.put("uid", log.getUid()); map.put("oid", log.getOid()); map.put("reamk", log.getReamk()); map.put("order_id", log.getOrderId()); map.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); resultList.add(map); } // 构建分页结构 Map dataPage = new HashMap<>(); dataPage.put("current_page", pageInfo.getPageNum()); dataPage.put("data", resultList); dataPage.put("first_page_url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=1"); dataPage.put("from", pageInfo.getStartRow()); dataPage.put("last_page", pageInfo.getPages()); dataPage.put("last_page_url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPages()); // links List> links = new ArrayList<>(); Map prevLink = new HashMap<>(); prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null); prevLink.put("label", "« Previous"); prevLink.put("active", false); links.add(prevLink); for (int i = 1; i <= pageInfo.getPages(); i++) { Map link = new HashMap<>(); link.put("url", "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + i); link.put("label", String.valueOf(i)); link.put("active", i == pageInfo.getPageNum()); links.add(link); } Map nextLink = new HashMap<>(); nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null); nextLink.put("label", "Next »"); nextLink.put("active", false); links.add(nextLink); dataPage.put("links", links); dataPage.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getNextPage() : null); dataPage.put("path", "https://www.huafurenjia.cn/api/worker/mergin/log"); dataPage.put("per_page", limit); dataPage.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/mergin/log?page=" + pageInfo.getPrePage() : null); dataPage.put("to", pageInfo.getEndRow()); dataPage.put("total", pageInfo.getTotal()); // 构建user信息 Map userMap = buildUserInfoResponse(user); // 最终返回结构 Map data = new HashMap<>(); data.put("data", dataPage); data.put("user", userMap); return AjaxResult.success(data); } catch (Exception e) { return AjaxResult.error("查询质保金日志失败:" + e.getMessage()); } } /** * 师傅收益明细接口 * * @param params {"limit":15,"page":1,"type":"1"} * @param request * @return 收益明细分页数据 */ @PostMapping("/api/worker/money/log") public AjaxResult getWorkerMoneyLog(@RequestBody Map params, HttpServletRequest request) { try { // 校验token并获取用户 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; String type = params.get("type") != null ? params.get("type").toString() : null; // 查询收益明细 WorkerMoneyLog query = new WorkerMoneyLog(); query.setWorkerId(user.getId()); if (type != null && !type.isEmpty()) { query.setType(Integer.valueOf(type)); } PageHelper.startPage(page, limit); List logList = workerMoneyLogService.selectWorkerMoneyLogList(query); PageInfo pageInfo = new PageInfo<>(logList); List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (WorkerMoneyLog log : logList) { Map map = new HashMap<>(); map.put("id", log.getId()); map.put("worker_id", log.getWorkerId()); map.put("oid", log.getOid()); map.put("order_id", log.getOrderId()); map.put("price", log.getPrice() != null ? log.getPrice().toString() : "0.00"); map.put("type", log.getType()); map.put("service_price", log.getServicePrice() != null ? log.getServicePrice().toString() : "0.00"); map.put("reduction_price", log.getReductionPrice() != null ? log.getReductionPrice().toString() : "0.00"); map.put("cr", log.getCr()); map.put("goodsmoney",log.getClmoney()); // map.put("jsfs","服务佣金:1397.00*60.0000=838.20\\n材料费用:180.00材料分佣:0\\n质保金:(838.20+0)*质保金基数(10%)=83.82\\n最终应得:838.20+0-83.82+0=754.38"); map.put("jsfs", log.getGongshi()); map.put("status", log.getStatus()); map.put("lookday", log.getLookday()); map.put("status_type", log.getStatusType()); map.put("beginlook", log.getBeginlook() != null ? log.getBeginlook().toString() : null); map.put("endlook", log.getEndlook() != null ? log.getEndlook().toString() : null); map.put("look_money", log.getLookMoney()); map.put("admin_up_price", log.getAdminUpPrice()); map.put("admin_up_reamk", log.getAdminUpReamk()); map.put("mergin", log.getMergin() != null ? log.getMergin().toString() : "0.00"); map.put("door_price", log.getDoorPrice() != null ? log.getDoorPrice().toString() : null); map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); resultList.add(map); } // 构建分页结构 Map dataPage = new HashMap<>(); dataPage.put("current_page", pageInfo.getPageNum()); dataPage.put("data", resultList); dataPage.put("first_page_url", "https://www.huafurenjia.cn/api/worker/money/log?page=1"); dataPage.put("from", pageInfo.getStartRow()); dataPage.put("last_page", pageInfo.getPages()); dataPage.put("last_page_url", "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPages()); // links List> links = new ArrayList<>(); Map prevLink = new HashMap<>(); prevLink.put("url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null); prevLink.put("label", "« Previous"); prevLink.put("active", false); links.add(prevLink); for (int i = 1; i <= pageInfo.getPages(); i++) { Map link = new HashMap<>(); link.put("url", "https://www.huafurenjia.cn/api/worker/money/log?page=" + i); link.put("label", String.valueOf(i)); link.put("active", i == pageInfo.getPageNum()); links.add(link); } Map nextLink = new HashMap<>(); nextLink.put("url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null); nextLink.put("label", "Next »"); nextLink.put("active", false); links.add(nextLink); dataPage.put("links", links); dataPage.put("next_page_url", pageInfo.isHasNextPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getNextPage() : null); dataPage.put("path", "https://www.huafurenjia.cn/api/worker/money/log"); dataPage.put("per_page", limit); dataPage.put("prev_page_url", pageInfo.isHasPreviousPage() ? "https://www.huafurenjia.cn/api/worker/money/log?page=" + pageInfo.getPrePage() : null); dataPage.put("to", pageInfo.getEndRow()); dataPage.put("total", pageInfo.getTotal()); return AjaxResult.success(dataPage); } catch (Exception e) { return AjaxResult.error("查询收益明细失败:" + e.getMessage()); } } /** * 师傅提现记录接口 * 查询当前师傅的提现记录,支持分页和类型筛选 * * @param params {"limit":15,"page":1,"type":2} * @param request HttpServletRequest * @return AjaxResult 分页提现记录 */ @PostMapping("/api/worker/withdraw_log") public AjaxResult getWorkerWithdrawLog(@RequestBody Map params, HttpServletRequest request) { try { // 1. 校验token并获取用户 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } // 2. 解析分页和筛选参数 int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; // 3. 构建查询条件 WechatTransfer query = new WechatTransfer(); query.setUid(user.getId()); //if (type != null) query.setStatus(type); PageHelper.startPage(page, limit); List logList = wechatTransferService.selectWechatTransferList(query); PageInfo pageInfo = new PageInfo<>(logList); // 4. 数据组装 List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (WechatTransfer log : logList) { Map map = new HashMap<>(); map.put("id", log.getId()); map.put("uid", log.getUid()); map.put("batch_id", log.getBatchId()); map.put("money", log.getMoney() != null ? log.getMoney().toString() : "0.00"); map.put("status", log.getStatus()); map.put("order_id", log.getOrderId()); map.put("openid", log.getOpenid()); map.put("paid", log.getPaid()); map.put("pay_time", log.getPayTime() != null ? sdf.format(log.getPayTime()) : null); map.put("time", log.getTime()); map.put("created_at", log.getCreatedAt() != null ? sdf.format(log.getCreatedAt()) : null); map.put("updated_at", log.getUpdatedAt() != null ? sdf.format(log.getUpdatedAt()) : null); resultList.add(map); } // 5. 构建分页响应结构 String baseUrl = "https://www.huafurenjia.cn/api/worker/withdraw_log"; Map dataPage = AppletControllerUtil.buildPageResult(pageInfo, resultList, baseUrl); return AjaxResult.success(dataPage); } catch (Exception e) { return AppletControllerUtil.appletError("查询提现记录失败:" + e.getMessage()); } } /** * 师傅设置出发上门 * GET /api/worker/start/door/{id} * 逻辑参考OrderController的edit接口中jsonStatus=4的流程 */ @GetMapping("/api/cuidan/{id}") public AjaxResult workercuidanDoor(@PathVariable("id") Long id, HttpServletRequest request) throws Exception { // 1. 获取当前登录师傅ID(token在header) String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletWarning("未登录或token无效"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletWarning("用户信息获取失败"); } Long workerId = user.getId(); // 2. 获取订单 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } Users usersworker = usersService.selectUsersById(order.getWorkerId()); if (usersworker != null) { WXsendMsgUtil.sendMsgForWorkerCuiDanInfo(usersworker.getOpenid(), order, "订单催单","用户催师傅快点服务"); } return AppletControllerUtil.appletSuccess("催单成功"); } /** * 师傅设置出发上门 * GET /api/worker/start/door/{id} * 逻辑参考OrderController的edit接口中jsonStatus=4的流程 */ @GetMapping("/api/worker/start/door/{id}") public AjaxResult workerStartDoor(@PathVariable("id") Long id, HttpServletRequest request) throws Exception { // 1. 获取当前登录师傅ID(token在header) String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletWarning("未登录或token无效"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletWarning("用户信息获取失败"); } Long workerId = user.getId(); // 2. 获取订单 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } if (!workerId.equals(order.getWorkerId())) { return AppletControllerUtil.appletWarning("您不是该订单的师傅"); } // if (order.getStatus() == null || order.getStatus() != 2L) { // return AppletControllerUtil.appletWarning("订单状态不正确"); // } // if (order.getJsonStatus() == null || order.getJsonStatus() != 3) { // return AppletControllerUtil.appletWarning("订单进度不正确"); // } order.setJsonStatus(4); // 出发上门 JSONObject typeJson = new JSONObject(); typeJson.put("type", 3); order.setLogJson(typeJson.toJSONString()); // 5. 保存 orderService.updateOrder(order); // 4. 写订单日志 OrderLog orderLog = new OrderLog(); orderLog.setOid(order.getId()); orderLog.setOrderId(order.getOrderId()); orderLog.setWorkerId(workerId); orderLog.setWorkerLogId(workerId); orderLog.setTitle("出发上门"); JSONObject typeJson1 = new JSONObject(); typeJson1.put("name", "师傅收到派单信息准备出发"); orderLog.setType(new BigDecimal("3.0")); orderLog.setContent(typeJson1.toJSONString()); orderLogService.insertOrderLog(orderLog); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); //小程序推送给用户师傅已经出发 WXsendMsgUtil.sendStartDoorMoney(user.getOpenid(), order, serviceGoods); return AppletControllerUtil.appletSuccess("出发上门成功"); } /** * 师傅确认到达(新版,校验手机号后两位) * POST /api/worker/confirm/door * 参数:{id: 订单id, phone_two: 用户手机号后两位} */ @PostMapping("/api/worker/confirm/door") public AjaxResult workerConfirmDoor(@RequestBody Map params, HttpServletRequest request) throws Exception { // 1. 获取参数 if (params == null || !params.containsKey("id") || !params.containsKey("phone_two")) { return AppletControllerUtil.appletWarning("参数不完整"); } Long id; try { id = Long.valueOf(params.get("id").toString()); } catch (Exception e) { return AppletControllerUtil.appletWarning("订单ID格式错误"); } String phoneTwo = params.get("phone_two").toString(); if (phoneTwo.length() != 2) { return AppletControllerUtil.appletWarning("请输入手机号后两位"); } String latitude = params.get("latitude").toString(); String longitude = params.get("longitude").toString(); String addressName = params.get("addressName").toString(); // 2. 获取当前登录师傅ID(token在header) String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletWarning("未登录或token无效"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletWarning("用户信息获取失败"); } Long workerId = user.getId(); // 3. 获取订单 Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } if (!workerId.equals(order.getWorkerId())) { return AppletControllerUtil.appletWarning("您不是该订单的师傅"); } // 校验用户手机号后两位 String userPhone = order.getPhone(); if (userPhone == null || userPhone.length() < 2) { return AppletControllerUtil.appletWarning("用户手机号无效"); } String lastTwo = userPhone.substring(userPhone.length() - 2); if (!phoneTwo.equals(lastTwo)) { return AppletControllerUtil.appletWarning("手机号后两位不正确"); } //解绑订单虚拟号 //需要解绑原订单上原师傅和客户的虚拟号 VoiceResponseResult resultObj = YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone(), order.getId()); System.out.println("----------------------------------"+resultObj.getResult()); System.out.println("----------------------------------"+resultObj.getResult()); if (resultObj.getResult().equals("000000")) { // order.setWorkerPhone(null); // order.setUserPhone(null); // order.setMiddlePhone(null); // orderService.updateOrder(order); orderService.updateOrderPhone(order.getId()); } // 4. 更新订单状态 order.setJsonStatus(5); // 确认到达 JSONObject typeJson = new JSONObject(); typeJson.put("type", 4); order.setLogJson(typeJson.toJSONString()); // 6. 保存 orderService.updateOrder(order); // 5. 写订单日志 //一口价直接开始服务,没有报价的环节 if (order.getOdertype()!= 0){ OrderLog orderLog = new OrderLog(); orderLog.setOid(order.getId()); orderLog.setOrderId(order.getOrderId()); orderLog.setWorkerId(workerId); orderLog.setLatitude(latitude); orderLog.setLongitude(longitude); orderLog.setAddressName(addressName); orderLog.setWorkerLogId(workerId); orderLog.setTitle("师傅到达"); orderLog.setType(new BigDecimal("5.0")); JSONObject content = new JSONObject(); content.put("name", "师傅到达服务地点,开始服务工作"); orderLog.setContent(content.toJSONString()); // 6. 保存 orderLogService.insertOrderLog(orderLog); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); // WXsendMsgUtil.sendMsgForWorkerInfo(user.getOpenid(), order, serviceGoods); return AppletControllerUtil.appletSuccess("师傅已经上门"); } OrderLog orderLog = new OrderLog(); orderLog.setOid(order.getId()); orderLog.setOrderId(order.getOrderId()); orderLog.setWorkerId(workerId); orderLog.setWorkerLogId(workerId); orderLog.setTitle("师傅到达"); orderLog.setType(new BigDecimal("4.0")); JSONObject content = new JSONObject(); content.put("name", "师傅到达服务地点"); orderLog.setContent(content.toJSONString()); // 6. 保存 orderLogService.insertOrderLog(orderLog); //解绑号码 YunXinPhoneUtilAPI.httpsPrivacyUnbind(order.getWorkerPhone(), order.getUserPhone(), order.getMiddlePhone(), order.getId()); // 小程序推送给用户师傅已经到达 ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); //师傅到达的时候给客户的微信推送 WXsendMsgUtil.sendWorkerIsComing(user.getOpenid(), order, serviceGoods); return AppletControllerUtil.appletSuccess("师傅已经上门"); } // ... existing code ... /** * 获取基检项目和订单报价信息 * GET /api/worker/basic/project?id=订单id&goodid=服务id */ @GetMapping("/api/worker/basic/project") public AjaxResult getWorkerBasicProject(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "goodid", required = false) Long goodid) { List basicList = new ArrayList<>(); Map data = new HashMap<>(); Object quoteJson = null; // 1. 如果订单id不为空,查订单和报价日志 if (id != null) { Order order = orderService.selectOrderById(id); if (order != null) { // 查 type=5.0 的订单日志 OrderLog logQuery = new OrderLog(); logQuery.setOid(order.getId()); logQuery.setType(new BigDecimal("5.0")); List logs = orderLogService.selectOrderLogList(logQuery); if (logs != null && !logs.isEmpty()) { String content = logs.getFirst().getContent(); try { quoteJson = JSON.parse(content); } catch (Exception e) { quoteJson = content; } } // 取服务id if (order.getProductId() != null) { goodid = order.getProductId(); } } } // 2. 查服务信息 if (goodid != null) { ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodid); if (serviceGoods != null) { String basic = serviceGoods.getBasic(); if (basic != null && !basic.trim().isEmpty()) { try { JSONArray jsonArray = JSONArray.parse(basic); for (int i = 0; i < jsonArray.size(); i++) { String item = jsonArray.getString(i); if (item != null && !item.trim().isEmpty()) { basicList.add(item.trim()); } } } catch (Exception e) { String[] arr = basic.split("[\n,,]"); for (String s : arr) { if (!s.trim().isEmpty()) basicList.add(s.trim()); } } } } } //查询报价的支付信息 if (id != null) { Order order = orderService.selectOrderById(id); if (order != null) { // 查 type=5.0 的订单日志 OrderLog logQuery = new OrderLog(); logQuery.setOid(order.getId()); logQuery.setType(new BigDecimal("5.0")); List logs = orderLogService.selectOrderLogList(logQuery); if (logs != null && !logs.isEmpty()) { OrderLog logdata = logs.getFirst(); if (logdata != null) { Map paydata = new HashMap<>(); paydata.put("weikuan", logdata.getPaid()); paydata.put("dingjin", logdata.getDepPaid()); data.put("payStatusdata", paydata); } } } }else{ Map paydata = new HashMap<>(); paydata.put("weikuan", "1"); paydata.put("dingjin", "1"); data.put("payStatusdata", paydata); } data.put("basic", basicList); if (quoteJson != null) { data.put("quote", quoteJson); } return AjaxResult.success(data); } // ... existing code ... /** * 获取基检项目 * GET /api/worker/basic/project/{id} */ @GetMapping("/api/worker/basic/project/{id}") public AjaxResult getWorkerBasicProject(@PathVariable("id") Long id) { ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(id); if (serviceGoods == null) { return AppletControllerUtil.appletError("商品不存在"); } Order order = orderService.selectOrderById(id); if (order != null) { return AppletControllerUtil.appletError("订单不存在"); } String basic = serviceGoods.getBasic(); List basicList = new ArrayList<>(); if (basic != null && !basic.trim().isEmpty()) { try { JSONArray jsonArray = JSONArray.parseArray(basic); for (int i = 0; i < jsonArray.size(); i++) { String item = jsonArray.getString(i); if (item != null && !item.trim().isEmpty()) { basicList.add(item.trim()); } } } catch (Exception e) { String[] arr = basic.split("[\n,,]"); for (String s : arr) { if (!s.trim().isEmpty()) basicList.add(s.trim()); } } } Map data = new HashMap<>(); data.put("basic", basicList); return AjaxResult.success(data); } /** * 报价获取服务项目 */ @GetMapping("/api/worker/quote/craft/{goodsId}") public Object getWorkerQuoteCraft(@PathVariable("goodsId") Long goodsId) { // 1. 查询商品基本信息 ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsId); if (serviceGoods == null) { return AppletControllerUtil.appletError("商品不存在"); } // 2. 查询服务分类(IQuoteTypeService) QuoteType typeQuery = new QuoteType(); typeQuery.setGoodId("\"" + goodsId + "\""); List typeList = quoteTypeService.selectQuoteTypeList(typeQuery); List dataArr = new ArrayList<>(); for (QuoteType type : typeList) { Map typeMap = new HashMap<>(); typeMap.put("id", type.getId()); typeMap.put("title", type.getTitle()); // 3. 查询工艺(IQuoteCraftService) QuoteCraft craftQuery = new QuoteCraft(); craftQuery.setTypeId("[\"" + type.getId() + "\"]"); List craftList = quoteCraftService.selectQuoteCraftList(craftQuery); List> craftArr = new ArrayList<>(); for (QuoteCraft craft : craftList) { Map craftMap = new HashMap<>(); craftMap.put("id", craft.getId()); craftMap.put("title", craft.getTitle()); craftMap.put("price", craft.getPrice() != null ? craft.getPrice().toString() : "0.00"); craftMap.put("unit", craft.getUnit()); // type_id为数组,需解析 List typeIdList = new ArrayList<>(); String typeIdStr = craft.getTypeId(); if (typeIdStr != null && typeIdStr.trim().startsWith("[") && typeIdStr.trim().endsWith("]")) { try { typeIdList = JSON.parseArray(typeIdStr, String.class); } catch (Exception e) { typeIdList.add(typeIdStr); } } else if (typeIdStr != null) { typeIdList.add(typeIdStr); } craftMap.put("type_id", typeIdList); craftArr.add(craftMap); } typeMap.put("craft", craftArr); dataArr.add(typeMap); } Map result = new HashMap<>(); result.put("data", dataArr); result.put("code", 200); result.put("msg", "OK"); return result; } /** * 报价所需物料查询 * GET /api/worker/quote/material/{goodsId} */ @GetMapping("/api/worker/quote/material/{goodsId}") public Object getWorkerQuoteMaterial(@PathVariable("goodsId") Long goodsId) { // 1. 查询商品基本信息 ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsId); if (serviceGoods == null) { return AppletControllerUtil.appletError("商品不存在"); } // 2. 查询物料分类(IQuoteMaterialTypeService) QuoteMaterialType typeQuery = new QuoteMaterialType(); typeQuery.setGoodId("\"" + goodsId + "\""); List typeList = quoteMaterialTypeService.selectQuoteMaterialTypeList(typeQuery); List dataArr = new ArrayList<>(); for (QuoteMaterialType type : typeList) { Map typeMap = new HashMap<>(); typeMap.put("id", type.getId()); typeMap.put("title", type.getTitle()); // 3. 查询物料信息(IQuoteMaterialService) QuoteMaterial materialQuery = new QuoteMaterial(); materialQuery.setTypeId("\"" + type.getId() + "\""); List materialList = quoteMaterialService.selectQuoteMaterialList(materialQuery); List> materialArr = new ArrayList<>(); for (QuoteMaterial material : materialList) { Map materialMap = new HashMap<>(); materialMap.put("id", material.getId()); materialMap.put("title", material.getTitle()); materialMap.put("image",AppletControllerUtil.buildImageUrl(material.getImage())); materialMap.put("price", material.getPrice() != null ? material.getPrice().toString() : "0.00"); materialMap.put("unit", material.getUnit()); // 格式化manyimages为数组 if (material.getManyimages() != null && !material.getManyimages().trim().isEmpty()) { materialMap.put("manyimages", JSONArray.parseArray(material.getManyimages())); } else { materialMap.put("manyimages", new JSONArray()); } if (org.apache.commons.lang3.StringUtils.isNotBlank(material.getContent())&& org.apache.commons.lang3.StringUtils.isNotBlank(material.getManyimages())){ materialMap.put("showtype", 1); }else{ materialMap.put("showtype", 2); } materialMap.put("content", material.getContent()); // type_id为数组,需解析 List typeIdList = new ArrayList<>(); String typeIdStr = material.getTypeId(); if (typeIdStr != null && typeIdStr.trim().startsWith("[") && typeIdStr.trim().endsWith("]")) { try { typeIdList = JSON.parseArray(typeIdStr, String.class); } catch (Exception e) { typeIdList.add(typeIdStr); } } else if (typeIdStr != null) { typeIdList.add(typeIdStr); } materialMap.put("type_id", typeIdList); materialArr.add(materialMap); } typeMap.put("material", materialArr); dataArr.add(typeMap); } Map result = new HashMap<>(); result.put("data", dataArr); result.put("code", 200); result.put("msg", "OK"); return result; } /** * 师傅报价接口 * POST /api/worker/estimate */ @PostMapping("/api/worker/estimate") public AjaxResult workerEstimate(@RequestBody Map params, HttpServletRequest request) throws Exception { if (params == null) { return AppletControllerUtil.appletError("参数错误"); } PayBeforeUtil payBeforeUtil = new PayBeforeUtil(); // 1. 计算金额 BigDecimal GoodsAllPrice = BigDecimal.ZERO; BigDecimal ServiceAllPrice = BigDecimal.ZERO; BigDecimal totalPrice = BigDecimal.ZERO; List> craftList = (List>) params.get("craft"); if (craftList != null) { for (Map craft : craftList) { Long craftId = null; try { craftId = Long.valueOf(craft.get("id").toString()); } catch (Exception ignore) { } if (craftId != null) { QuoteCraft quoteCraft = quoteCraftService.selectQuoteCraftById(craftId); if (quoteCraft != null) { BigDecimal price = new BigDecimal(craft.get("price").toString()); Integer count = craft.get("count") == null ? 1 : Integer.parseInt(craft.get("count").toString()); totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(count))); ServiceAllPrice = ServiceAllPrice.add(price.multiply(BigDecimal.valueOf(count))); } } } } List> materialList = (List>) params.get("material"); if (materialList != null) { for (Map material : materialList) { Long materialId = null; try { materialId = Long.valueOf(material.get("id").toString()); } catch (Exception ignore) { } if (materialId != null) { QuoteMaterial quoteMaterial = quoteMaterialService.selectQuoteMaterialById(materialId); if (quoteMaterial != null) { BigDecimal price = new BigDecimal(material.get("price").toString()); Integer count = material.get("count") == null ? 1 : Integer.parseInt(material.get("count").toString()); totalPrice = totalPrice.add(price.multiply(BigDecimal.valueOf(count))); GoodsAllPrice = GoodsAllPrice.add(price.multiply(BigDecimal.valueOf(count))); } } } } BigDecimal reductionPrice = BigDecimal.ZERO; String reduction = params.get("reduction").toString(); String reamk = null; if (params.get("reamk") != null){ reamk =params.get("reamk").toString(); } if (reduction != null && !reduction.trim().isEmpty()) { reductionPrice = new BigDecimal(reduction); // totalPrice = totalPrice.subtract(reductionPrice); totalPrice = totalPrice; } // 2. 组装新json Map resultJson = new LinkedHashMap<>(); // project Map project = new LinkedHashMap<>(); project.put("name", "项目费用"); project.put("price", totalPrice); resultJson.put("project", project); Map reductionproject = new LinkedHashMap<>(); reductionproject.put("name", "优惠金额"); reductionproject.put("price", params.get("reduction")); resultJson.put("reduction", reductionproject); Map depositproject = new LinkedHashMap<>(); depositproject.put("name", "定金"); depositproject.put("price", params.get("price")); resultJson.put("deposit", depositproject); // basic resultJson.put("basic", params.get("basic")); if (StringUtils.isNotBlank(reamk)){ resultJson.put("reamk", reamk); } // craft List> craftListNew = new ArrayList<>(); if (craftList != null) { for (Map craft : craftList) { Map item = new LinkedHashMap<>(); item.put("name", craft.get("title") != null ? craft.get("title") : craft.get("name")); item.put("price", craft.get("price")); item.put("pid", craft.get("pid")); item.put("id", craft.get("id")); item.put("count", craft.get("count")); craftListNew.add(item); } } resultJson.put("craft", craftListNew); // material List> materialListNew = new ArrayList<>(); if (materialList != null) { for (Map material : materialList) { Map item = new LinkedHashMap<>(); item.put("name", material.get("title") != null ? material.get("title") : material.get("name")); item.put("price", material.get("price")); item.put("id", material.get("id")); item.put("pid", material.get("pid")); item.put("count", material.get("count")); materialListNew.add(item); } } resultJson.put("material", materialListNew); // 3. 转为字符串 String contentStr = JSONObject.toJSONString(resultJson); // 4. 订单相关处理 Long orderId = null; if (params.get("id") != null) { try { orderId = Long.valueOf(params.get("id").toString()); } catch (Exception ignore) { } } if (orderId == null) { return AppletControllerUtil.appletError("订单ID格式错误"); } Order order = orderService.selectOrderById(orderId); if (order == null) { return AppletControllerUtil.appletError("订单不存在"); } // 查询最新订单日志 OrderLog neworderLogdata =new OrderLog(); neworderLogdata.setType(new BigDecimal(5.0)); neworderLogdata.setOid(order.getId()); List orderLogslist = orderLogService.selectOrderLogList(neworderLogdata); if(!orderLogslist.isEmpty()){ OrderLog neworderLog=orderLogslist.getFirst(); neworderLog.setContent(contentStr); if (params.get("price") != null) { //String DepLogId = GenerateCustomCode.generCreateOrder("LOG"); neworderLog.setDeposit(new BigDecimal(params.get("price").toString())); neworderLog.setDepPaid(1); // neworderLog.setDepLogId(DepLogId); //给尾款添加预支 // BigDecimal totalAmount=neworderLog.getDeposit(); // PayBeforeUtil payBeforeUtil = new PayBeforeUtil(); // payBeforeUtil.createPayBefore(userinfo, totalAmount, DepLogId, neworderLog.getId(), // null, 7L, null, null, // null, null, null,1L,null); //// payBeforeUtil.createPayBefore(user, totalPrice.add(reductionPrice), order.getOrderId(), order.getId(),); }else { neworderLog.setDeposit(BigDecimal.ZERO); } // neworderLog.setPrice(totalPrice.add(reductionPrice)); neworderLog.setPaid(1L); if (params.get("reduction") != null) { neworderLog.setReductionPrice(new BigDecimal(params.get("reduction").toString())); } else { neworderLog.setReductionPrice(BigDecimal.ZERO); } System.out.println("neworderLog.getPrice():totalPrice"+totalPrice); System.out.println("neworderLog.getPrice():reductionPrice"+reductionPrice); System.out.println("neworderLog.getPrice():neworderLog.getDeposit()"+neworderLog.getDeposit()); BigDecimal WK=totalPrice.subtract(reductionPrice).subtract(neworderLog.getDeposit()); System.out.println("neworderLog.getPrice():neworderLog.getDeposit()WKWKWK"+WK); if(WK.compareTo(BigDecimal.ZERO)>0){ System.out.println("111neworderLog.getPrice():neworderLog.getDeposit()WKWKWK"+WK); neworderLog.setPrice(WK); }else{ neworderLog.setPrice(BigDecimal.ZERO); } // if (params.get("reduction") != null) { // neworderLog.setReductionPrice(new BigDecimal(params.get("reduction").toString())); // } else { // neworderLog.setReductionPrice(BigDecimal.ZERO); // } neworderLog.setWorkerCost(BigDecimal.ZERO); //log.set neworderLog.setLogId(GenerateCustomCode.generCreateOrder("EST")); //删除之前的预支付信息 UsersPayBefor payBefore = new UsersPayBefor(); payBefore.setOrderid(neworderLog.getDepLogId()); List payBeforeList = usersPayBeforService.selectUsersPayBeforList(payBefore); if(!payBeforeList.isEmpty()){ for (UsersPayBefor payBefore1 : payBeforeList) { usersPayBeforService.deleteUsersPayBeforById(payBefore1.getId()); } } //删除之前的预支付信息 UsersPayBefor payBefore3 = new UsersPayBefor(); payBefore3.setOrderid(neworderLog.getLogOrderId()); payBefore3.setType(9L); List payBeforeList3 = usersPayBeforService.selectUsersPayBeforList(payBefore3); if(!payBeforeList3.isEmpty()){ for (UsersPayBefor payBefore4 : payBeforeList3) { usersPayBeforService.deleteUsersPayBeforById(payBefore4.getId()); } } Users userinfo = usersService.selectUsersById(order.getUid()); payBeforeUtil.handleQuotationPayBefore(userinfo, neworderLog, contentStr, order.getOrderId()); int flg= orderLogService.updateOrderLog(neworderLog); if (flg > 0) { order.setGoodPrice(GoodsAllPrice); order.setServicePrice(ServiceAllPrice); orderService.updateOrder(order); } //小程序推送报价成功 Users user = usersService.selectUsersById(order.getUid()); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); WXsendMsgUtil.sendWorkerADDmoney(user.getOpenid(), order, serviceGoods); return AppletControllerUtil.appletSuccess("报价成功"); }else{ order.setJsonStatus(6); JSONObject jsonObject = new JSONObject(); jsonObject.put("type", 5); order.setLogJson(jsonObject.toJSONString()); // order.setTotalPrice(totalPrice); // order.setUpdatedAt(new Date()); order.setGoodPrice(GoodsAllPrice); order.setServicePrice(ServiceAllPrice); int update = orderService.updateOrder(order); if (update > 0) { OrderLog log = new OrderLog(); log.setOid(order.getId()); log.setLogOrderId(GenerateCustomCode.generCreateOrder("DSB") ); log.setOrderId(order.getOrderId()); log.setType(new BigDecimal(5)); log.setContent(contentStr); log.setTitle("已检查评估报价"); if (params.get("price") != null) { log.setDeposit(new BigDecimal(params.get("price").toString())); log.setDepPaid(1); log.setDepLogId(GenerateCustomCode.generCreateOrder("RED")); }else { log.setDeposit(BigDecimal.ZERO); } BigDecimal WK=totalPrice.subtract(reductionPrice).subtract(log.getDeposit()); if(WK.compareTo(BigDecimal.ZERO)>0){ log.setPrice(WK); }else{ log.setPrice(BigDecimal.ZERO); } // log.setPrice(totalPrice.add(reductionPrice)); log.setPaid(1L); if (params.get("reduction") != null) { log.setReductionPrice(new BigDecimal(params.get("reduction").toString())); } else { log.setReductionPrice(BigDecimal.ZERO); } //log.setPrice(ServiceAllPrice.subtract(reductionPrice)); //log.set log.setLogId(GenerateCustomCode.generCreateOrder("EST")); log.setWorkerLogId(order.getWorkerId()); log.setWorkerId(order.getWorkerId()); int flg=orderLogService.insertOrderLog(log); if (flg > 0) { order.setGoodPrice(GoodsAllPrice); order.setServicePrice(ServiceAllPrice); orderService.updateOrder(order); } Users user = usersService.selectUsersById(order.getUid()); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); //小程序推送用户报价成功 WXsendMsgUtil.sendWorkerADDmoney(user.getOpenid(), order, serviceGoods); Users userinfo = usersService.selectUsersById(order.getUid()); payBeforeUtil.handleQuotationPayBefore(userinfo, log, contentStr, order.getOrderId()); return AppletControllerUtil.appletSuccess("报价成功"); } else { return AppletControllerUtil.appletError("报价失败"); } } } /** * 师傅开始服务接口 * POST /api/worker/do/service * 参数:{"oid":订单id,"image":[图片url数组]} */ @PostMapping("/api/worker/do/service") public AjaxResult workerDoService(@RequestBody Map params, HttpServletRequest request) { Long oid = 0L; if (params.get("id") != null) { try { oid = Long.valueOf(params.get("id").toString()); } catch (Exception e) { return AppletControllerUtil.appletError("订单ID格式错误"); } } Order order = orderService.selectOrderById(oid); if (order == null) { return AppletControllerUtil.appletError("订单不存在"); } OrderLog newlogdata =new OrderLog(); newlogdata.setType(new BigDecimal("6.0")); newlogdata.setOid(order.getId()); //如果没有进行服务的记录就是开启服务 List logList = orderLogService.selectOrderLogList(newlogdata); if (logList.isEmpty()){ // 2. 组装日志内容为数组格式 Map logItem = new LinkedHashMap<>(); logItem.put("name", "师傅开始服务"); logItem.put("image", params.get("image")); logItem.put("type", 1); List logArr = new ArrayList<>(); logArr.add(logItem); String contentStr = JSONObject.toJSONString(logArr); // 3. 写入订单日志 OrderLog log = new OrderLog(); log.setOid(order.getId()); log.setOrderId(order.getOrderId()); log.setTitle("开始服务"); log.setType(new BigDecimal(6.0)); log.setContent(contentStr); log.setWorkerId(order.getWorkerId()); log.setWorkerLogId(order.getWorkerId()); log.setIsPause(1); log.setCreatedAt(new Date()); orderLogService.insertOrderLog(log); //开始服务 // 1. 修改订单状态 order.setStatus(3L); // 服务中 order.setJsonStatus(7); // 服务中 order.setLogJson("{\"type\":6}"); order.setIsPause(1); // 服务中 order.setUpdatedAt(new Date()); int update = orderService.updateOrder(order); return AppletControllerUtil.appletSuccess("服务已开始"); }else{ if (order.getJsonStatus() == 7) { JSONObject logItem = new JSONObject(); logItem.put("name", "暂停服务"); logItem.put("image", params.get("image")); logItem.put("reson", params.get("reson")); logItem.put("next_time", params.get("next_time")); logItem.put("time", new Date()); logItem.put("type", 2); OrderLog newlogdata1 =new OrderLog(); newlogdata1.setOid(order.getId()); newlogdata1.setOrderId(order.getOrderId()); newlogdata1.setTitle("暂停服务"); newlogdata1.setIsPause(2); newlogdata1.setContent(logItem.toJSONString()); newlogdata1.setType(new BigDecimal(6.0)); newlogdata1.setWorkerId(order.getWorkerId()); newlogdata1.setWorkerLogId(order.getWorkerId()); orderLogService.insertOrderLog(newlogdata1); if (order != null) { // 1. 修改订单状态 order.setStatus(3L); // 服务中 order.setJsonStatus(8); // 服务中 order.setLogJson("{\"type\":6}"); order.setIsPause(2); // 服务中 order.setUpdatedAt(new Date()); orderService.updateOrder(order); } return AppletControllerUtil.appletSuccess("操作成功"); } if (order.getJsonStatus() == 8) { JSONObject logItem = new JSONObject(); logItem.put("name", "继续服务"); logItem.put("image", params.get("image")); logItem.put("time", new Date()); logItem.put("type", 1); OrderLog newlogdata2 =new OrderLog(); newlogdata2.setOid(order.getId()); newlogdata2.setOrderId(order.getOrderId()); newlogdata2.setTitle("继续服务"); newlogdata2.setIsPause(1); newlogdata2.setType(new BigDecimal(6.0)); newlogdata2.setWorkerId(order.getWorkerId()); newlogdata2.setWorkerLogId(order.getWorkerId()); newlogdata2.setContent(logItem.toJSONString()); orderLogService.insertOrderLog(newlogdata2); if (order != null) { //继续服务 order.setStatus(3L); // 服务中 order.setJsonStatus(7); // 服务中 order.setLogJson("{\"type\":6}"); order.setIsPause(1); // 服务中 order.setUpdatedAt(new Date()); orderService.updateOrder(order); } return AppletControllerUtil.appletSuccess("操作成功"); } } return AppletControllerUtil.appletSuccess("操作成功"); } /** * 师傅完成订单接口 * POST /api/worker/finish/service * 参数:{"id":订单id,"image":[图片url数组]} */ @PostMapping("/api/worker/finish/service") public AjaxResult workerFinishService(@RequestBody Map params, HttpServletRequest request) throws Exception { if (params == null || params.get("id") == null) { return AppletControllerUtil.appletError("参数错误"); } Long id; try { id = Long.valueOf(params.get("id").toString()); } catch (Exception e) { return AppletControllerUtil.appletError("订单ID格式错误"); } Order order = orderService.selectOrderById(id); if (order == null) { return AppletControllerUtil.appletError("订单不存在"); } String reamk = params.get("reamk").toString(); String latitude = params.get("latitude").toString(); String longitude = params.get("longitude").toString(); String addressName = params.get("addressName").toString(); PayBeforeUtil payBeforeUtil = new PayBeforeUtil(); String priceDifferenceprice= params.get("priceDifferenceprice").toString(); // int paynum=usersPayBeforService.countByLastOrderIdAndStatus(order.getOrderId()); // //如果订单没有支付 // if (paynum<=0){ // // 1. 修改订单状态 // order.setStatus(6L); // 完成 // order.setReceiveType(3L); // 完成类型 // order.setJsonStatus(9); // 完成 // order.setLogJson("{\"type\":8}"); // int update = orderService.updateOrder(order); // } // 2. 组装日志内容 Map logContent = new LinkedHashMap<>(); if (StringUtils.isNotBlank(reamk)) { logContent.put("name","师傅服务完成--"+ reamk); }else{ logContent.put("name", "师傅服务完成"); } logContent.put("image", params.get("image")); String contentStr = com.alibaba.fastjson2.JSONObject.toJSONString(logContent); // 3. 写入订单日志 OrderLog log = new OrderLog(); log.setOid(order.getId()); log.setOrderId(order.getOrderId()); log.setLogOrderId(GenerateCustomCode.generCreateOrder("DSB")); log.setTitle("服务完成"); log.setLatitude(latitude); log.setLongitude(longitude); log.setAddressName(addressName); log.setType(new java.math.BigDecimal(7)); log.setContent(contentStr); log.setWorkerId(order.getWorkerId()); log.setCreatedAt(new Date()); if (StringUtils.isNotBlank(priceDifferenceprice)) { log.setCjMoney(new BigDecimal(priceDifferenceprice)); log.setCjPaid(1L); } orderLogService.insertOrderLog(log); //如果有补差价,就要插入日志中进行处理 if (StringUtils.isNotBlank(priceDifferenceprice)) { log.setCjMoney(new BigDecimal(priceDifferenceprice)); log.setCjPaid(1L); Users userinfo = usersService.selectUsersById(order.getUid()); payBeforeUtil.createPayBefore(userinfo, log.getCjMoney(), log.getLogOrderId(), log.getId(), null, 10L, null, null, null, null, null,1L,null,order.getOrderId(), null); } //判断这个订单还有没有未支付的数据,如果有就停留在服务中如果没有就直接去到状态为4的已完成状态 int paynum=usersPayBeforService.countByLastOrderIdAndStatus(order.getOrderId()); //如果订单没有支付,订单完成,分佣,推送 if (paynum<=0){ //师傅完成时,确认没有可支付的信息,就可以分佣,让这个订单结束 OrderUtil.ISTOPAYSIZE(order.getOrderId()); order.setStatus(4L); // 完成 order.setReceiveType(3L); // 完成类型 order.setJsonStatus(9); // 完成 order.setLogJson("{\"type\":8}"); int update = orderService.updateOrder(order); Users wusers = usersService.selectUsersById(order.getWorkerId()); WorkerCommissionUtil.processWorkerCommission(order,wusers); Users users = usersService.selectUsersById(order.getUid()); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); WXsendMsgUtil.sendWorkerFinishOrder(users.getOpenid(), order, serviceGoods); }else{ order.setStatus(6L); // 完成 order.setJsonStatus(9); // 完成 int update = orderService.updateOrder(order); } return AppletControllerUtil.appletSuccess("服务已完成"); } /** * 师傅设置上门费接口 * 参数:{"id":订单id,"price":金额} * 逻辑:查找订单最新日志,设置workerCost和price,并设置paid=1 */ @PostMapping("/api/worker/set/price") public AjaxResult setWorkerPrice(@RequestBody Map params, HttpServletRequest request) { try { // 1. 校验token并获取用户 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } Long orderId = params.get("id") != null ? Long.parseLong(params.get("id").toString()) : null; String priceStr = params.get("price") != null ? params.get("price").toString() : null; if (orderId == null || StringUtils.isEmpty(priceStr)) { return AppletControllerUtil.appletWarning("参数错误"); } BigDecimal price = new BigDecimal(priceStr); // 查询订单 Order order = orderService.selectOrderById(orderId); if (order == null) { return AppletControllerUtil.appletWarning("订单不存在"); } // 查询最新订单日志 OrderLog neworderLogdata =orderLogService.selectDataTheFirstNew(order.getId()); // neworderLogdata.setType(new BigDecimal(2.0)); // neworderLogdata.setOid(order.getId()); // List orderLogslist = orderLogService.selectOrderLogList(neworderLogdata); // OrderLog neworderLog = orderLogslist.getFirst(); if (neworderLogdata != null) { String logOrderId = GenerateCustomCode.generCreateOrder("DSB"); OrderLog neworderLog =new OrderLog(); neworderLog.setOid(order.getId()); neworderLog.setOrderId(order.getOrderId()); neworderLog.setLogOrderId(logOrderId); neworderLog.setTitle("上门费"); neworderLog.setType(neworderLogdata.getType()); JSONObject jsonObject = new JSONObject(); jsonObject.put("name", "师傅"+user.getName()+"设置上门费"+ price+"元"); neworderLog.setContent(jsonObject.toJSONString()); neworderLog.setPaid(1L); neworderLog.setPrice( price); neworderLog.setLogId(GenerateCustomCode.generCreateOrder("FEE")); neworderLog.setWorkerId(user.getId()); neworderLog.setWorkerCost( price); neworderLog.setWorkerLogId(user.getId()); int insert =orderLogService.insertOrderLog(neworderLog); if (insert > 0) { //上门费创建支付单 BigDecimal totalAmount=neworderLog.getPrice(); Users userinfo = usersService.selectUsersById(order.getUid()); PayBeforeUtil payBeforeUtil = new PayBeforeUtil(); payBeforeUtil.createPayBefore(userinfo, totalAmount, logOrderId, neworderLog.getId(), null, 7L, null, null, null, null, null,1L,null,order.getOrderId(), null); // // 9. 计算会员优惠和服务金抵扣 // BigDecimal memberMoney = BigDecimal.ZERO; // BigDecimal serviceMoney = BigDecimal.ZERO; // // try { // // 查询config_one配置 // SiteConfig configQuery = new SiteConfig(); // configQuery.setName("config_one"); // List configList = siteConfigService.selectSiteConfigList(configQuery); // // if (configList != null && !configList.isEmpty()) { // String configValue = configList.get(0).getValue(); // if (configValue != null && !configValue.trim().isEmpty()) { // JSONObject configJson = JSONObject.parseObject(configValue); // // // 计算会员优惠金额 // if (user.getIsmember() != null && user.getIsmember() == 1) { // // 用户是包年会员,计算会员优惠 // Integer memberDiscount = configJson.getInteger("member_discount"); // if (memberDiscount != null && memberDiscount > 0) { // // 会员优惠金额 = 订单金额 * (100 - 会员折扣) / 100 // BigDecimal discountRate = BigDecimal.valueOf(memberDiscount).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP); // if (totalAmount != null) { // memberMoney = totalAmount.multiply(discountRate); // } // } // } // // // 计算服务金抵扣金额 // Integer serviceFee = configJson.getInteger("servicefee"); // if (serviceFee != null && serviceFee > 0) { // // 查询数据库最新用户数据 // Users userDb = usersService.selectUsersById(user.getId()); // if (userDb != null && userDb.getServicefee() != null && userDb.getServicefee().compareTo(BigDecimal.ZERO) > 0) { // // 服务金抵扣金额 = 用户服务金 * 服务金比例 / 100 // BigDecimal serviceRate = BigDecimal.valueOf(serviceFee).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP); // serviceMoney = userDb.getServicefee().multiply(serviceRate); // } // } // } // } // } catch (Exception e) { // logger.warn("计算会员优惠和服务金抵扣失败: " + e.getMessage()); // memberMoney = BigDecimal.ZERO; // serviceMoney = BigDecimal.ZERO; // } // // // 10. 创建预支付记录 // UsersPayBefor usersPayBefor = new UsersPayBefor(); // usersPayBefor.setUid(userinfo.getId()); // usersPayBefor.setOrderid(logOrderId); // usersPayBefor.setOid(neworderLog.getId()); // usersPayBefor.setPaycode(GenerateCustomCode.generCreateOrder("PAY")); // usersPayBefor.setAllmoney(totalAmount); // usersPayBefor.setWxmoney(totalAmount); // usersPayBefor.setShopmoney(BigDecimal.ZERO); // usersPayBefor.setServicemoney(serviceMoney); // usersPayBefor.setMtmoney(BigDecimal.ZERO); // usersPayBefor.setYemoney(BigDecimal.ZERO); // usersPayBefor.setCouponmoney(BigDecimal.ZERO); // usersPayBefor.setServicetype(1L); // usersPayBefor.setMembermoney(memberMoney); // usersPayBefor.setType(7L); // usersPayBefor.setSku(""); // usersPayBefor.setStatus(1L); // 1=待支付 // usersPayBefor.setPaytype(1L); // 默认微信支付 // // int payBeforResult = usersPayBeforService.insertUsersPayBefor(usersPayBefor); // if (payBeforResult <= 0) { // return AppletControllerUtil.appletWarning("预支付记录创建失败"); // } } // //修改订单日志添加费用 // neworderLog.setPrice(price); // neworderLog.setPaid(1L); // neworderLog.setWorkerCost(price); // neworderLog.setLogId(GenerateCustomCode.generCreateOrder("FEE")); // //修改订单状态 // order.setJsonStatus(3); // JSONObject jsonObject3 = new JSONObject(); // jsonObject3.put("type", 2); // order.setLogJson(jsonObject3.toJSONString()); // orderLogService.updateOrderLog(neworderLog); // orderService.updateOrder(order); // Users userinfo = usersService.selectUsersById(order.getUid()); // ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); // //给用户发送微信推送消息 // WXsendMsgUtil.sendMsgForUserDoorMoney(userinfo.getOpenid(), order, serviceGoods); } return AjaxResult.success("设置上门费成功"); } catch (Exception e) { return AppletControllerUtil.appletError("设置上门费失败:" + e.getMessage()); } } /** * 结束订单 * POST * 参数:{"id":订单id} */ @PostMapping("/api/worker/order/end") public AjaxResult workerOrderEnd(@RequestBody Map params, HttpServletRequest request) { // 1. 参数校验 RefundUtil refundUtil = new RefundUtil(); if (params.get("id") == null) { return AjaxResult.error("系统错误"); } Long id = Long.valueOf(params.get("id").toString()); Order orderInfo = orderService.selectOrderById(id); if (orderInfo == null) { return AjaxResult.error("订单不存在"); } String shangmenprice = params.get("price").toString(); // Order orderInfo = orderService.selectOrderById(id); // if (orderInfo == null) { // return AjaxResult.error("订单不存在"); // } Users workerInfo = usersService.selectUsersById(orderInfo.getWorkerId()); if (workerInfo == null) { return AjaxResult.error("师傅记录不存在"); } // 2. 状态判断 String msg = null; switch (orderInfo.getStatus().intValue()) { case 1: msg = "还未接单,不能结束订单"; break; case 3: msg = "服务还在进行中,不能提前结束订单"; break; case 4: msg = "订单已完成"; break; case 5: msg = "订单已取消"; break; case 6: case 7: msg = "订单已结束"; break; } if (msg != null) { return AjaxResult.error(msg); } try { // 3.1 更新订单状态为7(已结束) Order updateOrder = new Order(); updateOrder.setId(id); updateOrder.setStatus(7L); updateOrder.setServicePrice(new BigDecimal(0)); updateOrder.setGoodPrice(new BigDecimal(0)); updateOrder.setTotalPrice(new BigDecimal(0)); orderService.updateOrder(updateOrder); String logOrderId = GenerateCustomCode.generCreateOrder("DSB"); // 3.2 插入订单日志 OrderLog log = new OrderLog(); JSONObject jsonObject = new JSONObject(); //1.1结束订单就要删除客户未支付的付款数据 UsersPayBefor payBefor = new UsersPayBefor(); payBefor.setLastorderid(orderInfo.getOrderId()); payBefor.setStatus(1L); List payBeforList = usersPayBeforService.selectUsersPayBeforList(payBefor); for (UsersPayBefor payBeforInfo : payBeforList) { usersPayBeforService.deleteUsersPayBeforById(payBeforInfo.getId()); } //1.2如果这个订单有支付数据,还要给客户退回去 UsersPayBefor userpayBefor = usersPayBeforService.selectUsersPayBeforByOrderId(orderInfo.getOrderId()); if (userpayBefor != null) { Users user = usersService.selectUsersById(orderInfo.getUid()); //退回其他对应支付时产生的金额和积分 BenefitPointsUtil.refundServiceAndConsumption(orderInfo.getId(), user, userpayBefor.getServicemoney(),userpayBefor.getShopmoney()); System.out.println("=== 开始退款处理,2222222222订单号: " + userpayBefor.getStatus() + " ==="); // if (usersPayBefor.getStatus() == 2){ System.out.println("=== 开始退款处理,2222222222订单号: " + orderInfo.getOrderId() + " ==="); refundUtil.refundOrder(orderInfo.getOrderId()); // } } //1.3找到订单日志的报价数据将报价的支付数据给抹除 OrderLog orderLog = new OrderLog(); orderLog.setOrderId(orderInfo.getOrderId()); orderLog.setType(new BigDecimal(5)); List orderLogList = orderLogService.selectOrderLogList(orderLog); if (!orderLogList.isEmpty()) { orderLogService.updateOrderLogEnd(orderLogList.getFirst().getId()); } if (StringUtils.isNotBlank(shangmenprice)){ log.setPaid(1L); log.setPrice(new BigDecimal(shangmenprice)); jsonObject.put("name","师傅提前结束订单,上门费"+shangmenprice+"元"); }else{ jsonObject.put("name","师傅提前结束订单,无其他费用"); } log.setLogOrderId(logOrderId); log.setOid(orderInfo.getId()); log.setOrderId(orderInfo.getOrderId()); log.setTitle("结束订单"); log.setType(BigDecimal.valueOf(10)); log.setContent(jsonObject.toJSONString()); //Long workerId = getCurrentWorkerId(request); // 需实现 log.setWorkerId(workerInfo.getId()); log.setCreatedAt(new Date()); log.setUpdatedAt(new Date()); orderLogService.insertOrderLog(log); if (StringUtils.isNotBlank(shangmenprice)){ BigDecimal totalAmount=log.getPrice(); Users userinfo = usersService.selectUsersById(orderInfo.getUid()); PayBeforeUtil payBeforeUtil = new PayBeforeUtil(); payBeforeUtil.createPayBefore(userinfo, totalAmount, logOrderId, log.getId(), null, 7L, null, null, null, null, null,1L,null,orderInfo.getOrderId(), null); ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(orderInfo.getProductId()); //微信推送师傅设置上门费 WXsendMsgUtil.sendMsgForUserDoorMoney(userinfo.getOpenid(), orderInfo, serviceGoods); } // 3.4 如果还有虚拟号就解绑虚拟号 if (orderInfo.getMiddlePhone() != null) { VoiceResponseResult unbind = YunXinPhoneUtilAPI.httpsPrivacyUnbind(orderInfo.getWorkerPhone(), orderInfo.getUserPhone(), orderInfo.getMiddlePhone(), orderInfo.getId()); if (unbind.getResult().equals("000000")) { orderService.updateOrderPhone(orderInfo.getId()); } } return AjaxResult.success("订单结束成功"); } catch (Exception e) { return AjaxResult.error("订单结束失败:" + e.getMessage()); } } /** * 云信交互式语音通知呼叫结果推送回调接口 * 用于接收云信平台推送的交互式语音通知呼叫结果。 * * @param requestBody 云信平台推送的JSON字符串 * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 */ @PostMapping("/api/voice/interactNotify/resultCallback") public Map voiceInteractNotifyResultCallback(@RequestBody String requestBody) { // 解析请求体(可根据业务需要保存或处理字段) try { JSONObject json = JSONObject.parseObject(requestBody); // 可提取字段:accountId、callId、calleeNumber、startCallTime、endTime、duration等 // String accountId = json.getString("accountId"); // String callId = json.getString("callId"); // ... 其他字段 // 这里可以根据业务需求进行日志记录、数据库保存等操作 } catch (Exception e) { // 解析异常可记录日志 } // 必须返回{"resultCode":"200"},否则云信会认为推送失败 Map resp = new java.util.HashMap<>(); resp.put("resultCode", "200"); return resp; } /** * 云信交互式小号呼叫结果推送结果推送回调接口 * 用于接收云信平台推送的交互式语音通知呼叫结果。 * * @param requestBody 云信平台推送的JSON字符串 * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 */ @PostMapping("/api/voice/middleNumberAXB/resultCallback") public Map voiceInteractmiddleNumberAXBCallback(@RequestBody String requestBody) { // 解析请求体(可根据业务需要保存或处理字段) try { JSONObject json = JSONObject.parseObject(requestBody); // 可提取字段:accountId、callId、calleeNumber、startCallTime、endTime、duration等 // String accountId = json.getString("accountId"); // String callId = json.getString("callId"); // ... 其他字段 // 这里可以根据业务需求进行日志记录、数据库保存等操作 } catch (Exception e) { // 解析异常可记录日志 } // 必须返回{"resultCode":"200"},否则云信会认为推送失败 Map resp = new java.util.HashMap<>(); resp.put("resultCode", "200"); return resp; } /** * 抢单大厅 - 获取可抢订单列表 *

* 功能说明: * - 查询状态为1(待接单)的订单 * - 支持分页查询 * - 组装商品信息和系统配置 * - 返回标准分页格式数据 * * @param params 请求参数,包含分页信息 * @param request HTTP请求对象 * @return 抢单大厅订单列表数据 */ @PostMapping(value = "/api/worker/grab/lst") public AjaxResult getWorkerGrabOrderList(@RequestBody Map params, HttpServletRequest request) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 1. 解析分页参数 int page = 1; int limit = 15; if (params.get("page") != null) { try { page = Integer.parseInt(params.get("page").toString()); if (page < 1) page = 1; } catch (NumberFormatException e) { page = 1; } } if (params.get("limit") != null) { try { limit = Integer.parseInt(params.get("limit").toString()); if (limit < 1) limit = 15; if (limit > 100) limit = 100; // 限制最大每页数量 } catch (NumberFormatException e) { limit = 15; } } // 2. 设置分页 PageHelper.startPage(page, limit); // 3. 查询状态为1(待接单)的订单 Order orderQuery = new Order(); orderQuery.setStatus(1L); // 待接单状态 orderQuery.setQiangdan("1"); List orderList = orderService.selectOrderList(orderQuery); PageInfo pageInfo = new PageInfo<>(orderList); // 4. 组装订单数据 List> formattedOrderList = new ArrayList<>(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (Order order : orderList) { Map orderData = new HashMap<>(); // 基础订单信息 orderData.put("id", order.getId()); orderData.put("type", order.getType()); orderData.put("main_order_id", order.getMainOrderId()); orderData.put("order_id", order.getOrderId()); orderData.put("transaction_id", order.getTransactionId() != null ? order.getTransactionId() : ""); orderData.put("create_type", order.getCreateType()); orderData.put("create_phone", order.getCreatePhone()); orderData.put("uid", order.getUid()); orderData.put("product_id", order.getProductId()); orderData.put("name", order.getName()); orderData.put("phone", order.getPhone()); orderData.put("address", order.getAddress()); // make_time格式化 if (order.getMakeTime() != null && order.getMakeHour() != null) { orderData.put("make_time", sdf.format(new Date(order.getMakeTime() * 1000)) + " " + order.getMakeHour()); } else { orderData.put("make_time", null); } // // 预约时间处理 // String makeTime = ""; // if (order.getMakeTime() != null) { // try { // // 将时间戳转换为日期格式 // Date makeDate = new Date(order.getMakeTime() * 1000L); // SimpleDateFormat makeDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // makeTime = makeDateFormat.format(makeDate); // if (order.getMakeHour() != null) { // makeTime += " " + order.getMakeHour(); // } // } catch (Exception e) { // makeTime = ""; // } // } // orderData.put("make_time", makeTime); orderData.put("make_hour", order.getMakeHour()); orderData.put("num", order.getNum()); orderData.put("total_price", order.getTotalPrice() != null ? order.getTotalPrice().toString() : "0.00"); orderData.put("good_price", order.getGoodPrice() != null ? order.getGoodPrice().toString() : "0.00"); orderData.put("service_price", order.getServicePrice() != null ? order.getServicePrice().toString() : null); orderData.put("pay_price", order.getPayPrice() != null ? order.getPayPrice().toString() : "0.00"); orderData.put("coupon_id", order.getCouponId()); orderData.put("deduction", order.getDeduction() != null ? order.getDeduction().toString() : "0.00"); orderData.put("pay_time", order.getPayTime()); orderData.put("status", order.getStatus()); orderData.put("is_pause", order.getIsPause()); orderData.put("mark", order.getMark()); orderData.put("address_id", order.getAddressId()); // orderData.put("sku", order.getSku()); orderData.put("sku",AppletControllerUtil.parseSkuStringToObject(order.getSku())); orderData.put("worker_id", order.getWorkerId()); orderData.put("first_worker_id", order.getFirstWorkerId()); orderData.put("receive_time", order.getReceiveTime() != null ? dateFormat.format(order.getReceiveTime()) : null); orderData.put("is_comment", order.getIsComment()); orderData.put("receive_type", order.getReceiveType()); orderData.put("is_accept", order.getIsAccept()); orderData.put("middle_phone", order.getMiddlePhone()); orderData.put("user_phone", order.getUserPhone()); orderData.put("worker_phone", order.getWorkerPhone()); orderData.put("address_en", order.getAddressEn()); orderData.put("uid_admin", order.getUidAdmin()); orderData.put("address_admin", order.getAddressAdmin()); orderData.put("log_status", order.getLogStatus()); orderData.put("log_json", order.getLogJson()); orderData.put("json_status", order.getJsonStatus()); orderData.put("log_images", order.getLogImages()); orderData.put("created_at", order.getCreatedAt() != null ? dateFormat.format(order.getCreatedAt()) : null); orderData.put("updated_at", order.getUpdatedAt() != null ? dateFormat.format(order.getUpdatedAt()) : null); orderData.put("deleted_at", order.getDeletedAt()); // 5. 组装商品信息 Map productData = new HashMap<>(); if (order.getProductId() != null) { try { ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId()); if (serviceGoods != null) { productData.put("id", serviceGoods.getId()); productData.put("title", serviceGoods.getTitle()); productData.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); productData.put("price", serviceGoods.getPrice() != null ? serviceGoods.getPrice().toString() : "0.00"); } else { // 商品不存在时的默认信息 productData.put("id", order.getProductId()); productData.put("title", "商品已下架"); productData.put("icon", ""); productData.put("price", "0.00"); } } catch (Exception e) { // 查询异常时的默认信息 productData.put("id", order.getProductId()); productData.put("title", "商品信息获取失败"); productData.put("icon", ""); productData.put("price", "0.00"); } } else { productData.put("id", null); productData.put("title", ""); productData.put("icon", ""); productData.put("price", "0.00"); } orderData.put("product", productData); formattedOrderList.add(orderData); } // 6. 构建分页数据 String baseUrl = request.getRequestURL().toString().split("\\?")[0]; Map paginationData = AppletControllerUtil.buildPageResult(pageInfo, formattedOrderList, baseUrl); // 7. 查询系统配置(config_one) Map configData = new HashMap<>(); try { SiteConfig siteConfigQuery = new SiteConfig(); siteConfigQuery.setName("config_one"); List configList = siteConfigService.selectSiteConfigList(siteConfigQuery); if (!configList.isEmpty()) { com.ruoyi.system.domain.SiteConfig config = configList.get(0); String configValue = config.getValue(); if (configValue != null && !configValue.trim().isEmpty()) { try { // 尝试解析JSON配置 JSONObject configJson = JSONObject.parseObject(configValue); configData.putAll(configJson); } catch (Exception e) { // JSON解析失败时的默认配置 setDefaultConfig(configData); } } else { // 配置值为空时的默认配置 setDefaultConfig(configData); } } else { // 配置不存在时的默认配置 setDefaultConfig(configData); } } catch (Exception e) { // 查询配置异常时的默认配置 setDefaultConfig(configData); } // 8. 构建最终返回数据 Map responseData = new HashMap<>(); responseData.put("data", paginationData); responseData.put("config", configData); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { logger.error("获取抢单大厅订单列表异常:", e); return AppletControllerUtil.appletError("获取抢单大厅订单列表失败:" + e.getMessage()); } } /** * 商品订单游标接口 * * @param params 请求参数,包含product_id(商品ID)、num(数量)、sku(规格信息) * @param request HTTP请求对象 * @return 返回商品ID *

* 接口说明: * - 接收商品订单相关信息 * - 调用IGoodsOrderCursorService新增一条数据 * - 返回商品ID作为响应数据 *

*/ @PostMapping("/api/service/cursor") public AjaxResult serviceCursor(@RequestBody Map params, HttpServletRequest request) { try { // 1. 参数验证 if (params == null) { return AppletControllerUtil.appletWarning("请求参数不能为空"); } // 验证必要参数 if (params.get("product_id") == null) { return AppletControllerUtil.appletWarning("商品ID不能为空"); } if (params.get("num") == null) { return AppletControllerUtil.appletWarning("商品数量不能为空"); } // 2. 解析参数 Long productId; Integer num; String sku = params.get("sku") != null ? params.get("sku").toString() : ""; try { productId = Long.valueOf(params.get("product_id").toString()); num = Integer.valueOf(params.get("num").toString()); } catch (NumberFormatException e) { return AppletControllerUtil.appletWarning("参数格式错误"); } // 3. 验证参数有效性 if (productId <= 0) { return AppletControllerUtil.appletWarning("商品ID无效"); } if (num <= 0) { return AppletControllerUtil.appletWarning("商品数量必须大于0"); } // 4. 验证商品是否存在 ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId); if (serviceGoods == null) { return AppletControllerUtil.appletWarning("商品不存在"); } // 5. 验证商品状态 if (serviceGoods.getStatus() == null || !"1".equals(serviceGoods.getStatus())) { return AppletControllerUtil.appletWarning("商品已下架或不可购买"); } // 6. 验证库存(如果有库存管理) if (serviceGoods.getStock() != null && serviceGoods.getStock() < num) { return AppletControllerUtil.appletWarning("商品库存不足"); } // 7. 解析并验证SKU信息(如果有的话) if (sku != null && !sku.trim().isEmpty()) { try { JSONObject skuJson = JSONObject.parseObject(sku); // 验证SKU中的库存 if (skuJson.containsKey("stock")) { String stockStr = skuJson.getString("stock"); try { int skuStock = Integer.parseInt(stockStr); if (skuStock < num) { return AppletControllerUtil.appletWarning("SKU库存不足"); } } catch (NumberFormatException e) { // SKU库存格式错误,忽略验证 } } } catch (Exception e) { // SKU JSON格式错误,但不影响主流程 } } // 8. 构建GoodsOrderCursor对象 GoodsOrderCursor goodsOrderCursor = new GoodsOrderCursor(); goodsOrderCursor.setProductId(productId); goodsOrderCursor.setType(2l); goodsOrderCursor.setNum(num.longValue()); goodsOrderCursor.setSku(sku); // 设置其他必要字段 // 计算价格(从SKU或商品价格) BigDecimal totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); if (sku != null && !sku.trim().isEmpty()) { try { JSONObject skuJson = JSONObject.parseObject(sku); if (skuJson.containsKey("price")) { String priceStr = skuJson.getString("price"); try { BigDecimal skuPrice = new BigDecimal(priceStr); totalPrice = skuPrice.multiply(BigDecimal.valueOf(num)); } catch (NumberFormatException e) { // SKU价格解析失败,使用商品原价 totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); } } } catch (Exception e) { // SKU解析失败,使用商品原价 totalPrice = serviceGoods.getPrice().multiply(BigDecimal.valueOf(num)); } } goodsOrderCursor.setTotalPrice(totalPrice); // goodsOrderCursor.setProductName(serviceGoods.getTitle()); // 9. 调用服务新增数据 int result = goodsOrderCursorService.insertGoodsOrderCursor(goodsOrderCursor); if (result > 0) { // 10. 返回商品ID return AppletControllerUtil.appletSuccess(goodsOrderCursor.getId()); } else { return AppletControllerUtil.appletWarning("数据保存失败"); } } catch (Exception e) { System.err.println("商品订单游标接口异常:" + e.getMessage()); return AppletControllerUtil.appletWarning("操作失败:" + e.getMessage()); } } /** * 云信交互式小号呼叫结果推送结果推送回调接口 * 用于接收云信平台推送的交互式语音通知呼叫结果。 * * @return 必须返回{"resultCode":"200"},否则云信认为推送失败 */ @PostMapping("api/worker/withdraw") public Map withdraw(@RequestBody Map params, HttpServletRequest request) { // 1. 验证用户登录状态 String token = request.getHeader("token"); Map userValidation = AppletLoginUtil.validateUserToken(token, usersService); if (!(Boolean) userValidation.get("valid")) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } String orderId =GenerateCustomCode.generCreateOrder("TX"); // 2. 获取用户信息 Users user = (Users) userValidation.get("user"); if (user == null) { return AppletControllerUtil.appletdengluWarning("用户信息获取失败"); } String money = params.get("money").toString(); if (money == null || money.trim().isEmpty()) { return AppletControllerUtil.appletWarning("提现金额不能为空"); } BigDecimal moneyBigDecimal = new BigDecimal(money); if (moneyBigDecimal.compareTo(new BigDecimal(1)) <= 0) { return AppletControllerUtil.appletWarning("提现金额必须大于1元"); } if (moneyBigDecimal.compareTo(user.getCommission()) > 0) { return AppletControllerUtil.appletWarning("提现金额不能大于账户余额"); } if (moneyBigDecimal.compareTo(new BigDecimal("2000")) > 0) { return AppletControllerUtil.appletWarning("提现金额不能大于2000"); } //--------------------------预留提现的接口实现核心逻辑开始-------------------------------- Map result = wechatPayV3Util.quickWithdraw(user.getOpenid(), moneyBigDecimal, "师傅收益提现",orderId); if ((Boolean) result.get("success")) { System.out.println("快速提现成功"+result); WechatTransfer wechatTransfer = new WechatTransfer(); wechatTransfer.setUid(user.getId()); wechatTransfer.setMoney(moneyBigDecimal);// wechatTransfer.setUname(user.getName()); wechatTransfer.setOrderId(orderId); wechatTransfer.setStatus(1L); wechatTransfer.setPaid(0L); wechatTransfer.setOpenid(user.getOpenid()); int flg= wechatTransferService.insertWechatTransfer(wechatTransfer); // if(flg>0){ // // //减少师傅提现的余额 // user.setCommission(user.getCommission().subtract(moneyBigDecimal)); // //增加师傅的累计提现金额 // user.setPropose(user.getPropose().add(moneyBigDecimal)); // usersService.updateUsers(user); // } return AppletControllerUtil.appletSuccess("提现成功") ; } else { System.out.println("快速提现失败"+result); return AppletControllerUtil.appletError("服务器繁忙,请稍后重试"); } //------------------------------------结束-------------------------------- // Map resp = new java.util.HashMap<>(); // resp.put("resultCode", "200"); // return resp; } /** * 获取商品订单临时信息 * * @param id 订单临时ID * @param request HTTP请求对象 * @return 订单临时信息及关联商品信息 *

* 接口说明: * - 根据ID查询商品订单临时数据 * - 通过product_id关联查询商品信息 * - 返回包含订单信息和商品详情的完整数据 */ @GetMapping(value = "/api/service/cursor/info/{id}") public AjaxResult getGoodsOrderCursorInfo(@PathVariable("id") long id, HttpServletRequest request) { try { // 参数验证 if (id <= 0) { return AppletControllerUtil.appletError("订单ID无效"); } // 1. 查询商品订单临时数据 GoodsOrderCursor orderCursor = goodsOrderCursorService.selectGoodsOrderCursorById(id); if (orderCursor == null) { return AppletControllerUtil.appletError("订单信息不存在"); } // 2. 根据product_id查询商品信息 ServiceGoods product = null; if (orderCursor.getProductId() != null) { product = serviceGoodsService.selectServiceGoodsById(orderCursor.getProductId()); } // 3. 构建返回数据 Map responseData = new HashMap<>(); // 订单基本信息 responseData.put("id", orderCursor.getId()); responseData.put("product_id", orderCursor.getProductId()); responseData.put("type", orderCursor.getType()); responseData.put("num", orderCursor.getNum()); responseData.put("sku", orderCursor.getSku()); responseData.put("total_price", orderCursor.getTotalPrice() != null ? orderCursor.getTotalPrice().toString() : "0.00"); responseData.put("created_at", AppletControllerUtil.formatDateToString(orderCursor.getCreatedAt())); responseData.put("updated_at", AppletControllerUtil.formatDateToString(orderCursor.getUpdatedAt())); // 4. 添加商品信息 if (product != null) { Map productInfo = new HashMap<>(); productInfo.put("id", product.getId()); productInfo.put("title", product.getTitle()); responseData.put("postage",product.getPostage()); productInfo.put("price", product.getPrice() != null ? product.getPrice().toString() : "0.00"); productInfo.put("stock", product.getStock()); productInfo.put("isforservice", product.getIsforservice()); productInfo.put("forserviceid", product.getForserviceid()); productInfo.put("sku_type", product.getSkuType()); productInfo.put("icon", AppletControllerUtil.buildImageUrl(product.getIcon())); responseData.put("product", productInfo); } else { // 商品不存在时的默认信息 Map productInfo = new HashMap<>(); productInfo.put("id", orderCursor.getProductId()); productInfo.put("title", "商品已下架"); productInfo.put("price", "0.00"); productInfo.put("stock", 0); productInfo.put("sku_type", 1); productInfo.put("icon", ""); responseData.put("product", productInfo); } return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { return AppletControllerUtil.appletError("查询订单信息失败:" + e.getMessage()); } } /** * 设置默认配置信息 * * @param configData 配置数据Map */ private void setDefaultConfig(Map configData) { configData.put("phone", "02988256922"); configData.put("loot_start", "00:59"); configData.put("loot_end", "23:30"); configData.put("margin", "10"); configData.put("integral", "100"); configData.put("hot", new String[]{"水电维修", "家电清洗", "灯具维修", "墙面翻新", "门窗家具", "改造维修", "防水维修"}); configData.put("kf", ""); } /** * 获取首页通知公告列表接口 * * @param request HTTP请求对象 * @return 上线状态的通知公告列表 *

* 接口说明: * - 查询config_seven配置中的通知公告数据 * - 只返回status=1(上线)状态的公告 * - 按sort字段升序排列 * - 返回title、content、link、sort等字段 * - 无需用户登录验证 *

*/ @GetMapping(value = "/api/public/notice/list") public AjaxResult getHomeNoticeList(HttpServletRequest request) { try { // 新增:获取category参数(1=首页,2=活动) String categoryParam = request.getParameter("category"); String filterCategory = null; if ("1".equals(categoryParam)) { filterCategory = "home"; } else if ("2".equals(categoryParam)) { filterCategory = "activity"; } // 1. 查询config_seven配置 SiteConfig configQuery = new SiteConfig(); configQuery.setName("config_seven"); List configList = siteConfigService.selectSiteConfigList(configQuery); if (configList.isEmpty()) { // 配置不存在时返回空数组 return AppletControllerUtil.appletSuccess(new ArrayList<>()); } SiteConfig config = configList.get(0); String configValue = config.getValue(); if (configValue == null || configValue.trim().isEmpty()) { // 配置值为空时返回空数组 return AppletControllerUtil.appletSuccess(new ArrayList<>()); } // 2. 解析JSON配置 JSONObject configJson; try { configJson = JSONObject.parseObject(configValue); } catch (Exception e) { System.err.println("解析config_seven配置JSON失败:" + e.getMessage()); return AppletControllerUtil.appletSuccess(new ArrayList<>()); } // 3. 获取notice数组 if (!configJson.containsKey("notice")) { return AppletControllerUtil.appletSuccess(new ArrayList<>()); } Object noticeObj = configJson.get("notice"); if (!(noticeObj instanceof JSONArray)) { return AppletControllerUtil.appletSuccess(new ArrayList<>()); } JSONArray noticeArray = (JSONArray) noticeObj; // 4. 过滤上线状态的公告并构建返回数据 List> resultList = new ArrayList<>(); for (int i = 0; i < noticeArray.size(); i++) { try { JSONObject noticeItem = noticeArray.getJSONObject(i); // 检查状态是否为上线(status=1) Integer status = noticeItem.getInteger("status"); if (status == null || status != 1) { continue; // 跳过下线或状态异常的公告 } // 新增:按分类过滤 if (filterCategory != null) { String itemCategory = noticeItem.getString("category"); if (itemCategory == null) itemCategory = "home"; // 兼容老数据 if (!filterCategory.equals(itemCategory)) { continue; } } // 构建公告数据 Map notice = new HashMap<>(); notice.put("title", noticeItem.getString("title")); notice.put("content", noticeItem.getString("content")); notice.put("link", noticeItem.getString("link")); notice.put("sort", noticeItem.getInteger("sort")); notice.put("status", status); resultList.add(notice); } catch (Exception e) { // 单个公告解析失败时跳过,继续处理其他公告 System.err.println("解析单个公告数据失败:" + e.getMessage()); continue; } } // 5. 按sort字段升序排序 resultList.sort((a, b) -> { Integer sortA = (Integer) a.get("sort"); Integer sortB = (Integer) b.get("sort"); if (sortA == null) sortA = Integer.MAX_VALUE; if (sortB == null) sortB = Integer.MAX_VALUE; return sortA.compareTo(sortB); }); return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { System.err.println("获取首页通知公告列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("获取通知公告列表失败:" + e.getMessage()); } } /** * 获取报价产品列表接口 * * @param params 请求参数,包含limit(每页数量)、page(页码)、keywords(搜索关键词) * @param request HTTP请求对象 * @return 报价产品列表 *

* 接口说明: * - 查询servicetype=2的报价产品 * - 支持按商品标题进行模糊查询 * - 支持分页查询 * - 自动添加图片CDN前缀 * - 无需用户登录验证 *

*/ @PostMapping(value = "/api/quote/product/lst") public AjaxResult getQuoteProductList(@RequestBody Map params, HttpServletRequest request) { try { // 1. 获取分页参数并进行安全的类型转换 int page = 1; int limit = 15; if (params.get("page") != null) { try { page = Integer.parseInt(params.get("page").toString()); if (page < 1) page = 1; } catch (NumberFormatException e) { page = 1; } } if (params.get("limit") != null) { try { limit = Integer.parseInt(params.get("limit").toString()); if (limit < 1) limit = 15; if (limit > 100) limit = 100; // 限制最大每页数量 } catch (NumberFormatException e) { limit = 15; } } String keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : ""; // 2. 验证分页参数 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } // 3. 设置分页参数 PageHelper.startPage(page, limit); // 4. 构建查询条件 ServiceGoods queryGoods = new ServiceGoods(); queryGoods.setServicetype(2); // 查询servicetype=2的报价产品 queryGoods.setStatus(String.valueOf(1L)); // 只查询启用状态的商品 // 如果有关键词,设置标题模糊查询 if (!keywords.isEmpty()) { queryGoods.setTitle(keywords); } // 5. 查询报价产品列表 List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); // 6. 构建返回数据 List> resultList = new ArrayList<>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (ServiceGoods goods : goodsList) { Map goodsData = new HashMap<>(); // 基本商品信息 goodsData.put("id", goods.getId()); goodsData.put("title", goods.getTitle()); goodsData.put("sub_title", goods.getSubTitle()); goodsData.put("price", goods.getPrice() != null ? goods.getPrice().toString() : "0.00"); goodsData.put("price_zn", goods.getPriceZn()); goodsData.put("servicetype", goods.getServicetype()); goodsData.put("status", goods.getStatus()); goodsData.put("type", goods.getType()); goodsData.put("cate_id", goods.getCateId()); goodsData.put("sort", goods.getSort()); goodsData.put("stock", goods.getStock()); goodsData.put("sales", goods.getSales()); goodsData.put("sku_type", goods.getSkuType()); // 处理图片URL - 添加CDN前缀 goodsData.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); // 处理轮播图 if (goods.getImgs() != null && !goods.getImgs().isEmpty()) { try { List bannerList = AppletControllerUtil.parseStringToList(goods.getImgs()); List processedBannerList = new ArrayList<>(); for (String banner : bannerList) { processedBannerList.add(AppletControllerUtil.buildImageUrl(banner)); } goodsData.put("banner", processedBannerList); } catch (Exception e) { goodsData.put("banner", new ArrayList<>()); } } else { goodsData.put("banner", new ArrayList<>()); } // // 处理标签 // if (goods.getLabel() != null && !goods.getLabel().isEmpty()) { // try { // List labelList = AppletControllerUtil.parseStringToList(goods.getLabel()); // goodsData.put("label", labelList); // } catch (Exception e) { // goodsData.put("label", new ArrayList<>()); // } // } else { // goodsData.put("label", new ArrayList<>()); // } // 时间字段格式化 goodsData.put("created_at", goods.getCreatedAt() != null ? sdf.format(goods.getCreatedAt()) : null); goodsData.put("updated_at", goods.getUpdatedAt() != null ? sdf.format(goods.getUpdatedAt()) : null); // 其他字段 goodsData.put("basic", goods.getBasic()); goodsData.put("images", goods.getImgs()); goodsData.put("content", goods.getInfo()); goodsData.put("sku", goods.getSku()); resultList.add(goodsData); } // 7. 构建分页信息 PageInfo pageInfo = new PageInfo<>(goodsList); // 8. 构建返回数据格式 Map responseData = new HashMap<>(); responseData.put("current_page", pageInfo.getPageNum()); responseData.put("data", resultList); responseData.put("from", pageInfo.getStartRow()); responseData.put("last_page", pageInfo.getPages()); responseData.put("per_page", pageInfo.getPageSize()); responseData.put("to", pageInfo.getEndRow()); responseData.put("total", pageInfo.getTotal()); // 构建分页链接信息 String baseUrl = "https://www.huafurenjia.cn/api/quote/product/lst"; responseData.put("first_page_url", baseUrl + "?page=1"); responseData.put("last_page_url", baseUrl + "?page=" + pageInfo.getPages()); responseData.put("next_page_url", pageInfo.isHasNextPage() ? baseUrl + "?page=" + pageInfo.getNextPage() : null); responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ? baseUrl + "?page=" + pageInfo.getPrePage() : null); responseData.put("path", baseUrl); // 构建links数组 List> links = new ArrayList<>(); Map prevLink = new HashMap<>(); prevLink.put("url", pageInfo.isHasPreviousPage() ? baseUrl + "?page=" + pageInfo.getPrePage() : null); prevLink.put("label", "« Previous"); prevLink.put("active", false); links.add(prevLink); Map nextLink = new HashMap<>(); nextLink.put("url", pageInfo.isHasNextPage() ? baseUrl + "?page=" + pageInfo.getNextPage() : null); nextLink.put("label", "Next »"); nextLink.put("active", false); links.add(nextLink); responseData.put("links", links); return AppletControllerUtil.appletSuccess(responseData); } catch (Exception e) { System.err.println("查询报价产品列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("查询报价产品列表失败:" + e.getMessage()); } } /** * 获取活动专区展示接口 * 查询config_eight配置,返回activities数组 */ @GetMapping(value = "/api/public/activity/list") public AjaxResult getActivityList(HttpServletRequest request) { try { // 查询config_eight配置 SiteConfig configQuery = new SiteConfig(); configQuery.setName("config_eight"); List configList = siteConfigService.selectSiteConfigList(configQuery); if (configList.isEmpty()) { // 配置不存在时返回空数组 return AppletControllerUtil.appletSuccess(new ArrayList<>()); } SiteConfig config = configList.get(0); String configValue = config.getValue(); if (configValue == null || configValue.trim().isEmpty()) { // 配置值为空时返回空数组 return AppletControllerUtil.appletSuccess(new ArrayList<>()); } // 解析JSON配置 JSONObject configJson; try { configJson = JSONObject.parseObject(configValue); } catch (Exception e) { System.err.println("解析config_eight配置JSON失败:" + e.getMessage()); return AppletControllerUtil.appletSuccess(new ArrayList<>()); } // 获取activities数组 if (!configJson.containsKey("activities")) { return AppletControllerUtil.appletSuccess(new ArrayList<>()); } Object activitiesObj = configJson.get("activities"); if (!(activitiesObj instanceof JSONArray)) { return AppletControllerUtil.appletSuccess(new ArrayList<>()); } JSONArray activitiesArray = (JSONArray) activitiesObj; // 直接返回activities数组 return AppletControllerUtil.appletSuccess(activitiesArray); } catch (Exception e) { System.err.println("获取活动专区列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("获取活动专区列表失败:" + e.getMessage()); } } /** * 首页拼团专区列表接口 * 查询type=1且isgroup=1的服务商品前6个 * 返回icon、标题、price、groupprice字段 */ @GetMapping(value = "/api/public/group/list") public AjaxResult getGroupList(HttpServletRequest request) { try { // 构建查询条件 ServiceGoods queryGoods = new ServiceGoods(); queryGoods.setType(1); // type=1 queryGoods.setIsgroup(1); // isgroup=1 queryGoods.setStatus("1"); // 只查询启用状态的商品 // 查询服务商品列表 List goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods); // 只取前4个 if (goodsList.size() > 4) { goodsList = goodsList.subList(0, 6); } // 构建返回数据 List> resultList = new ArrayList<>(); for (ServiceGoods goods : goodsList) { Map goodsData = new HashMap<>(); // 基本信息 goodsData.put("id", goods.getId()); goodsData.put("groupnum", goods.getGroupnum()); goodsData.put("title", goods.getTitle()); goodsData.put("price", goods.getPrice() != null ? goods.getPrice().toString() : "0.00"); goodsData.put("groupprice", goods.getGroupprice() != null ? goods.getGroupprice().toString() : "0.00"); // 处理图片URL - 添加CDN前缀 goodsData.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); resultList.add(goodsData); } return AppletControllerUtil.appletSuccess(resultList); } catch (Exception e) { System.err.println("获取拼团专区列表异常:" + e.getMessage()); return AppletControllerUtil.appletError("获取拼团专区列表失败:" + e.getMessage()); } } /** * 首页接口汇总 */ @GetMapping(value = "/api/public/home/data") public AjaxResult publichomedata(HttpServletRequest request) { String city = request.getHeader("ct"); Map responseData = new HashMap<>(); HomeUtril homeUtril = new HomeUtril(); //轮播图 responseData.put("lunbotu", homeUtril.getAdvImgData(2L)); //首页公告 responseData.put("shouyegonggao", homeUtril.getHomeNoticeList("1")); //分类列表 responseData.put("shouyefenlei", homeUtril.getServiceCategories(city)); //活动专区 responseData.put("huodongzhuanqu", homeUtril.getActivityList()); //活动专区公告 responseData.put("huodongzhuanqugonggao", homeUtril.getHomeNoticeList("2")); //公司简介 responseData.put("gongsijianjie", homeUtril.getConfig("config_one")); //资质证书 responseData.put("zizhizhengshu", homeUtril.getAdvImgData(1L)); //拼团专区 responseData.put("pintuanzhuanqu", homeUtril.getGroupList(city)); return AppletControllerUtil.appletSuccess(responseData); } /** * 首页接口汇总 */ @GetMapping(value = "/api/public/group/catelst") public AjaxResult groupCatelst(@RequestParam(value = "type", required = false, defaultValue = "1") int type) { List cateList; // 根据type调用不同的分类查询方法 if (type == 1) { cateList = serviceCateService.selectServiceCatepintuanList(); // 拼团 } else if (type == 2) { cateList = serviceCateService.selectServiceCateCiKaList(); // 次卡 } else if (type == 3) { cateList = serviceCateService.selectServiceCateMiaoshaList(); // 秒杀 } else if (type == 4) { cateList = serviceCateService.selectServiceCateBaojiaList(); // 报价 } else { cateList = new ArrayList<>(); } List> cateDataList = new ArrayList<>(); for (ServiceCate cate : cateList) { Map cateData = new HashMap<>(); cateData.put("id", cate.getId()); cateData.put("title", cate.getTitle()); cateData.put("icon", AppletControllerUtil.buildImageUrl(cate.getIcon())); cateDataList.add(cateData); } return AppletControllerUtil.appletSuccess(cateDataList); } /** * 获取拼团服务列表 * 查询status=1、type=1、isgroup=1的服务商品,分页返回 * 只返回图标、标题、原价、拼团价、拼团人数 * @param params 请求参数,包含page和limit * @return 拼团服务分页列表 * * 1查拼团 2查次卡 3查秒杀 4查报价 */ @PostMapping("/api/group/service/list") public AjaxResult getGroupServiceList(@RequestBody Map params,HttpServletRequest request) { try { String city = request.getHeader("ct"); int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1; int limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 15; Long cateId = null; if (params.get("cateid") != null && !params.get("cateid").toString().isEmpty()) { cateId = Long.parseLong(params.get("cateid").toString()); } int type = params.get("type") != null ? Integer.parseInt(params.get("type").toString()) : 1; // 分页参数校验 Map pageValidation = PageUtil.validatePageParams(page, limit); if (!(Boolean) pageValidation.get("valid")) { return AppletControllerUtil.appletWarning((String) pageValidation.get("message")); } //拼团数据 if (type == 1) { // 设置分页 PageHelper.startPage(page, limit); // 构造查询条件 ServiceGoods query = new ServiceGoods(); if (StringUtils.isNotBlank(city)) { query.setCity(city); } query.setStatus("1"); query.setType(1); query.setIsgroup(1);//1是拼团 if (cateId != null) { query.setCateId(cateId); } List goodsList = serviceGoodsService.selectServiceGoodsList(query); // 只返回需要的字段 List> resultList = new ArrayList<>(); for (ServiceGoods goods : goodsList) { Map map = new HashMap<>(); map.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); map.put("title", goods.getTitle()); map.put("price", goods.getPrice()); map.put("id", goods.getId()); map.put("groupprice", goods.getGroupprice()); map.put("groupnum", goods.getGroupnum()); resultList.add(map); } // 分页封装 TableDataInfo tableDataInfo = getDataTable(goodsList); tableDataInfo.setRows(resultList); // 只返回精简字段 Map pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit); return AppletControllerUtil.appletSuccess(pageData); } //次卡数据 if (type == 2) { // 设置分页 PageHelper.startPage(page, limit); // 构造查询条件 UserSecondaryCard queryParams = new UserSecondaryCard(); queryParams.setStatus(1L); if (cateId != null) { queryParams.setType(cateId); } List goodsList = userSecondaryCardService.selectUserSecondaryCardList(queryParams); // 只返回需要的字段 List> resultList = new ArrayList<>(); for (UserSecondaryCard goods : goodsList) { Map map = new HashMap<>(); map.put("id", goods.getId()); map.put("orderid", goods.getOrderid()); map.put("title", goods.getTitle()); map.put("goodsids", goods.getGoodsids()); map.put("show_money", goods.getShowMoney()); map.put("real_money", goods.getRealMoney()); map.put("showimage", AppletControllerUtil.buildImageUrl(goods.getShowimage())); map.put("status", goods.getStatus()); map.put("creattime", goods.getCreattime()); map.put("type", goods.getType()); map.put("num", goods.getNum()); map.put("allnum", goods.getAllnum()); map.put("introduction", goods.getIntroduction()); List idsList = JSONArray.parseArray(goods.getGoodsids(), String.class); List serviceGoodsList = serviceGoodsService.selectServiceGoodsfrocikaList(idsList); List> serviceDetail = new ArrayList<>(); if(serviceGoodsList != null && !serviceGoodsList.isEmpty()) { for(ServiceGoods serviceGoods : serviceGoodsList) { Map card = new HashMap<>(); card.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); card.put("title", serviceGoods.getTitle()); card.put("price", serviceGoods.getPrice()); card.put("id", serviceGoods.getId()); serviceDetail.add( card); } } map.put("serviceDetail", serviceDetail); // card.setServiceDetail(serviceGoodsService.selectServiceGoodsfrocikaList(idsList)); resultList.add(map); } // 分页封装 TableDataInfo tableDataInfo = getDataTable(goodsList); tableDataInfo.setRows(resultList); // 只返回精简字段 Map pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit); return AppletControllerUtil.appletSuccess(pageData); } //秒杀数据 if (type == 3) { // 设置分页 PageHelper.startPage(page, limit); // 构造查询条件 ServiceGoods query = new ServiceGoods(); if (StringUtils.isNotBlank(city)) { query.setCity(city); } query.setStatus("1"); query.setType(1); query.setIsfixed(1);//秒杀 if (cateId != null) { query.setCateId(cateId); } List goodsList = serviceGoodsService.selectServiceGoodsList(query); // 只返回需要的字段 List> resultList = new ArrayList<>(); for (ServiceGoods goods : goodsList) { Map map = new HashMap<>(); map.put("id", goods.getId()); map.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); map.put("title", goods.getTitle()); map.put("price", goods.getPrice()); map.put("fixedprice", goods.getFixedprice()); resultList.add(map); } // 分页封装 TableDataInfo tableDataInfo = getDataTable(goodsList); tableDataInfo.setRows(resultList); // 只返回精简字段 Map pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit); // 获取秒杀相关数据 long msdata = 0L; try { // 获取config_one配置中的秒杀结束时间 SiteConfig configQuery = new SiteConfig(); configQuery.setName("config_one"); List configList = siteConfigService.selectSiteConfigList(configQuery); if (configList != null && !configList.isEmpty()) { String configValue = configList.get(0).getValue(); if (configValue != null && !configValue.trim().isEmpty()) { JSONObject configJson = JSONObject.parseObject(configValue); String mstime = configJson.getString("mstime"); if (mstime != null && !mstime.trim().isEmpty()) { // 解析秒杀结束时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date endTime = sdf.parse(mstime); msdata = endTime.getTime(); // 返回结束时间的毫秒数 } } } } catch (Exception e) { // 解析异常时设置为0 msdata = 0L; } Map reData = new HashMap<>(); reData.put("listData", pageData); reData.put("msdata", msdata); return AppletControllerUtil.appletSuccess(reData); } //报价数据 if (type == 4) { // 设置分页 PageHelper.startPage(page, limit); // 构造查询条件 ServiceGoods query = new ServiceGoods(); query.setStatus("1"); query.setType(1); if (StringUtils.isNotBlank(city)) { query.setCity(city); } query.setServicetype(2);//报价 if (cateId != null) { query.setCateId(cateId); } List goodsList = serviceGoodsService.selectServiceGoodsList(query); // 只返回需要的字段 List> resultList = new ArrayList<>(); for (ServiceGoods goods : goodsList) { Map map = new HashMap<>(); map.put("id", goods.getId()); map.put("icon", AppletControllerUtil.buildImageUrl(goods.getIcon())); map.put("title", goods.getTitle()); resultList.add(map); } // 分页封装 TableDataInfo tableDataInfo = getDataTable(goodsList); tableDataInfo.setRows(resultList); // 只返回精简字段 Map pageData = PageUtil.buildPageResponse(tableDataInfo, page, limit); return AppletControllerUtil.appletSuccess(pageData); } } catch (Exception e) { return AppletControllerUtil.appletError("获取拼团服务列表失败:" + e.getMessage()); } return null; } }