javacodeadmin/ruoyi-system/src/main/java/com/ruoyi/system/controllerUtil/OrderUtil.java

2094 lines
96 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ruoyi.system.ControllerUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.AmapUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* 服务订单Controller工具类
* 专注于订单编号生成、状态验证和用户地址处理等核心功能
*/
@Controller
public class OrderUtil {
private static IUsersService usersService = SpringUtils.getBean(IUsersService.class);
private static IOrderLogService orderLogService = SpringUtils.getBean(IOrderLogService.class);
private static IGoodsOrderService goodsOrderService = SpringUtils.getBean(IGoodsOrderService.class);
private static IUserDemandQuotationService userDemandQuotationService = SpringUtils.getBean(IUserDemandQuotationService.class);
private static IUsersPayBeforService usersPayBeforService = SpringUtils.getBean(IUsersPayBeforService.class);
private static IQuoteMaterialService quoteMaterialService = SpringUtils.getBean(IQuoteMaterialService.class);
private static IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
private static OrderLogHandler orderLogHandler = SpringUtils.getBean(OrderLogHandler.class);
// 订单编号生成相关常量
private static final String PREFIX = "C";
private static final int FIXED_LENGTH = 15; // 总长度为15
/**
* 创建新用户对象
*
* @return 新用户对象
*/
public static JSONObject getbaojiajson(String json) {
if (StringUtils.isNotBlank(json)) {
JSONObject jsonObject = JSONObject.parseObject(json);
JSONArray material = jsonObject.getJSONArray("material");
if (material != null) {
for (int i = 0; i < material.size(); i++) {
JSONObject jsonObjectmaterial = material.getJSONObject(i);
String id = jsonObjectmaterial.getString("id");
if (StringUtils.isNotBlank(id)) {
QuoteMaterial quoteMaterial = quoteMaterialService.selectQuoteMaterialById(Long.parseLong(id));
if (quoteMaterial != null) {
jsonObjectmaterial.put("manyimages", JSONArray.parseArray(quoteMaterial.getManyimages()));
jsonObjectmaterial.put("image", AppletControllerUtil.buildImageUrl(quoteMaterial.getImage()));
if (StringUtils.isNotBlank(quoteMaterial.getContent()) && StringUtils.isNotBlank(quoteMaterial.getManyimages())) {
jsonObjectmaterial.put("showtype", 1);
} else {
jsonObjectmaterial.put("showtype", 2);
}
jsonObjectmaterial.put("content", quoteMaterial.getContent());
}
}
}
}
// 直接返回原始jsonObject其他字段都保留
return jsonObject;
}
return new JSONObject();
}
/**
* 生成订单编码的工具
*
* @return 格式为 C + yyyyMMdd + 随机数字 的订单编号
*/
public static String generateCode() {
// 获取当前日期格式化为yyyyMMdd
String currentDate = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
// 生成固定长度的随机数字字符串
int randomLength = FIXED_LENGTH - 1 - currentDate.length(); // 计算需要生成的随机数位数
StringBuilder randomBuilder = new StringBuilder();
Random random = new Random();
for (int i = 0; i < randomLength; i++) {
randomBuilder.append(random.nextInt(10)); // 生成0-9之间的随机数字
}
// 拼接最终的编码
return PREFIX + currentDate + randomBuilder.toString();
}
/**
* 验证订单状态变更是否合法
*
* @param newOrder 新订单状态
* @param oldOrder 旧订单状态
* @return 验证结果,包含状态码和消息
*/
public VerificationResult validateOrderStatusChange(Order newOrder, Order oldOrder) {
// 基础参数验证
if (oldOrder == null) {
return new VerificationResult(VerificationResult.CODE_FAILURE, "旧订单不能为空");
}
Integer newStatus = newOrder.getJsonStatus();
Integer oldStatus = oldOrder.getJsonStatus() != null ? oldOrder.getJsonStatus() : 0;
// 状态未发生变化,直接通过
if (Objects.equals(newStatus, oldStatus)) {
return new VerificationResult(VerificationResult.CODE_SUCCESS, "NODATA");
}
// 创建验证器实例并进行验证
OrderStatusValidator validator = new OrderStatusValidator();
return performStatusValidation(validator, newOrder, newStatus, oldStatus);
}
/**
* 执行状态验证
*
* @param validator 状态验证器
* @param newOrder 新订单
* @param newStatus 新状态
* @param oldStatus 旧状态
* @return 验证结果
*/
private VerificationResult performStatusValidation(OrderStatusValidator validator, Order newOrder, Integer newStatus, Integer oldStatus) {
switch (newStatus) {
case OrderStatusValidator.STATUS_DISPATCH:
return validator.validateDispatchStatus(newOrder, oldStatus);
case OrderStatusValidator.STATUS_ACCEPT:
return validator.validateAcceptStatus(oldStatus);
case OrderStatusValidator.STATUS_SET_FEE:
return validator.validateSetFeeStatus(newOrder, oldStatus);
case OrderStatusValidator.STATUS_DEPART:
return validator.validateDepartStatus(oldStatus);
case OrderStatusValidator.STATUS_ARRIVE:
return validator.validateArriveStatus(oldStatus);
case OrderStatusValidator.STATUS_QUOTE:
return validator.validateQuoteStatus(newOrder, oldStatus);
case OrderStatusValidator.STATUS_START_SERVICE:
return validator.validateStartServiceStatus(newOrder, oldStatus);
case OrderStatusValidator.STATUS_PAUSE_SERVICE:
return validator.validatePauseServiceStatus(newOrder, oldStatus);
case OrderStatusValidator.STATUS_COMPLETE:
return validator.validateCompleteStatus(newOrder, oldStatus);
default:
return new VerificationResult(VerificationResult.CODE_FAILURE, "无效的订单状态");
}
}
/**
* 保存订单日志
* 委托给OrderLogHandler处理具体的业务逻辑
*
* @param order 订单对象,包含状态和服务进度信息
* @return 影响的行数大于0表示保存成功
* @throws IllegalArgumentException 当订单参数无效时
*/
public int SaveOrderLog(Order order) {
// 参数验证
validateOrderForLog(order);
try {
// 委托给OrderLogHandler处理
OrderLog orderLog = orderLogHandler.createBaseOrderLog(order);
orderLogHandler.processOrderStatus(order, orderLog);
// 保存订单日志
return orderLogService.insertOrderLog(orderLog);
} catch (Exception e) {
// 记录异常信息(这里可以添加日志记录)
throw new RuntimeException("保存订单日志失败: " + e.getMessage(), e);
}
}
/**
* 验证订单日志参数
*
* @param order 订单对象
*/
private void validateOrderForLog(Order order) {
if (order == null) {
throw new IllegalArgumentException("订单对象不能为空");
}
if (order.getId() == null || order.getOrderId() == null) {
throw new IllegalArgumentException("订单ID和订单编号不能为空");
}
}
/**
* 根据用户手机号判断用户是否存在,如果不存在则新增用户数据
*
* @param phone 用户手机号
* @param addressName 地址名称
* @return 包含用户和地址信息的Map
*/
public Map<String, Object> isUser(String phone, String addressName) {
Users existingUser = usersService.selectUsersByPhone(phone);
if (existingUser == null) {
// 用户不存在,创建新用户
Users newUser = createNewUser(phone);
if (usersService.insertUsers(newUser) > 0) {
return isAddAddressUser(newUser, addressName);
} else {
return createFailureResult();
}
} else {
return isAddAddressUser(existingUser, addressName);
}
}
/**
* 创建新用户对象
*
* @param phone 用户手机号
* @return 新用户对象
*/
private Users createNewUser(String phone) {
Users user = new Users();
user.setName("微信用户");
user.setType("1");
user.setStatus(1);
user.setPhone(phone);
return user;
}
/**
* 创建失败结果
*
* @return 失败结果Map
*/
private Map<String, Object> createFailureResult() {
Map<String, Object> map = new HashMap<>();
map.put("code", "0");
return map;
}
/**
* 根据用户地址获取经纬度,然后存储地址数据
*
* @param user 用户对象
* @param addressName 地址名称
* @return 包含处理结果的Map
*/
public Map<String, Object> isAddAddressUser(Users user, String addressName) {
// 查询用户是否已有该地址
List<UserAddress> existingAddresses = findExistingAddress(user.getId(), addressName);
if (!existingAddresses.isEmpty()) {
// 地址已存在
return createSuccessResult(user, existingAddresses.get(0));
} else {
// 地址不存在,创建新地址
return createNewUserAddress(user, addressName);
}
}
/**
* 查找已存在的地址
*
* @param userId 用户ID
* @param addressName 地址名称
* @return 地址列表
*/
private List<UserAddress> findExistingAddress(Long userId, String addressName) {
UserAddress queryAddress = new UserAddress();
queryAddress.setUid(userId);
queryAddress.setAddressName(addressName);
return SpringUtils.getBean(IUserAddressService.class).selectUserAddressList(queryAddress);
}
/**
* 创建成功结果
*
* @param user 用户对象
* @param address 地址对象
* @return 成功结果Map
*/
private Map<String, Object> createSuccessResult(Users user, UserAddress address) {
Map<String, Object> map = new HashMap<>();
map.put("code", "1");
map.put("users", user);
map.put("UserAddress", address);
return map;
}
/**
* 创建新的用户地址
*
* @param user 用户对象
* @param addressName 地址名称
* @return 包含处理结果的Map
*/
private Map<String, Object> createNewUserAddress(Users user, String addressName) {
try {
UserAddress userAddress = buildUserAddress(user, addressName);
// 获取地址的经纬度信息
setAddressCoordinates(userAddress, addressName);
// 保存地址
if (SpringUtils.getBean(IUserAddressService.class).insertUserAddress(userAddress) > 0) {
return createSuccessResult(user, userAddress);
} else {
return createFailureResult();
}
} catch (Exception e) {
Map<String, Object> map = new HashMap<>();
map.put("code", "0");
map.put("message", "创建地址失败: " + e.getMessage());
return map;
}
}
/**
* 构建用户地址对象
*
* @param user 用户对象
* @param addressName 地址名称
* @return 用户地址对象
*/
private UserAddress buildUserAddress(Users user, String addressName) {
UserAddress userAddress = new UserAddress();
userAddress.setUid(user.getId());
userAddress.setName(user.getName());
userAddress.setPhone(user.getPhone());
userAddress.setAddressName(addressName);
userAddress.setAddressInfo(addressName);
userAddress.setInfo(addressName);
userAddress.setIsDefault(1L);
return userAddress;
}
/**
* 设置地址的经纬度坐标
*
* @param userAddress 用户地址对象
* @param addressName 地址名称
*/
private void setAddressCoordinates(UserAddress userAddress, String addressName) {
try {
AmapUtils amapUtils = new AmapUtils();
JSONObject geoResult = amapUtils.geocode(addressName);
if ("OK".equals(geoResult.get("info"))) {
parseCoordinates(userAddress, geoResult);
}
} catch (Exception e) {
// 地理编码失败,不影响地址保存,只是没有经纬度信息
System.err.println("获取地址坐标失败: " + e.getMessage());
}
}
/**
* 解析坐标信息
*
* @param userAddress 用户地址对象
* @param geoResult 地理编码结果
*/
private void parseCoordinates(UserAddress userAddress, JSONObject geoResult) {
JSONArray geocodes = geoResult.getJSONArray("geocodes");
if (geocodes != null && !geocodes.isEmpty()) {
JSONObject firstGeocode = geocodes.getJSONObject(0);
String location = firstGeocode.getString("location");
if (location != null && location.contains(",")) {
String[] coordinates = location.split(",");
userAddress.setLongitude(coordinates[0]); // 经度
userAddress.setLatitude(coordinates[1]); // 纬度
}
}
}
/**
* 拼团订单创建参考AppleOrderController标准流程
* @param id 预支付记录ID
* @return 新创建的订单对象若未找到预支付记录则返回null
*/
public Order createGroupOrderByPayBeforId(Long id) {
IUsersPayBeforService usersPayBeforService = SpringUtils.getBean(IUsersPayBeforService.class);
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
IUserAddressService userAddressService = SpringUtils.getBean(IUserAddressService.class);
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
IOrderLogService orderLogService = SpringUtils.getBean(IOrderLogService.class);
// 1. 查询预支付记录
UsersPayBefor payBefor = usersPayBeforService.selectUsersPayBeforById(id);
if (payBefor == null) {
return null; // 未找到预支付记录
}
// 2. 查询商品信息
Long productId = null;
try {
productId = Long.valueOf(payBefor.getSku()); // 假设sku字段存储商品ID
} catch (Exception e) {
// 若sku不是商品ID则尝试orderid等其它方式
}
if (productId == null) {
// 若无法获取商品ID直接返回
return null;
}
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId);
if (serviceGoods == null) {
return null;
}
// 3. 查询地址信息
UserAddress userAddress = null;
if (payBefor.getAddressid() != null) {
userAddress = userAddressService.selectUserAddressById(payBefor.getAddressid());
}
// GenerateCustomCode.
// 4. 生成订单号
//com.ruoyi.system.ControllerUtil.GenerateCustomCode GenerateCustomCode = null;
String orderId = payBefor.getOrderid() != null ? payBefor.getOrderid() : GenerateCustomCode.generCreateOrder("PT");
// 5. 创建订单
Order order = new Order();
order.setOdertype(4); // 拼团
order.setStatus(9L); // 状态9
order.setOrderId(orderId);
order.setUid(payBefor.getUid());
order.setNum(1L); // 默认1可根据业务调整
order.setProductId(serviceGoods.getId());
order.setProductName(serviceGoods.getTitle());
order.setSku(payBefor.getSku());
order.setTotalPrice(payBefor.getAllmoney());
order.setPayPrice(payBefor.getWxmoney());
order.setCreateTime(new Date());
order.setType(1); // 服务订单
order.setCreateType(1); // 用户自主下单
order.setUname(""); // 可补充用户名称
if (userAddress != null) {
order.setAddressId(userAddress.getId());
order.setName(userAddress.getName());
order.setPhone(userAddress.getPhone());
order.setAddress(userAddress.getAddressInfo());
}
// 可补充其它字段,如拼团价、优惠券、备注等
// 6. 保存订单
orderService.insertOrder(order);
// 7. 添加订单日志
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("拼团订单创建");
orderLog.setType(new BigDecimal("1.0"));
orderLog.setContent("拼团订单创建成功");
orderLog.setRemark("拼团订单自动创建");
orderLogService.insertOrderLog(orderLog);
return order;
}
/**
* 订单价格确认工具方法
* 根据服务ID、SKU、是否一口价和订单类型计算最终价格
*
* @param serviceId 服务ID
* @param sku SKU信息格式{"精细擦玻璃":"20㎡全屋精细擦窗","pic":"","price":"236","groupprice":"100","seckillprice":"99","stock":"1000"}
* @param type 订单类别 1=拼团 2=次卡 3=秒杀
* @return 计算后的价格如果计算失败返回null
*
* 使用示例:
* // 一口价订单(单规格)
* BigDecimal price1 = OrderUtil.confirmOrderPrice(1L, null, 1, 1);
*
* // 一口价订单(多规格)
* String sku = "{\"精细擦玻璃\":\"20㎡全屋精细擦窗\",\"pic\":\"\",\"price\":\"236\",\"groupprice\":\"100\",\"seckillprice\":\"99\",\"stock\":\"1000\"}";
* BigDecimal price2 = OrderUtil.confirmOrderPrice(1L, sku, 1, 1);
*
* // 拼团订单(单规格)
* BigDecimal price3 = OrderUtil.confirmOrderPrice(1L, null, 2, 1);
*
* // 秒杀订单(多规格)
* BigDecimal price4 = OrderUtil.confirmOrderPrice(1L, sku, 2, 3);
*/
public static BigDecimal confirmOrderPrice(Long serviceId, String sku, Integer type) {
try {
// // 参数验证
// if (serviceId == null || isyikoujia == null || type == null) {
// return null;
// }
// 获取服务商品信息
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(serviceId);
if (serviceGoods == null) {
return null;
}
// 获取sku_type默认为单规格
Integer skuType = serviceGoods.getSkuType();
if (skuType == null) {
skuType = 1; // 默认为单规格
}
// // 如果是一口价
// if (isyikoujia == 1) {
// // 如果是多规格商品从SKU中获取price
// if (skuType == 2 && sku != null && !sku.trim().isEmpty()) {
// return handleMultiSkuPrice(sku, null); // 传入null表示获取基础价格
// }
// // 单规格商品直接返回商品的基础价格
// return serviceGoods.getPrice();
// }
// 如果不是一口价需要根据sku_type和订单类型判断
// 单规格商品 (sku_type = 1)
if (skuType == 1) {
return handleSingleSkuPrice(serviceGoods, type);
}
// 多规格商品 (sku_type = 2)
else if (skuType == 2) {
return handleMultiSkuPrice(sku, type);
}
return null;
} catch (Exception e) {
// 记录异常信息(这里可以添加日志记录)
System.err.println("订单价格确认失败: " + e.getMessage());
return null;
}
}
/**
* 处理单规格商品价格计算
*
* @param serviceGoods 服务商品对象
* @param type 订单类型 1=拼团 2=次卡 3=秒杀
* @return 计算后的价格
*/
private static BigDecimal handleSingleSkuPrice(ServiceGoods serviceGoods, Integer type) {
switch (type) {
case 1: // 拼团
return serviceGoods.getGroupprice();
case 3: // 秒杀
return serviceGoods.getFixedprice();
case 2: // 一口价
return serviceGoods.getPrice();
default:
return serviceGoods.getPrice(); // 默认返回基础价格
}
}
/**
* 处理多规格商品价格计算
*
* @param sku SKU信息JSON字符串
* @param type 订单类型 1=拼团 2=次卡 3=秒杀null表示获取基础价格
* @return 计算后的价格
*/
private static BigDecimal handleMultiSkuPrice(String sku, Integer type) {
try {
if (sku == null || sku.trim().isEmpty()) {
return null;
}
// 解析SKU JSON
JSONObject skuJson = JSONObject.parseObject(sku);
// 如果type为null获取基础价格
if (type == null) {
String priceStr = skuJson.getString("price");
return parsePrice(priceStr);
}
switch (type) {
case 1: // 拼团
String groupPriceStr = skuJson.getString("groupprice");
return parsePrice(groupPriceStr);
case 3: // 秒杀
String seckillPriceStr = skuJson.getString("seckillprice");
return parsePrice(seckillPriceStr);
case 2: // 一口价
String priceStr = skuJson.getString("price");
return parsePrice(priceStr);
default:
String defaultPriceStr = skuJson.getString("price");
return parsePrice(defaultPriceStr);
}
} catch (Exception e) {
System.err.println("解析多规格SKU价格失败: " + e.getMessage());
return null;
}
}
/**
* 解析价格字符串为BigDecimal
*
* @param priceStr 价格字符串
* @return BigDecimal价格解析失败返回null
*/
private static BigDecimal parsePrice(String priceStr) {
try {
if (priceStr == null || priceStr.trim().isEmpty()) {
return null;
}
return new BigDecimal(priceStr.trim());
} catch (NumberFormatException e) {
System.err.println("价格格式解析失败: " + priceStr);
return null;
}
}
/**
* 预支付回调处理方法
* @param payBefor 预支付记录
* @param user 用户实体
* @return 新建的订单对象仅拼团或处理结果Map
*/
public static Object prepayCallback(UsersPayBefor payBefor, Users user) throws Exception {
System.out.println("=== prepayCallback 方法开始 ===");
System.out.println("输入参数 - payBefor: " + (payBefor != null ? payBefor.toString() : "null"));
System.out.println("输入参数 - user: " + (user != null ? user.toString() : "null"));
if (payBefor == null || user == null) {
System.out.println("参数验证失败 - payBefor或user为空");
return null;
}
int type = payBefor.getType() != null ? payBefor.getType().intValue() : 0;
System.out.println("支付类型 - type: " + type);
System.out.println("服务类型 - servicetype: " + payBefor.getServicetype());
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
// 单个商品支付
if (type == 5){
GoodsOrder gorder = new GoodsOrder();
gorder.setMainOrderId(payBefor.getOrderid());
List<GoodsOrder> gorders = goodsOrderService.selectGoodsOrderList(gorder);
if (gorders != null && !gorders.isEmpty()){
for (GoodsOrder g: gorders){
g.setStatus(2L);
g.setPayTime(DateUtils.getNowDate());
goodsOrderService.updateGoodsOrder(g);
// BenefitPointsUtil.processBenefitPoints(g.getId(),g.getTotalPrice(),"2");
}
}
//String openid, String orderid,String price,String Address, String title,String reamk
//微信发送消息
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),gorder.getAddress(),"商品支付","商品支付成功");
// updateInventoryAndSales(gorder.getOrderId(), 2);
//处理服务金
return payBefor.getOrderid();
}
if (type == 6){
GoodsOrder gorder = new GoodsOrder();
gorder.setMainOrderId(payBefor.getOrderid());
System.out.println("查询拼团商品订单 - orderid: " + payBefor.getOrderid());
List<GoodsOrder> orderslist =goodsOrderService.selectGoodsOrderList(gorder);
System.out.println("查询到的商品订单数量: " + (orderslist != null ? orderslist.size() : 0));
if (!orderslist.isEmpty()){
System.out.println("开始更新商品订单状态");
for (GoodsOrder goodsOrder : orderslist){
System.out.println("更新商品订单 - ID: " + goodsOrder.getId() + ", 原状态: " + goodsOrder.getStatus());
goodsOrder.setStatus(2L);
goodsOrder.setPayTime(DateUtils.getNowDate());
goodsOrder.setTransactionId(payBefor.getPaycode());
int updateResult = goodsOrderService.updateGoodsOrder(goodsOrder);
System.out.println("商品订单更新结果: " + updateResult);
}
} else {
System.out.println("未找到相关商品订单");
}
System.out.println("拼团商品订单处理完成返回orderid: " + payBefor.getOrderid());
//微信发送消息给客户
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),gorder.getAddress(),"商品支付","商品支付成功");
return payBefor.getOrderid();
}
// 7上门费 8定金 9尾款 10差价
if (type == 11) {
GoodsOrder order = goodsOrderService.selectGoodsOrderByorderId(payBefor.getOrderid());
if (order != null) {
order.setStatus(2L);
order.setPayTime(DateUtils.getNowDate());
order.setTransactionId(payBefor.getPaycode());
//BenefitPointsUtil.processBenefitPoints(order.getId(),order.getTotalPrice(),"2");
//微信发送消息
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"商品支付","商品支付成功");
int updateResult = goodsOrderService.updateGoodsOrder(order);
}
return null;
}
if (type == 7) {
// 4. 查询对应的订单日志(上门费记录)
OrderLog orderLog = orderLogService.selectOrderLogById(payBefor.getOid());
if (orderLog != null) {
// 6. 更新上门费支付状态
orderLog.setPaid(2L); // 1已支付
//orderLog.setWorkerCost(new BigDecimal(totalFee));
orderLog.setPayTime(System.currentTimeMillis()/1000);
//orderLog.setUpdateTime(new Date());
int updateResult = orderLogService.updateOrderLog(orderLog);
Order order = orderService.selectOrderByOrderId(payBefor.getLastorderid());
if (order != null){
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
orderService.updateOrder(order);
}
if (updateResult > 0){
ISTOPAYSIZE(payBefor.getLastorderid());
}
// int paynum=usersPayBeforService.countByLastOrderIdAndStatus(order.getOrderId(), 1);
// Order order = orderService.selectOrderByOrderId(payBefor.getLastorderid());
// if (order != null) {
// if (order.getStatus() == 6){
//
// }
// }
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"上门费支付","上门费支付成功");
//微信发送消息给师傅
Users master = usersService.selectUsersById(order.getWorkerId());
WXsendMsgUtil.sendUserPayDoorMoneyForWorker(master.getOpenid(),order,"上门费支付成功");
}
//微信发送消息
return 1;
}
if (type == 8) {
// 4. 查询对应的订单日志(定金记录)
OrderLog orderLog = orderLogService.selectOrderLogById(payBefor.getOid());
if (orderLog != null) {
// 6. 更新定金支付状态
orderLog.setDepPaid(2); // 1已支付
orderLog.setDepPayTime(System.currentTimeMillis()/1000);
int updateResult = orderLogService.updateOrderLog(orderLog);
if (updateResult > 0){
Order order = orderService.selectOrderByOrderId(payBefor.getLastorderid());
if (order != null){
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
orderService.updateOrder(order);
}
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"定金支付","定金支付成功");
//微信发送消息给师傅
Users master = usersService.selectUsersById(order.getWorkerId());
WXsendMsgUtil.sendUserPayDoorMoneyForWorker(master.getOpenid(),order,"定金支付成功");
ISTOPAYSIZE(payBefor.getLastorderid());
}
}
return 1;
}
if (type == 9) {
// 4. 查询对应的服务订单
Order order = orderService.selectOrderByOrderId(payBefor.getLastorderid());
if (order != null) {
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
orderService.updateOrder(order);
//更新最新的一条日志信息
OrderLog orderLog = orderLogService.selectOrderLogById(payBefor.getOid());
orderLog.setPayTime(System.currentTimeMillis()/1000);
orderLog.setPaid(2L);
int updateResult = orderLogService.updateOrderLog(orderLog);
// OrderLog orderLog1 = orderLogService.selectOrderLogById(payBefor.getOid());
// 6. 更新订单支付状态
// order.setStatus(4L); // 2已支付
// // order.setTransactionId(transactionId);
// order.setPayTime(new Date());
// //order.setUpdateTime(new Date());
// // 计算实际支付金额(分转换为元)
// BigDecimal paidAmount = orderLog1.getPrice();
// order.setPayPrice(paidAmount);
// int updateResult = orderService.updateOrder(order);
if (updateResult > 0){
ISTOPAYSIZE(payBefor.getLastorderid());
}
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"尾款支付","尾款支付成功");
//微信发送消息给师傅
Users master = usersService.selectUsersById(order.getWorkerId());
WXsendMsgUtil.sendUserPayDoorMoneyForWorker(master.getOpenid(),order,"尾款支付成功");
}
return 1;
}
if (type == 10) {
OrderLog orderLog = orderLogService.selectOrderLogById(payBefor.getOid());
if (orderLog != null) {
// 6. 更新定金支付状态
orderLog.setCjPaid(2L);
orderLog.setDepPayTime(System.currentTimeMillis()/1000);
int updateResult = orderLogService.updateOrderLog(orderLog);
if (updateResult > 0){
Order order = orderService.selectOrderByOrderId(payBefor.getLastorderid());
if (order != null){
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
orderService.updateOrder(order);
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"差价支付","差价支付成功");
//微信发送消息给师傅
Users master = usersService.selectUsersById(order.getWorkerId());
WXsendMsgUtil.sendUserPayDoorMoneyForWorker(master.getOpenid(),order,"差价支付成功");
}
ISTOPAYSIZE(payBefor.getLastorderid());
}
}
return 1;
}
//需求报价
if (type == 4) {
System.out.println("=== 处理需求报价订单 ===");
System.out.println("查询订单 - orderid: " + payBefor.getOrderid());
// 查询订单
Order order = orderService.selectOrderByOrderId(payBefor.getOrderid());
System.out.println("查询到的订单: " + (order != null ? order.toString() : "null"));
if (order != null) {
UserDemandQuotation userDemandQuotation=userDemandQuotationService.selectUserDemandQuotationById(payBefor.getBaojiaid());
if (userDemandQuotation!=null) {
System.out.println("找到报价记录,开始处理");
//UserDemandQuotation userDemandQuotation=userDemandQuotationList.getFirst();
System.out.println("报价记录详情: " + userDemandQuotation.toString());
System.out.println("更新报价状态为被选中");
userDemandQuotation.setStatus(2L);//被选中状态
int quotationUpdateResult = userDemandQuotationService.updateUserDemandQuotation(userDemandQuotation);
System.out.println("报价状态更新结果: " + quotationUpdateResult);
System.out.println("查询师傅信息 - workerId: " + userDemandQuotation.getWorkerid());
Users users = usersService.selectUsersById(userDemandQuotation.getWorkerid());
System.out.println("查询到的师傅信息: " + (users != null ? users.toString() : "null"));
if (users != null){
order.setStatus(2L);
order.setJsonStatus(2);
order.setPayPrice(order.getPayPrice().add(userDemandQuotation.getMoney()));
order.setFirstWorkerId(users.getId());
order.setIsAccept(1);
order.setWorkerPhone(users.getPhone());
order.setTotalPrice(userDemandQuotation.getMoney());
order.setWorkerId(users.getId());
int orderUpdateResult = orderService.updateOrder(order);
System.out.println("订单更新结果: " + orderUpdateResult);
// 添加订单日志
System.out.println("添加订单日志");
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("报价订单支付成功");
orderLog.setType(new BigDecimal("2.0"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "报价订单支付成功,待服务,师傅"+users.getName());
orderLog.setContent(jsonObject.toJSONString());
int logInsertResult = orderLogService.insertOrderLog(orderLog);
//开始派单
if (logInsertResult>0){
DispatchUtil.dispatchOrder(order.getId());
}
System.out.println("订单日志插入结果: " + logInsertResult);
System.out.println("需求报价订单处理完成");
} else {
System.out.println("未找到师傅信息,处理失败");
}
} else {
System.out.println("未找到报价记录,处理失败");
}
System.out.println("需求报价订单处理完成返回order: " + (order != null ? order.getOrderId() : "null"));
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"报价支付","师傅报价支付成功");
// updateInventoryAndSales(order.getOrderId(), 1);
//dispatchOrderCheck(order);
return order;
} else {
System.out.println("未找到订单,处理失败");
}
System.out.println("需求报价订单处理失败返回null");
return null;
}
//次卡购买的回调
if (type == 12) {
System.out.println("处理次卡订单");
IUserUseSecondaryCardService userUseSecondaryCardService = SpringUtils.getBean(IUserUseSecondaryCardService.class);
UserUseSecondaryCard userUseSecondaryCard = userUseSecondaryCardService.selectUserUseSecondaryCardByorderId(payBefor.getOrderid());
System.out.println("查询到的次卡记录: " + (userUseSecondaryCard != null ? userUseSecondaryCard.toString() : "null"));
if (userUseSecondaryCard != null) {
System.out.println("更新次卡状态");
userUseSecondaryCard.setStatus(1L);
int cardUpdateResult = userUseSecondaryCardService.updateUserUseSecondaryCard(userUseSecondaryCard);
System.out.println("次卡状态更新结果: " + cardUpdateResult);
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),"","次卡支付","次卡支付成功");
}
return null;
}
//秒杀的回调
if (type == 2) {
Order order = orderService.selectOrderByOrderId(payBefor.getOrderid());
System.out.println("查询到的订单: " + (order != null ? order.toString() : "null"));
if (order != null) {
System.out.println("添加订单日志");
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("订单支付");
orderLog.setType(new BigDecimal("1.1"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "订单支付成功,待派单");
orderLog.setContent(jsonObject.toJSONString());
int logInsertResult = orderLogService.insertOrderLog(orderLog);
System.out.println("订单日志插入结果: " + logInsertResult);
System.out.println("更新订单状态为待派单");
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
order.setStatus(1L); // 1=待预约
int orderUpdateResult = orderService.updateOrder(order);
System.out.println("订单状态更新结果: " + orderUpdateResult);
System.out.println("普通订单处理完成返回order: " + order.getOrderId());
//派单效验
// dispatchOrderCheck(order);
//库存及销量变更
// updateInventoryAndSales(order.getOrderId(), 1);
//开始派单 派单模式 1:系统派单 2:后台手动派单 3:指定工人
if (logInsertResult>0){
DispatchUtil.dispatchOrder(order.getId());
}
// if (logInsertResult>0){
// if (order.getReceiveType()==1){
// DispatchUtil.dispatchOrder(order.getId());
// }else{
// if (order.getReceiveType()==3){
// ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
// if (serviceGoods!=null){
// Users newworker = usersService.selectUsersById(order.getWorkerId());
// }
//
// }
// }
// }
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"秒杀订单支付","秒杀订单支付成功");
return order;
} else {
System.out.println("未找到订单");
}
return null;
}
if (type == 1) {
System.out.println("=== 处理拼团订单 ===");
String ptorderid= payBefor.getOrderid();
System.out.println("拼团订单ID: " + ptorderid);
//第一步创建订单状态为待成团
Order order = new Order();
order.setOdertype(1); // 拼团
order.setStatus(9L); // 9=待成团
order.setOrderId(ptorderid);
order.setUid(payBefor.getUid());
order.setNum(payBefor.getNum()); // 默认1可根据业务调整
//order.setProductId(payBefor.getSku() != null ? Long.valueOf(payBefor.getSku()) : null); // 假设sku字段存储商品ID
order.setProductId(payBefor.getServiceid()); // 假设sku字段存储商品ID
System.out.println("商品ID: " + payBefor.getServiceid());
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(payBefor.getServiceid());
System.out.println("查询到的商品信息: " + (serviceGoods != null ? serviceGoods.toString() : "null"));
//派单模式
Integer dispatchtype=serviceGoods.getDispatchtype();
if (dispatchtype==null){
dispatchtype=1;
}
// 商品名、图片、类型、价格等
String productName = "";
if (serviceGoods != null) {
productName = serviceGoods.getTitle();
System.out.println("商品名称: " + productName);
}
order.setProductName(productName);
order.setSku(payBefor.getSku());
order.setTotalPrice(payBefor.getAllmoney());
order.setBigtype(3);
order.setPayPrice(payBefor.getWxmoney());
order.setCreateTime(new Date());
order.setType(1); // 服务订单
order.setCreateType(1); // 用户自主下单
order.setUname(user.getName());
//20250809处理过的一个故障
order.setPayPrice(payBefor.getAllmoney());
order.setReceiveType(Long.valueOf(dispatchtype)); // 自由抢单
// 预约时间
System.out.println("预约时间: " + payBefor.getMaketime());
if (payBefor.getMaketime() != null && !payBefor.getMaketime().isEmpty()) {
String[] makeTimeArr = payBefor.getMaketime().split(" ");
if (makeTimeArr.length == 2) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(makeTimeArr[0]);
order.setMakeTime(date.getTime() / 1000);
order.setMakeHour(makeTimeArr[1]);
} catch (Exception e) {
// 忽略解析异常
}
}
}
System.out.println("地址ID: " + payBefor.getAddressid());
if (payBefor.getAddressid() != null) {
IUserAddressService userAddressService = SpringUtils.getBean(IUserAddressService.class);
UserAddress userAddress = userAddressService.selectUserAddressById(payBefor.getAddressid());
System.out.println("查询到的地址信息: " + (userAddress != null ? userAddress.toString() : "null"));
if (userAddress != null) {
order.setAddressId(userAddress.getId());
order.setName(userAddress.getName());
order.setPhone(userAddress.getPhone());
order.setAddress(userAddress.getAddressInfo());
System.out.println("地址信息设置完成");
}
}
// 可补充其它字段,如拼团价、优惠券、备注等
System.out.println("开始插入订单");
int orderInsertResult = orderService.insertOrder(order);
System.out.println("订单插入结果: " + orderInsertResult + ", 订单ID: " + order.getId());
// 添加订单日志
System.out.println("添加订单日志");
IOrderLogService orderLogService = SpringUtils.getBean(IOrderLogService.class);
//IOrderService orderService = SpringUtils.getBean(IOrderService.class);
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("订单生成");
orderLog.setType(new BigDecimal("1.0"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "订单创建成功,待成团");
orderLog.setContent(jsonObject.toJSONString());
int logInsertResult = orderLogService.insertOrderLog(orderLog);
System.out.println("订单日志插入结果: " + logInsertResult);
//第二步修改拼团时候的状态
System.out.println("=== 第二步:修改拼团状态 ===");
IUserGroupBuyingService userGroupBuyingService = SpringUtils.getBean(IUserGroupBuyingService.class);
UserGroupBuying userGroupBuying = userGroupBuyingService.selectUserGroupBuyingByptorderid(ptorderid);
System.out.println("查询到的拼团记录: " + (userGroupBuying != null ? userGroupBuying.toString() : "null"));
if (userGroupBuying != null){
System.out.println("更新拼团状态");
userGroupBuying.setStatus(1L);
userGroupBuying.setPaystatus(1L);
int groupUpdateResult = userGroupBuyingService.updateUserGroupBuying(userGroupBuying);
System.out.println("拼团状态更新结果: " + groupUpdateResult);
} else {
System.out.println("未找到拼团记录");
}
//第三步核验团数据,如果满足条件都修改为待预约
System.out.println("=== 第三步:核验团数据 ===");
System.out.println("团订单ID: " + payBefor.getGrouporderid());
System.out.println("商品拼团人数要求: " + (serviceGoods != null ? serviceGoods.getGroupnum() : "null"));
UserGroupBuying userGroupBuyingData = new UserGroupBuying();
userGroupBuyingData.setOrderid(payBefor.getGrouporderid());
userGroupBuyingData.setPaystatus(1L);
userGroupBuyingData.setStatus(1L);
List<UserGroupBuying> userGroupBuyingList = userGroupBuyingService.selectUserGroupBuyingList(userGroupBuyingData);
System.out.println("已支付的拼团人数: " + (userGroupBuyingList != null ? userGroupBuyingList.size() : 0));
if (userGroupBuyingList != null && serviceGoods != null && userGroupBuyingList.size() >= serviceGoods.getGroupnum()) {
System.out.println("拼团人数已满足要求,开始更新所有拼团订单状态");
for (UserGroupBuying groupBuying1 : userGroupBuyingList) {
System.out.println("更新拼团记录 - ID: " + groupBuying1.getId() + ", 订单ID: " + groupBuying1.getPtorderid());
groupBuying1.setStatus(2L);
groupBuying1.setPaystatus(1L);
int groupUpdateResult = userGroupBuyingService.updateUserGroupBuying(groupBuying1);
System.out.println("拼团记录更新结果: " + groupUpdateResult);
Order orderdata = orderService.selectOrderByOrderId(groupBuying1.getPtorderid());
System.out.println("查询到的订单: " + (orderdata != null ? orderdata.getOrderId() : "null"));
if (orderdata != null) {
System.out.println("更新订单状态为已成团待预约");
orderdata.setStatus(10L);//已成团待预约
int orderUpdateResult = orderService.updateOrder(orderdata);
System.out.println("订单状态更新结果: " + orderUpdateResult);
}
}
System.out.println("拼团成功,所有订单状态已更新");
}
System.out.println("拼团订单处理完成返回order: " + order.getOrderId());
//派单效验
dispatchOrderCheck(order);
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"拼团订单支付","拼团订单支付成功");
//库存及销量变更
// updateInventoryAndSales(ptorderid, 1);
return order;
} else { // 其他类型
System.out.println("=== 处理其他类型订单 ===");
System.out.println("订单ID: " + payBefor.getOrderid());
// 只更新订单状态为待预约假设为1
if (payBefor.getOrderid() != null) {
if (type == 2){
System.out.println("处理次卡订单");
IUserUseSecondaryCardService userUseSecondaryCardService = SpringUtils.getBean(IUserUseSecondaryCardService.class);
UserUseSecondaryCard userUseSecondaryCard = userUseSecondaryCardService.selectUserUseSecondaryCardByorderId(payBefor.getOrderid());
System.out.println("查询到的次卡记录: " + (userUseSecondaryCard != null ? userUseSecondaryCard.toString() : "null"));
if (userUseSecondaryCard != null){
System.out.println("更新次卡状态");
userUseSecondaryCard.setStatus(1L);
int cardUpdateResult = userUseSecondaryCardService.updateUserUseSecondaryCard(userUseSecondaryCard);
System.out.println("次卡状态更新结果: " + cardUpdateResult);
} else {
Order order = orderService.selectOrderByOrderId(payBefor.getOrderid());
System.out.println("添加订单日志");
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("订单支付");
orderLog.setType(new BigDecimal("1.1"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "一口价订单支付成功,待派单");
orderLog.setContent(jsonObject.toJSONString());
int logInsertResult = orderLogService.insertOrderLog(orderLog);
if (logInsertResult>0){
DispatchUtil.dispatchOrder(order.getId());
}
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
order.setStatus(1L); // 1=待预约
int orderUpdateResult = orderService.updateOrder(order);
dispatchOrderCheck(order);
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"次卡下单","次卡下单成功");
return order;
}
System.out.println("次卡订单处理完成,返回: " + (userUseSecondaryCard != null ? userUseSecondaryCard.getId() : "null"));
return userUseSecondaryCard;
}else{
System.out.println("处理普通订单");
Order order = orderService.selectOrderByOrderId(payBefor.getOrderid());
System.out.println("查询到的订单: " + (order != null ? order.toString() : "null"));
if (order != null) {
System.out.println("添加订单日志");
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("订单支付");
orderLog.setType(new BigDecimal("1.1"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "订单支付成功,待派单");
orderLog.setContent(jsonObject.toJSONString());
int logInsertResult = orderLogService.insertOrderLog(orderLog);
if (logInsertResult>0){
DispatchUtil.dispatchOrder(order.getId());
}
System.out.println("订单日志插入结果: " + logInsertResult);
System.out.println("更新订单状态为待派单");
order.setPayPrice(order.getPayPrice().add(payBefor.getAllmoney()));
order.setStatus(1L); // 1=待预约
int orderUpdateResult = orderService.updateOrder(order);
System.out.println("订单状态更新结果: " + orderUpdateResult);
System.out.println("普通订单处理完成返回order: " + order.getOrderId());
dispatchOrderCheck(order);
WXsendMsgUtil.sendUserForMoneySuccess(user.getOpenid(),payBefor.getOrderid(),payBefor.getAllmoney().toString(),order.getAddress(),"预约下单","预约下单成功");
return order;
} else {
System.out.println("未找到订单");
}
}
} else {
System.out.println("订单ID为空无法处理");
}
System.out.println("其他类型订单处理失败返回null");
return null;
}
}
/**
* 核验拼团订单
* @param orderId 主订单号
* @param uid 用户ID
* @return 处理结果 true=拼团成功 false=未成团
*/
public static boolean verifyGroupOrder(String orderId, Long uid) {
IUserGroupBuyingService userGroupBuyingService = SpringUtils.getBean(IUserGroupBuyingService.class);
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
// 1. 查询拼团记录
UserGroupBuying query = new UserGroupBuying();
query.setOrderid(orderId);
query.setUid(uid);
List<UserGroupBuying> groupList = userGroupBuyingService.selectUserGroupBuyingList(query);
if (groupList == null || groupList.isEmpty()) {
return false;
}
UserGroupBuying group = groupList.get(0);
// 2. 设置paystatus=1
group.setPaystatus(1L);
userGroupBuyingService.updateUserGroupBuying(group);
// 3. 查询服务详情
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(group.getProductId());
if (serviceGoods == null) {
return false;
}
Integer groupNum = serviceGoods.getGroupnum();
if (groupNum == null || groupNum <= 0) {
return false;
}
// 4. 统计已支付人数
UserGroupBuying paidQuery = new UserGroupBuying();
paidQuery.setOrderid(orderId);
paidQuery.setPaystatus(1L);
List<UserGroupBuying> paidList = userGroupBuyingService.selectUserGroupBuyingList(paidQuery);
int paidCount = paidList != null ? paidList.size() : 0;
// 5. 如果已支付人数达到拼团人数,更新订单状态
if (paidCount >= groupNum) {
// 查询所有mainOrderId=orderId的订单
Order orderQuery = new Order();
orderQuery.setMainOrderId(orderId);
List<Order> orderList = orderService.selectOrderList(orderQuery);
if (orderList != null) {
for (Order o : orderList) {
o.setStatus(1L); // 1=待预约
orderService.updateOrder(o);
}
}
return true;
}
return false;
}
/**
* 用户付款后回调中修改订单状态的辅助方法
* 逻辑如果用户付款的时候查询paynum=0没有可付款的数据
* 且订单最新状态大于等于6师傅已完成那么就修改订单为已完成状态
*
* @param orderid 订单ID
* @return 剩余可付款数量
*/
public static int ISTOPAYSIZE(String orderid) {
try {
IUsersPayBeforService usersPayBeforService = SpringUtils.getBean(IUsersPayBeforService.class);
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
// 1. 查询剩余可付款数量
int paynum = usersPayBeforService.countByLastOrderIdAndStatus(orderid);
System.out.println("订单 " + orderid + " 剩余可付款数量: " + paynum);
// 2. 查询订单信息
Order order = orderService.selectOrderByOrderId(orderid);
if (order == null) {
System.err.println("未找到订单信息orderid: " + orderid);
return paynum;
}
// 3. 查询订单最新日志
OrderLog orderLog = orderLogService.selectDataTheFirstNew(order.getId());
if (orderLog == null) {
System.err.println("未找到订单最新日志orderid: " + orderid);
return paynum;
}
// 4. 判断订单最新状态是否大于等于6师傅已完成
BigDecimal latestLogType = orderLog.getType();
boolean isWorkerCompleted = latestLogType != null && latestLogType.compareTo(new BigDecimal("6")) >= 0;
System.out.println("订单 " + orderid + " 最新日志类型: " + latestLogType + ", 师傅是否已完成: " + isWorkerCompleted);
// 5. 如果paynum=0且师傅已完成则修改订单为已完成状态
if (paynum <= 0 && isWorkerCompleted) {
System.out.println("订单 " + orderid + " 满足完成条件:无剩余付款且师傅已完成,开始修改订单状态");
// 修改订单状态为已完成
order.setStatus(4L); // 4已完成
order.setReceiveType(3L); // 3完成类型
order.setJsonStatus(9); // 9已完成
order.setLogJson("{\"type\":8}"); // 8完成状态
int updateResult = orderService.updateOrder(order);
System.out.println("订单状态更新结果: " + updateResult);
// 处理师傅佣金
if (order.getWorkerId() != null) {
Users worker = usersService.selectUsersById(order.getWorkerId());
if (worker != null) {
JSONObject commissionResult = WorkerCommissionUtil.calculateCompleteWorkerCommission(order.getId());
// WorkerCommissionUtil.processWorkerCommission(order, worker);
System.out.println("师傅佣金处理完成师傅ID: " + order.getWorkerId());
}
}
// // 处理用户通知(可选)
// if (order.getUid() != null) {
// Users user = usersService.selectUsersById(order.getUid());
// if (user != null) {
// // 这里可以添加微信通知等逻辑
// // ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
// // WXsendMsgUtil.sendWorkerFinishOrder(user.getOpenid(), order, serviceGoods);
// System.out.println("用户通知处理完成用户ID: " + order.getUid());
// }
// }
System.out.println("订单 " + orderid + " 状态修改为已完成");
}
// else {
// System.out.println("订单 " + orderid + " 不满足完成条件:剩余付款数量=" + paynum + ", 师傅是否已完成=" + isWorkerCompleted);
//
// // 如果还有剩余付款,但师傅已完成,可以设置为待付款状态
// if (paynum > 0 && isWorkerCompleted) {
// order.setStatus(6L); // 6待付款
// order.setJsonStatus(9); // 9已完成
// int updateResult = orderService.updateOrder(order);
// System.out.println("订单状态更新为待付款,更新结果: " + updateResult);
// }
// }
return paynum;
} catch (Exception e) {
System.err.println("ISTOPAYSIZE方法执行异常orderid: " + orderid + ", 错误: " + e.getMessage());
e.printStackTrace();
return 0;
}
}
public static int addgoodsorderlog(Long oid,String orderId,String title,String type,JSONObject content,Long ordertype) {
OrderLog orderLog = new OrderLog();
orderLog.setOid(oid);
orderLog.setOrderId(orderId);
orderLog.setTitle( title);
orderLog.setContent(content.toJSONString());
orderLog.setType(new BigDecimal(type));
orderLog.setOrdertype(ordertype);
orderLogService.insertOrderLog(orderLog);
return 1;
}
/**
* 派单效验方法
* @param order 订单对象,需包含 productId
* @return 处理结果Map包含派单方式、绑定工人等信息
*/
public static Map<String, Object> dispatchOrderCheck(Order order) {
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
Map<String, Object> result = new HashMap<>();
if (order == null || order.getProductId() == null) {
result.put("success", false);
result.put("msg", "订单或商品ID为空");
return result;
}
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
IOrderLogService orderLogService = SpringUtils.getBean(IOrderLogService.class);
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (serviceGoods == null) {
result.put("success", false);
result.put("msg", "未找到对应服务商品");
return result;
}
if(order.getOdertype()==4){
return result;
}
Integer dispatchType = serviceGoods.getDispatchtype();
result.put("dispatchtype", dispatchType);
if (dispatchType != null && dispatchType == 3) {
// 指定工人派单
String workerIdsStr = serviceGoods.getWorkerids();
result.put("workerids", workerIdsStr);
if (workerIdsStr != null) {
Users users = usersService.selectUsersById(Long.valueOf(workerIdsStr));
order.setStatus(1L);
order.setFirstWorkerId(users.getId());
// order.setIsAccept(1);
order.setWorkerPhone(users.getPhone());
order.setWorkerId(users.getId());
int orderUpdateResult = orderService.updateOrder(order);
// 添加订单日志
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("订单支付成功");
orderLog.setType(new BigDecimal("1.0"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "一口价订单支付成功,待服务,师傅"+users.getName());
orderLog.setContent(jsonObject.toJSONString());
int logInsertResult = orderLogService.insertOrderLog(orderLog);
return result;
} else {
result.put("success", false);
result.put("msg", "服务未配置指定工人");
return result;
}
}
// 智能派单 - 调用DispatchUtil进行智能派单
try {
System.out.println("【OrderUtil】开始智能派单订单ID: " + order.getId());
DispatchUtil.DispatchResult dispatchResult = DispatchUtil.dispatchOrder(order.getId());
if (dispatchResult.isSuccess()) {
Users selectedWorker = dispatchResult.getWorker();
System.out.println("【OrderUtil】智能派单成功选中师傅: " + selectedWorker.getName());
// 更新订单状态和师傅信息
order.setStatus(1L); // 待服务
order.setWorkerId(selectedWorker.getId());
order.setWorkerPhone(selectedWorker.getPhone());
orderService.updateOrder(order);
// 添加订单日志
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("智能派单成功");
orderLog.setType(new BigDecimal("1.0"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "智能派单成功,师傅: " + selectedWorker.getName());
orderLog.setContent(jsonObject.toJSONString());
orderLogService.insertOrderLog(orderLog);
result.put("success", true);
result.put("msg", "智能派单成功,师傅: " + selectedWorker.getName());
result.put("workerId", selectedWorker.getId());
result.put("workerName", selectedWorker.getName());
result.put("workerPhone", selectedWorker.getPhone());
} else {
System.out.println("【OrderUtil】智能派单失败: " + dispatchResult.getMessage());
result.put("success", false);
result.put("msg", "智能派单失败: " + dispatchResult.getMessage());
}
} catch (Exception e) {
System.out.println("【OrderUtil】智能派单异常: " + e.getMessage());
e.printStackTrace();
result.put("success", false);
result.put("msg", "智能派单异常: " + e.getMessage());
}
return result;
}
/**
* 获取维修订单派单师傅列表
* @param orderId 订单id
* @return 符合条件的师傅列表
*/
public static List<Users> getDispatchWorkerList(Long orderId) {
IUsersService usersService = SpringUtils.getBean(IUsersService.class);
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
IUserAddressService userAddressService = SpringUtils.getBean(IUserAddressService.class);
List<Users> result = new ArrayList<>();
// 2. 查询订单、服务、地址
Order order = orderService.selectOrderById(orderId);
if (order == null) return result;
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (serviceGoods == null) return result;
UserAddress address = userAddressService.selectUserAddressById(order.getAddressId());
if (address == null) return result;
// 服务技能要求
List<String> requiredSkills = new ArrayList<>();
if (serviceGoods.getSkillIds() != null && !serviceGoods.getSkillIds().trim().isEmpty()) {
requiredSkills = JSONArray.parseArray(serviceGoods.getSkillIds(), String.class);
}
// 1. 查找当日签到过的师傅type=2is_stop=0worker_time为当天
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
Users query = new Users();
query.setType("2");
query.setWorkerTimeStr(today);
query.setSkillArr(requiredSkills);
query.setIsStop(0);
List<Users> signedWorkers = usersService.selectUsersList(query);
if (signedWorkers.isEmpty()) return result;
// 3. 逐个师傅筛选技能和服务区域
for (Users worker : signedWorkers) {
// // 技能匹配
// boolean skillMatch = false;
// if (worker.getSkillIds() != null && !worker.getSkillIds().trim().isEmpty() && !requiredSkills.isEmpty()) {
// List<String> workerSkills = com.alibaba.fastjson.JSONArray.parseArray(worker.getSkillIds(), String.class);
// for (String s : requiredSkills) {
// if (workerSkills.contains(s)) {
// skillMatch = true;
// break;
// }
// }
// }
// if (!skillMatch) continue;
// // 区域匹配
// boolean areaMatch = false;
// // 假设addressInfo字段中包含城市ID如有cityId字段请替换
// String addressCityId = null;
// if (address.getAddressInfo() != null) {
// addressCityId = address.getAddressInfo(); // 这里请根据实际情况提取城市ID
// }
// if (worker.getServiceCityIds() != null && !worker.getServiceCityIds().trim().isEmpty() && addressCityId != null) {
// List<String> workerAreas = com.alibaba.fastjson.JSONArray.parseArray(worker.getServiceCityIds(), String.class);
// if (workerAreas.contains(addressCityId)) {
// areaMatch = true;
// }
// }
// if (!areaMatch) continue;
result.add(worker);
}
// 排序:先按等级降序,再按质保金降序
result.sort((a, b) -> {
int levelA = a.getLevel() != null ? a.getLevel() : 0;
int levelB = b.getLevel() != null ? b.getLevel() : 0;
int cmp = Integer.compare(levelB, levelA);
if (cmp != 0) return cmp;
BigDecimal marginA = a.getMargin() != null ? a.getMargin() : BigDecimal.ZERO;
BigDecimal marginB = b.getMargin() != null ? b.getMargin() : BigDecimal.ZERO;
return marginB.compareTo(marginA);
});
return result;
}
/**
* 库存及销量变更
* 根据订单ID更新商品/服务的销量和库存
*
* @param orderid 订单ID
* @param type 商品类型 1=服务类商品 2=商城类商品
* @return 处理结果成功返回true失败返回false
*/
/**
* 库存及销量变更方法
* 根据订单ID更新商品/服务的销量和库存
*
* @param orderid 订单ID
* @param type 商品类型1-服务类商品2-商城类商品
* @return 处理结果成功返回true失败返回false
*/
public static boolean updateInventoryAndSales(String orderid, Integer type) {
try {
// 参数验证
if (orderid == null || orderid.trim().isEmpty()) {
System.err.println("订单ID不能为空");
return false;
}
if (type == null || (type != 1 && type != 2)) {
System.err.println("无效的商品类型type: " + type + ", orderid: " + orderid);
return false;
}
// 1. 根据type查询订单数据
Object order = null;
if (type == 1) {
// 服务类商品调用IOrderService查询订单数据
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
order = orderService.selectOrderByOrderId(orderid);
} else if (type == 2) {
// 商城类商品调用IGoodsOrderService查询订单数据
IGoodsOrderService goodsOrderService = SpringUtils.getBean(IGoodsOrderService.class);
order = goodsOrderService.selectGoodsOrderByorderId(orderid);
}
if (order == null) {
System.err.println("未找到订单数据orderid: " + orderid + ", type: " + type);
return false;
}
// 2. 提取订单信息
IServiceGoodsService serviceGoodsService = SpringUtils.getBean(IServiceGoodsService.class);
Long productId = null;
Long orderNum = null;
String orderSku = null;
if (type == 1) {
// 服务类商品
Order serviceOrder = (Order) order;
productId = serviceOrder.getProductId();
orderNum = serviceOrder.getNum() != null ? serviceOrder.getNum() : 1L;
orderSku = serviceOrder.getSku();
} else if (type == 2) {
// 商城类商品
GoodsOrder goodsOrder = (GoodsOrder) order;
productId = goodsOrder.getProductId();
orderNum = goodsOrder.getNum() != null ? goodsOrder.getNum() : 1L;
orderSku = goodsOrder.getSku();
}
// 验证商品ID
if (productId == null) {
System.err.println("订单商品ID为空orderid: " + orderid + ", type: " + type);
return false;
}
// 3. 查询商品/服务数据
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId);
if (serviceGoods == null) {
System.err.println("未找到商品/服务数据productId: " + productId + ", type: " + type);
return false;
}
// 4. 增加销量无论是否有SKU都要增加销量
Long currentSales = serviceGoods.getSales() != null ? serviceGoods.getSales() : 0L;
serviceGoods.setSales(currentSales + orderNum);
System.out.println("销量更新商品ID: " + serviceGoods.getId() +
", 原销量: " + currentSales + ", 增加销量: " + orderNum +
", 新销量: " + serviceGoods.getSales());
// 5. 更新库存
updateStock(serviceGoods, orderSku, orderNum, type);
// 6. 保存更新后的商品/服务数据
int updateResult = serviceGoodsService.updateServiceGoods(serviceGoods);
if (updateResult > 0) {
System.out.println("库存及销量更新成功orderid: " + orderid +
", type: " + type + ", 销量增加: " + orderNum + ", 商品ID: " + serviceGoods.getId());
return true;
} else {
System.err.println("库存及销量更新失败orderid: " + orderid + ", type: " + type);
return false;
}
} catch (Exception e) {
System.err.println("库存及销量变更异常orderid: " + orderid + ", type: " + type + ", 错误: " + e.getMessage());
e.printStackTrace();
return false;
}
}
/**
* 库存及销量变更(兼容旧版本)
* 根据订单ID更新商品/服务的销量和库存,默认为服务类商品
*
* @param orderid 订单ID
* @return 处理结果成功返回true失败返回false
*/
// public static boolean updateInventoryAndSales(String orderid) {
//// return updateInventoryAndSales(orderid, 1); // 默认为服务类商品
// }
/**
* 更新库存逻辑
*
* @param serviceGoods 商品/服务对象
* @param orderSku 订单SKU
* @param orderNum 订单数量
* @param type 商品类型1-服务类商品2-商城类商品
*/
private static void updateStock(ServiceGoods serviceGoods, String orderSku, Long orderNum, Integer type) {
try {
// 参数验证
if (serviceGoods == null) {
System.err.println("商品对象为空,无法更新库存");
return;
}
if (orderNum == null || orderNum <= 0) {
System.err.println("订单数量无效orderNum: " + orderNum);
return;
}
// 如果订单的sku为空或null直接扣减ServiceGoods的库存
if (orderSku == null || orderSku.trim().isEmpty()) {
Long currentStock = serviceGoods.getStock() != null ? serviceGoods.getStock() : 0L;
Long newStock = Math.max(0, currentStock - orderNum); // 确保库存不为负数
serviceGoods.setStock(newStock);
System.out.println("直接扣减库存商品ID: " + serviceGoods.getId() +
", 原库存: " + currentStock + ", 扣减数量: " + orderNum +
", 剩余库存: " + newStock);
} else {
// 根据商品类型选择不同的SKU更新方法
if (type == 1) {
// 服务类商品使用原有的SKU更新逻辑
updateSkuStock(serviceGoods, orderSku, orderNum);
} else if (type == 2) {
// 商城类商品使用新的SKU更新逻辑
updateGoodsSkuStock(serviceGoods, orderSku, orderNum);
} else {
System.err.println("无效的商品类型type: " + type);
}
}
} catch (Exception e) {
System.err.println("更新库存异常商品ID: " + (serviceGoods != null ? serviceGoods.getId() : "null") +
", 错误: " + e.getMessage());
}
}
/**
* 更新SKU库存
*
* @param serviceGoods 商品/服务对象
* @param orderSku 订单SKU具体规格选择
* @param orderNum 订单数量
*/
private static void updateSkuStock(ServiceGoods serviceGoods, String orderSku, Long orderNum) {
try {
// 参数验证
if (serviceGoods == null) {
System.err.println("商品对象为空无法更新SKU库存");
return;
}
if (orderSku == null || orderSku.trim().isEmpty()) {
System.err.println("订单SKU为空无法更新SKU库存");
return;
}
String serviceSku = serviceGoods.getSku();
if (serviceSku == null || serviceSku.trim().isEmpty()) {
System.err.println("商品SKU为空无法更新SKU库存商品ID: " + serviceGoods.getId());
return;
}
// 解析ServiceGoods的SKU JSON复杂多规格格式
JSONObject skuJson;
try {
skuJson = JSONObject.parseObject(serviceSku);
} catch (Exception e) {
System.err.println("商品SKU JSON格式错误商品ID: " + serviceGoods.getId() + ", SKU: " + serviceSku);
return;
}
// 检查是否是复杂多规格格式
if (!skuJson.containsKey("sku") || !skuJson.containsKey("type")) {
System.err.println("商品SKU格式不是多规格格式商品ID: " + serviceGoods.getId());
return;
}
// 获取sku数组
JSONArray skuArray = skuJson.getJSONArray("sku");
if (skuArray == null || skuArray.isEmpty()) {
System.err.println("商品SKU数组为空商品ID: " + serviceGoods.getId());
return;
}
// 解析订单SKU具体规格选择
JSONObject orderSkuJson;
try {
orderSkuJson = JSONObject.parseObject(orderSku);
} catch (Exception e) {
System.err.println("订单SKU JSON格式错误订单SKU: " + orderSku);
return;
}
// 在sku数组中查找匹配的规格
boolean found = false;
for (int i = 0; i < skuArray.size(); i++) {
JSONObject skuItem = skuArray.getJSONObject(i);
// 检查是否匹配订单SKU的所有属性
if (isSkuMatch(skuItem, orderSkuJson)) {
// 找到匹配的SKU更新库存
String stockStr = skuItem.getString("stock");
if (stockStr != null && !stockStr.trim().isEmpty()) {
try {
Long currentStock = Long.parseLong(stockStr);
Long newStock = Math.max(0, currentStock - orderNum); // 确保库存不为负数
skuItem.put("stock", newStock.toString());
// 更新ServiceGoods的sku字段
serviceGoods.setSku(skuJson.toJSONString());
System.out.println("SKU库存更新成功商品ID: " + serviceGoods.getId() +
", 订单SKU: " + orderSku + ", 原库存: " + currentStock +
", 扣减数量: " + orderNum + ", 剩余库存: " + newStock);
found = true;
break;
} catch (NumberFormatException e) {
System.err.println("SKU库存格式错误商品ID: " + serviceGoods.getId() +
", SKU: " + orderSku + ", 库存值: " + stockStr);
}
} else {
System.err.println("SKU库存为空商品ID: " + serviceGoods.getId() + ", SKU: " + orderSku);
}
}
}
if (!found) {
System.err.println("未找到匹配的SKU商品ID: " + serviceGoods.getId() +
", 订单SKU: " + orderSku + ", 商品SKU数组大小: " + skuArray.size());
}
} catch (Exception e) {
System.err.println("更新SKU库存异常商品ID: " + (serviceGoods != null ? serviceGoods.getId() : "null") +
", 订单SKU: " + orderSku + ", 错误: " + e.getMessage());
}
}
/**
* 更新商城商品SKU库存
*
* @param serviceGoods 商品/服务对象
* @param orderSku 订单SKU具体规格选择
* @param orderNum 订单数量
*/
private static void updateGoodsSkuStock(ServiceGoods serviceGoods, String orderSku, Long orderNum) {
try {
// 参数验证
if (serviceGoods == null) {
System.err.println("商品对象为空无法更新SKU库存");
return;
}
if (orderSku == null || orderSku.trim().isEmpty()) {
System.err.println("订单SKU为空无法更新SKU库存");
return;
}
String serviceSku = serviceGoods.getSku();
if (serviceSku == null || serviceSku.trim().isEmpty()) {
System.err.println("商品SKU为空无法更新SKU库存商品ID: " + serviceGoods.getId());
return;
}
// 解析ServiceGoods的SKU JSON商城商品格式
JSONObject skuJson;
try {
skuJson = JSONObject.parseObject(serviceSku);
} catch (Exception e) {
System.err.println("商品SKU JSON格式错误商品ID: " + serviceGoods.getId() + ", SKU: " + serviceSku);
return;
}
// 检查是否是商城商品格式
if (!skuJson.containsKey("sku") || !skuJson.containsKey("type")) {
System.err.println("商品SKU格式不是商城商品格式商品ID: " + serviceGoods.getId());
return;
}
// 获取sku数组
JSONArray skuArray = skuJson.getJSONArray("sku");
if (skuArray == null || skuArray.isEmpty()) {
System.err.println("商品SKU数组为空商品ID: " + serviceGoods.getId());
return;
}
// 解析订单SKU具体规格选择
JSONObject orderSkuJson;
try {
orderSkuJson = JSONObject.parseObject(orderSku);
} catch (Exception e) {
System.err.println("订单SKU JSON格式错误订单SKU: " + orderSku);
return;
}
// 在sku数组中查找匹配的规格
boolean found = false;
for (int i = 0; i < skuArray.size(); i++) {
JSONObject skuItem = skuArray.getJSONObject(i);
// 检查是否匹配订单SKU的"价格"属性
if (isGoodsSkuMatch(skuItem, orderSkuJson)) {
// 找到匹配的SKU更新库存
String stockStr = skuItem.getString("stock");
if (stockStr != null && !stockStr.trim().isEmpty()) {
try {
Long currentStock = Long.parseLong(stockStr);
Long newStock = Math.max(0, currentStock - orderNum); // 确保库存不为负数
skuItem.put("stock", newStock.toString());
// 更新ServiceGoods的sku字段
serviceGoods.setSku(skuJson.toJSONString());
System.out.println("商城商品SKU库存更新成功商品ID: " + serviceGoods.getId() +
", 订单SKU: " + orderSku + ", 原库存: " + currentStock +
", 扣减数量: " + orderNum + ", 剩余库存: " + newStock);
found = true;
break;
} catch (NumberFormatException e) {
System.err.println("SKU库存格式错误商品ID: " + serviceGoods.getId() +
", SKU: " + orderSku + ", 库存值: " + stockStr);
}
} else {
System.err.println("SKU库存为空商品ID: " + serviceGoods.getId() + ", SKU: " + orderSku);
}
}
}
if (!found) {
System.err.println("未找到匹配的SKU商品ID: " + serviceGoods.getId() +
", 订单SKU: " + orderSku + ", 商品SKU数组大小: " + skuArray.size());
}
} catch (Exception e) {
System.err.println("更新商城商品SKU库存异常商品ID: " + (serviceGoods != null ? serviceGoods.getId() : "null") +
", 订单SKU: " + orderSku + ", 错误: " + e.getMessage());
}
}
/**
* 检查商城商品SKU是否匹配
*
* @param skuItem 商品SKU项
* @param orderSkuJson 订单SKU JSON
* @return 是否匹配
*/
private static boolean isGoodsSkuMatch(JSONObject skuItem, JSONObject orderSkuJson) {
try {
// 参数验证
if (skuItem == null || orderSkuJson == null) {
System.err.println("商城商品SKU匹配检查参数为空");
return false;
}
// 商城商品主要根据"价格"属性进行匹配
String orderPrice = orderSkuJson.getString("价格");
String skuPrice = skuItem.getString("价格");
if (orderPrice == null || skuPrice == null) {
System.err.println("商城商品SKU价格属性为空订单价格: " + orderPrice + ", 商品价格: " + skuPrice);
return false;
}
// 如果价格属性匹配返回true
if (orderPrice.equals(skuPrice)) {
return true;
}
return false;
} catch (Exception e) {
System.err.println("商城商品SKU匹配检查异常: " + e.getMessage());
return false;
}
}
/**
* 检查SKU是否匹配
*
* @param skuItem 商品SKU项
* @param orderSkuJson 订单SKU JSON
* @return 是否匹配
*/
private static boolean isSkuMatch(JSONObject skuItem, JSONObject orderSkuJson) {
try {
// 参数验证
if (skuItem == null || orderSkuJson == null) {
System.err.println("SKU匹配检查参数为空");
return false;
}
// 定义需要跳过的非属性字段
Set<String> skipFields = new HashSet<>(Arrays.asList(
"price", "groupprice", "seckillprice", "stock", "pic", "image"
));
// 遍历订单SKU的所有属性检查是否与商品SKU项匹配
for (String key : orderSkuJson.keySet()) {
// 跳过非属性字段
if (skipFields.contains(key)) {
continue;
}
String orderValue = orderSkuJson.getString(key);
String skuValue = skuItem.getString(key);
// 如果订单SKU中的属性在商品SKU中不存在返回false
if (skuValue == null) {
System.err.println("商品SKU中缺少属性: " + key + ", 订单SKU值: " + orderValue);
return false;
}
// 如果属性值不匹配返回false
if (!orderValue.equals(skuValue)) {
System.err.println("SKU属性不匹配属性: " + key +
", 订单值: " + orderValue + ", 商品值: " + skuValue);
return false;
}
}
return true;
} catch (Exception e) {
System.err.println("SKU匹配检查异常: " + e.getMessage());
return false;
}
}
/**
* 查找用户首次下单
* 根据用户ID查找该用户首次下单的订单ID
*
* @param userId 用户ID
* @return 首次下单的订单ID如果没有找到返回null
*/
public static String findUserFirstOrderId(Long userId) {
try {
if (userId == null) {
System.err.println("用户ID不能为空");
return null;
}
IOrderService orderService = SpringUtils.getBean(IOrderService.class);
String firstOrderId = orderService.selectUserFirstOrderId(userId);
if (firstOrderId != null) {
System.out.println("用户 " + userId + " 首次下单订单ID: " + firstOrderId);
} else {
System.out.println("用户 " + userId + " 没有找到首次下单记录");
}
return firstOrderId;
} catch (Exception e) {
System.err.println("查找用户首次下单异常用户ID: " + userId + ", 错误: " + e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 查找用户首次下单(重载方法,支持用户对象)
* 根据用户对象查找该用户首次下单的订单ID
*
* @param user 用户对象
* @return 首次下单的订单ID如果没有找到返回null
*/
public static String findUserFirstOrderId(Users user) {
if (user == null || user.getId() == null) {
System.err.println("用户对象或用户ID为空");
return null;
}
return findUserFirstOrderId(user.getId());
}
// public static void main(String[] args) {
// // 构造一个测试用的json字符串
// String testJson = "{\"project\":{\"name\":\"项目费用\",\"price\":1132.00},\"reduction\":{\"name\":\"优惠金额\",\"price\":\"1\"},\"deposit\":{\"name\":\"定金\",\"price\":\"10\"},\"basic\":[{\"name\":\"测试基建2\",\"select\":true},{\"name\":\"测试基建5\",\"select\":true},{\"name\":\"测试基建8\",\"select\":true}],\"craft\":[{\"name\":\"三挂一方柜\",\"price\":\"336.00\",\"pid\":192,\"id\":1889,\"count\":3}],\"material\":[{\"name\":\"其他辅料面议项\",\"price\":\"1.00\",\"id\":1241,\"pid\":93,\"count\":1},{\"name\":\"除味剂\",\"price\":\"28.00\",\"id\":1240,\"pid\":93,\"count\":1},{\"name\":\"除味剂\",\"price\":\"28.00\",\"id\":1196,\"pid\":93,\"count\":1},{\"name\":\"其他辅料面议项\",\"price\":\"1.00\",\"id\":1197,\"pid\":93,\"count\":1},{\"name\":\"其他辅料面议项\",\"price\":\"1.00\",\"id\":1197,\"pid\":92,\"count\":1},{\"name\":\"111\",\"price\":\"10.00\",\"id\":1250,\"pid\":92,\"count\":1},{\"name\":\"除味剂\",\"price\":\"28.00\",\"id\":1196,\"pid\":92,\"count\":2}]}";
// OrderUtil util = new OrderUtil();
// JSONObject result = util.getbaojiajson(testJson);
// System.out.println("处理后的结果: " + result.toJSONString());
//
// // 测试库存及销量变更方法
// System.out.println("=== 测试库存及销量变更方法 ===");
//
// // 测试服务类商品type=1
// String serviceOrderId = "TEST_SERVICE_ORDER_001";
// boolean serviceResult = updateInventoryAndSales(serviceOrderId, 1);
// System.out.println("服务类商品库存及销量变更测试结果: " + serviceResult);
//
// // 测试商城类商品type=2
// String goodsOrderId = "TEST_GOODS_ORDER_001";
// boolean goodsResult = updateInventoryAndSales(goodsOrderId, 2);
// System.out.println("商城类商品库存及销量变更测试结果: " + goodsResult);
//
// // 测试兼容旧版本(默认为服务类商品)
// String orderId = "TEST_ORDER_001";
// boolean result2 = updateInventoryAndSales(orderId);
// System.out.println("兼容旧版本库存及销量变更测试结果: " + result2);
//
// // 测试SKU匹配逻辑
// System.out.println("=== 测试SKU匹配逻辑 ===");
// String testOrderSku = "{\"颜色\":\"黑\",\"大小\":\"小\",\"尺寸\":\"300*300\",\"pic\":[\"https://img.huafurenjia.cn/images/2025-07-15/c638e39be08941aaaa47ee926a1ac5e5.png\"],\"price\":\"100\",\"groupprice\":\"100\",\"seckillprice\":\"99\",\"stock\":\"100\"}";
// JSONObject orderSkuJson = JSONObject.parseObject(testOrderSku);
//
// // 模拟一个SKU项进行匹配测试
// JSONObject testSkuItem = new JSONObject();
// testSkuItem.put("颜色", "黑");
// testSkuItem.put("大小", "小");
// testSkuItem.put("尺寸", "300*300");
// testSkuItem.put("price", "100");
// testSkuItem.put("stock", "100");
//
// boolean matchResult = isSkuMatch(testSkuItem, orderSkuJson);
// System.out.println("SKU匹配测试结果: " + matchResult);
// }
}