javacodeadmin/ruoyi-system/src/main/java/com/ruoyi/system/controller/AppleOrderController.java

6065 lines
285 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.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
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.enums.BusinessType;
import com.ruoyi.system.ControllerUtil.*;
import com.ruoyi.system.ControllerUtil.CartOrderUtil;
import com.ruoyi.system.ControllerUtil.AppletLoginUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.StringUtils;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Calendar;
import java.util.stream.Collectors;
import java.io.File;
import com.ruoyi.system.service.IShopAddressService;
import com.ruoyi.system.domain.ShopAddress;
import com.ruoyi.system.domain.GoodsCart;
import com.ruoyi.system.service.IGoodsCartService;
import com.ruoyi.system.service.IQuoteMaterialTypeService;
import com.ruoyi.system.service.IQuoteMaterialService;
import com.ruoyi.system.service.IOrderSoundService;
import com.ruoyi.system.domain.OrderSound;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.service.IOrderSoundLogService;
import com.ruoyi.system.domain.OrderSoundLog;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.utils.FFmpegUtilsSimple;
/**
* 苹果订单控制器
*
* @author ruoyi
* @date 2025-01-26
*/
@RestController
public class AppleOrderController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(AppleOrderController.class);
@Autowired
private IUsersService usersService;
@Autowired
private IServiceGoodsService serviceGoodsService;
@Autowired
private IUserAddressService userAddressService;
@Autowired
private ICouponUserService couponUserService;
@Autowired
private IOrderService orderService;
@Autowired
private IUserUseSecondaryCardService userUseSecondaryCardService;
@Autowired
private IContentService contentService;
@Autowired
private IUserGroupBuyingService userGroupBuyingService;
@Autowired
private IUsersPayBeforService usersPayBeforService;
@Autowired
private IOrderLogService orderLogService;
@Autowired
private IUserSecondaryCardService userSecondaryCardService;
@Autowired
private ISiteConfigService siteConfigService;
@Autowired
private ICouponsService couponsService;
@Autowired
private IServiceCateService serviceCateService;
@Autowired
private IShopAddressService shopAddressService;
@Autowired
private IGoodsOrderService goodsOrderService;
@Autowired
private IGoodsCartService goodsCartService;
@Autowired
private IUserDemandQuotationService userDemandQuotationService;
@Autowired
private IDiyCityService diyCityService;
@Autowired
private ISiteSkillService siteSkillService;
@Autowired
private IOrderCommentService orderCommentService;
@Autowired
private IWorkerLevelService workerLevelService;
@Autowired
private IOrderSoundService orderSoundService;
@Autowired
private IOrderSoundLogService orderSoundLogService;
// @Autowired
// private IUserGroupBuyingService userGroupBuyingService;
@Autowired
private IQuoteMaterialTypeService quoteMaterialTypeService;
@Autowired
private IQuoteMaterialService quoteMaterialService;
// 1. 注入IWorkerMoneyLogService
@Autowired
private IWorkerMoneyLogService workerMoneyLogService;
@Autowired
private IOrderReworkService orderReworkService;
/**
* 查询用户优惠券列表
*
* @param request HTTP请求对象
* @return 返回用户优惠券列表
*/
@PostMapping("/api/coupon/mypay/lst/{id}")
public AjaxResult getMyCouponList(@PathVariable("id") String id, HttpServletRequest request) {
// 3. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
UsersPayBefor usersPayBefor = usersPayBeforService.selectUsersPayBeforByOrderId(id);
if(usersPayBefor==null){
return AppletControllerUtil.appletWarning("订单不存在");
}
Long userId = user.getId(); // 获取当前用户id
int status = 1;
String productId = "";
if (usersPayBefor.getServiceid()==null){
GoodsOrder goodsOrder = new GoodsOrder();
goodsOrder.setMainOrderId( usersPayBefor.getOrderid());
List<GoodsOrder> GoodsOrderList = goodsOrderService.selectGoodsOrderList(goodsOrder);
if (!GoodsOrderList.isEmpty()){
productId = GoodsOrderList.getFirst().getProductId().toString();
}
}else{
productId = usersPayBefor.getServiceid().toString();
}
BigDecimal totalPrice = usersPayBefor.getAllmoney();
// 过期的优惠券标记为已过期
CouponUser couponUser = new CouponUser();
couponUser.setStatus(1L);
couponUser.setUid(user.getId());
List<CouponUser> 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<Coupons> 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<CouponUser> couponUserDataList = couponUserService.selectCouponUserList(couponUserData);
if (couponUserDataList!=null){
return AppletControllerUtil.appletSuccess(AppletControllerUtil.buildCouponUserList(couponUserDataList,serviceCateService,serviceGoodsService,productId,totalPrice));
}
}
// 按is_use排序
return AjaxResult.success();
}
/**
* 通用订单预支接口
*
* 创建订单但不执行支付,将订单状态设置为未支付,并在预支付表中记录支付信息
*
* @param params 预支付参数
* @param request HTTP请求对象
* @return 预支付结果
* 1=拼团 2一口价 3=秒杀 4=报价 0=普通预约(必填)
* 请求参数说明:
* - id: 产品或次卡主键ID必填
* - sku: 购买的规格(可选)
* - ordertype: 订单类别 1=拼团 2=次卡 3=秒杀 4=报价 0=普通预约(必填)
* - address_id: 地址ID可选
* - num: 购买数量可选默认1
* - make_time: 预约时间可选格式yyyy-MM-dd HH:mm
* - attachments: 附件数组可选最多9个附件
*/
@PostMapping("/api/universal/order/presupport")
@Log(title = "订单预支", businessType = BusinessType.INSERT)
public AjaxResult universalOrderPresupport(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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 (params == null || params.isEmpty()) {
return AppletControllerUtil.appletWarning("参数不能为空");
}
if (params.get("id") == null) {
return AppletControllerUtil.appletWarning("产品ID不能为空");
}
if (params.get("ordertype") == null) {
return AppletControllerUtil.appletWarning("订单类别不能为空");
}
// 3. 解析参数
Long productId = Long.valueOf(params.get("id").toString());
Integer ordertype = Integer.valueOf(params.get("ordertype").toString());
// 处理sku参数 - 可能是JSON对象或字符串
String sku = "";
if (params.get("sku") != null) {
Object skuObj = params.get("sku");
if (skuObj instanceof String) {
sku = (String) skuObj;
} else {
// 如果是JSON对象转换为JSON字符串
sku = JSONObject.toJSONString(skuObj);
}
}
// 处理address_id参数 - 避免空字符串导致的NumberFormatException
Long addressId = null;
if (params.get("address_id") != null) {
String addressIdStr = params.get("address_id").toString();
if (!addressIdStr.trim().isEmpty()) {
try {
addressId = Long.valueOf(addressIdStr);
} catch (NumberFormatException e) {
logger.warn("地址ID格式错误: " + addressIdStr);
addressId = null;
}
}
}
Integer num = params.get("num") != null ? Integer.valueOf(params.get("num").toString()) : 1;
String makeTime = params.get("make_time") != null ? params.get("make_time").toString() : "";
String grouporderid = params.get("grouporderid") != null ? params.get("grouporderid").toString() : "";
String reamk = params.get("reamk") != null ? params.get("reamk").toString() : "";
String cikaid = params.get("cikaid") != null ? params.get("cikaid").toString() : "";
if (grouporderid==""){
grouporderid=GenerateCustomCode.generCreateOrder("pt");
}
if (StringUtils.isNotBlank(cikaid)){
ordertype=2;
UserUseSecondaryCard userUseSecondaryCard = userUseSecondaryCardService.selectUserUseSecondaryCardByorderId(cikaid);
if (userUseSecondaryCard == null){
return AppletControllerUtil.appletWarning("此卡不存在");
}
if (userUseSecondaryCard.getStatus() != 1){
return AppletControllerUtil.appletWarning("此卡不是使用状态");
}
}
String ptcode=GenerateCustomCode.generCreateOrder("PT");
// 处理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<String> attachmentList = (List<String>) 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();
}
}
// 4. 验证订单类型
if (ordertype < 0 || ordertype > 4) {
return AppletControllerUtil.appletWarning("订单类别无效0=普通预约 1=拼团 2=一口价 3=秒杀 4=报价");
}
// 5. 查询商品信息
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(productId);
if (serviceGoods == null) {
return AppletControllerUtil.appletWarning("服务不存在");
}
// 6. 查询地址信息如果提供了地址ID
UserAddress userAddress = null;
if (addressId != null) {
userAddress = userAddressService.selectUserAddressById(addressId);
if (userAddress == null) {
return AppletControllerUtil.appletWarning("地址不存在");
}
}
// 根据订单类型确定是否一口价和订单类型
int isyikoujia = 2; // 默认非一口价
int priceType = ordertype; // 价格类型与订单类型一致
// 根据订单类型调整参数
switch (ordertype) {
case 0: // 普通预约 - 非一口价
isyikoujia = 2;
priceType = 1; // 使用普通价格
break;
case 1: // 拼团 - 非一口价
isyikoujia = 2;
priceType = 1; // 拼团价格
break;
case 2: // 一口价 - 一口价
isyikoujia = 1;
priceType = 2; // 一口价价格
break;
case 3: // 秒杀 - 非一口价
isyikoujia = 2;
priceType = 3; // 秒杀价格
break;
case 4: // 报价 - 非一口价
isyikoujia = 2;
priceType = 1; // 普通价格
break;
}
BigDecimal totalAmount=new BigDecimal(0);
if (ordertype != 0) {
BigDecimal money=OrderUtil.confirmOrderPrice(productId, sku, priceType);
if (money == null){
if (serviceGoods.getFixedprice() != null){
money = serviceGoods.getFixedprice();
}else{
money = serviceGoods.getPrice();
}
}
totalAmount =money.multiply(BigDecimal.valueOf(num));
}
// 7. 根据订单类型创建相应的订单
// Integer ordertype, Users user, Long productId,
// UserAddress userAddress, String sku, Integer num, String makeTime,
// String fileData,String grouporderid,String reamk,String cikaid
// BigDecimal allprice= OrderUtil.confirmOrderPrice(productId, sku, ordertype);
Map<String, Object> orderResult = AppletControllerUtil.createOrderByType(
ordertype, user, productId, userAddress, sku, num,
makeTime,fileData, grouporderid,reamk,cikaid,totalAmount,ptcode
);
if (!(Boolean) orderResult.get("success")) {
return AppletControllerUtil.appletWarning((String) orderResult.get("message"));
}
// 8. 获取订单信息
String orderId = (String) orderResult.get("orderId");
Long oid = (Long) orderResult.get("oid");
// 如果是报价订单直接返回结果不插入UsersPayBefor
//次卡订单不用支付直接走
if (ordertype == 2&&StringUtils.isNotBlank(cikaid)) {
//次卡订单需要处理的数据
UserUseSecondaryCard userUseSecondaryCard = userUseSecondaryCardService.selectUserUseSecondaryCardByorderId(cikaid);
if(userUseSecondaryCard!=null){
userUseSecondaryCard.setUsenum(userUseSecondaryCard.getUsenum()+1);
userUseSecondaryCardService.updateUserUseSecondaryCard(userUseSecondaryCard);
// if (userUseSecondaryCard.getUsenum().intValue() >= userUseSecondaryCard.getNum().intValue()){
// //次卡在这个时候就需要进行积分和购物金以的处理
// // BenefitPointsUtil.processBenefitPoints(userUseSecondaryCard.getId(), userUseSecondaryCard.getPaymoney(),"3");
// // JSONObject integralAndBenefitResult = IntegralAndBenefitUtil.processIntegralAndBenefit(totalAmount, orderId, user.getId());
// userUseSecondaryCard.setStatus(2L);//设置不可用
// userUseSecondaryCardService.updateUserUseSecondaryCard(userUseSecondaryCard);
// }
}
Map<String, Object> result = new HashMap<>();
result.put("trpe", "1");
result.put("orderid", orderId);
return AppletControllerUtil.appletSuccess(result);
}
if (ordertype == 0) {
Map<String, Object> result = new HashMap<>();
result.put("trpe", "1");
result.put("orderid", orderId);
// result.put("orderId", orderId);
// result.put("oid", oid);
// result.put("totalAmount", totalAmount);
// result.put("orderType", ordertype);
// result.put("attachments", attachments);
// Order order = orderService.selectOrderByOrderId(orderId);
// Users worker = usersService.selectUsersById(2L);
// if (order != null&&worker!=null){
// AppletControllerUtil.creatWorkerForOrder(order,worker);
// }
return AppletControllerUtil.appletSuccess(result);
}
// 9. 计算会员优惠和服务金抵扣
BigDecimal memberMoney = BigDecimal.ZERO;
BigDecimal serviceMoney = BigDecimal.ZERO;
try {
// 查询config_one配置
SiteConfig configQuery = new SiteConfig();
configQuery.setName("config_one");
List<SiteConfig> 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);
// }
// }
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(user.getId());
usersPayBefor.setOrderid(orderId);
usersPayBefor.setOid(oid);
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(Long.valueOf(serviceGoods.getType()));
usersPayBefor.setMembermoney(memberMoney);
usersPayBefor.setType(Long.valueOf(ordertype));
usersPayBefor.setSku(sku);
usersPayBefor.setNum(Long.valueOf(num));
usersPayBefor.setServiceid(productId);
usersPayBefor.setGrouporderid(grouporderid);
usersPayBefor.setAddressid(addressId);
usersPayBefor.setMaketime(makeTime);
usersPayBefor.setAttachments(fileData);
usersPayBefor.setStatus(1L); // 1=待支付
usersPayBefor.setPaytype(1L); // 默认微信支付
int payBeforResult = usersPayBeforService.insertUsersPayBefor(usersPayBefor);
if (payBeforResult <= 0) {
return AppletControllerUtil.appletWarning("预支付记录创建失败");
}
Map<String, Object> result1 = new HashMap<>();
if (ordertype == 4){
result1.put("type", "1");
}else{
result1.put("type", "2");
}
result1.put("orderid", usersPayBefor.getOrderid());
return AppletControllerUtil.appletSuccess(result1);
} catch (Exception e) {
logger.error("订单预支付创建失败:", e);
return AppletControllerUtil.appletError("订单预支付创建失败:" + e.getMessage());
}
}
/**
* 次卡购买接口
* @param params {"id":次卡id, "goodsids":["1","2",...]}
* @param request HTTP请求对象
* @return 预支付orderid
*/
@PostMapping("/api/secondary/card/buy")
public AjaxResult buySecondaryCard(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验参数
if (params == null || params.get("id") == null || params.get("goodsids") == null) {
return AppletControllerUtil.appletWarning("参数id和goodsids不能为空");
}
Long cardId = Long.valueOf(params.get("id").toString());
List<String> goodsids;
try {
goodsids = (List<String>) params.get("goodsids");
} catch (Exception e) {
return AppletControllerUtil.appletWarning("goodsids参数格式错误必须为字符串数组");
}
// 2. 获取用户
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 3. 查询次卡基本信息
UserSecondaryCard card = userSecondaryCardService.selectUserSecondaryCardById(cardId);
if (card == null) {
return AppletControllerUtil.appletWarning("次卡不存在");
}
// 4. 保存用户次卡购买记录
UserUseSecondaryCard useCard = new UserUseSecondaryCard();
useCard.setUid(user.getId());
useCard.setCarid(cardId.toString());
// goodsids存为JSON数组字符串
useCard.setGoodsids(JSONObject.toJSONString(goodsids));
useCard.setNum(card.getNum());
useCard.setUsenum(0L);
String orderid = GenerateCustomCode.generCreateOrder("CIKA");
useCard.setOrderid(orderid);
useCard.setTransactionId("");
useCard.setPaymoney(card.getRealMoney());
useCard.setStatus(4L); // 4=未支付
useCard.setRemark("");
int insertResult = userUseSecondaryCardService.insertUserUseSecondaryCard(useCard);
if (insertResult <= 0) {
return AppletControllerUtil.appletWarning("次卡购买记录保存失败");
}
// 5. 计算会员优惠和服务金抵扣
BigDecimal allMoney = card.getRealMoney();
BigDecimal memberMoney = BigDecimal.ZERO;
BigDecimal serviceMoney = BigDecimal.ZERO;
try {
SiteConfig configQuery = new SiteConfig();
configQuery.setName("config_one");
List<SiteConfig> 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) {
BigDecimal discountRate = BigDecimal.valueOf(memberDiscount).divide(BigDecimal.valueOf(100), 4, BigDecimal.ROUND_HALF_UP);
if (allMoney != null) {
memberMoney = allMoney.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) {
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;
}
// 6. 保存预支付信息,金额字段参考预支接口
UsersPayBefor payBefor = new UsersPayBefor();
payBefor.setUid(user.getId());
payBefor.setOrderid(orderid);
payBefor.setOid(useCard.getId());
payBefor.setPaycode(GenerateCustomCode.generCreateOrder("PAY"));
payBefor.setAllmoney(allMoney);
payBefor.setWxmoney(allMoney.subtract(memberMoney).subtract(serviceMoney));
payBefor.setShopmoney(BigDecimal.ZERO);
payBefor.setServicemoney(serviceMoney);
payBefor.setMtmoney(BigDecimal.ZERO);
payBefor.setYemoney(BigDecimal.ZERO);
payBefor.setCouponmoney(BigDecimal.ZERO);
payBefor.setServicetype(1L); // 2=次卡
payBefor.setMembermoney(memberMoney);
payBefor.setType(2L); // 2=次卡
payBefor.setSku("");
payBefor.setServiceid(cardId);
payBefor.setGrouporderid("");
payBefor.setAddressid(null);
payBefor.setMaketime("");
payBefor.setAttachments("");
payBefor.setStatus(1L); // 1=待支付
payBefor.setPaytype(1L); // 默认微信支付
int payBeforResult = usersPayBeforService.insertUsersPayBefor(payBefor);
if (payBeforResult <= 0) {
return AppletControllerUtil.appletWarning("预支付记录创建失败");
}
// 7. 返回orderid
Map<String, Object> result = new HashMap<>();
result.put("orderid", payBefor.getOrderid());
result.put("type", "2");
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("次卡购买失败:", e);
return AppletControllerUtil.appletError("次卡购买失败:" + e.getMessage());
}
}
/**
* 查询我的次卡列表(分页)
* @param pageNum 页码
* @param pageSize 每页数量
* @param request HTTP请求对象
* @return 我的次卡列表
*/
@GetMapping("/api/secondary/card/mylist")
public AjaxResult getMySecondaryCardList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
HttpServletRequest request) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(pageNum, pageSize);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning((String) pageValidation.get("message"));
}
// 2. 校验用户登录
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 3. 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 4. 查询用户全部次卡
UserUseSecondaryCard queryCard = new UserUseSecondaryCard();
queryCard.setUid(user.getId());
queryCard.setNostatus("1");
List<UserUseSecondaryCard> cardList = userUseSecondaryCardService.selectUserUseSecondaryCardList(queryCard);
// 5. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
for (UserUseSecondaryCard card : cardList) {
Map<String, Object> map = new HashMap<>();
// 查询次卡基本信息
UserSecondaryCard cardInfo = userSecondaryCardService.selectUserSecondaryCardById(Long.valueOf(card.getCarid()));
if (cardInfo != null) {
map.put("icon", AppletControllerUtil.buildImageUrl(cardInfo.getShowimage()));
map.put("price", cardInfo.getRealMoney());
map.put("title", cardInfo.getTitle());
if (card.getUsenum()==0){
map.put("iscanback", "1");
}else{
map.put("iscanback", "2");
}
} else {
map.put("icon", "");
map.put("price", "");
map.put("title", "");
}
map.put("num", "1");
map.put("id", card.getId());
map.put("canusenum", card.getNum());
map.put("buyTime",sdf.format(card.getCreatedAt()));
map.put("status", card.getStatus());
resultList.add(map);
}
// 6. 构建分页信息
PageInfo<UserUseSecondaryCard> pageInfo = new PageInfo<>(cardList);
// 7. 构建返回数据格式
Map<String, Object> 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/secondary/card/mylist";
responseData.put("first_page_url", baseUrl + "?pageNum=1");
responseData.put("last_page_url", baseUrl + "?pageNum=" + pageInfo.getPages());
responseData.put("next_page_url", pageInfo.isHasNextPage() ?
baseUrl + "?pageNum=" + pageInfo.getNextPage() : null);
responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
responseData.put("path", baseUrl);
// 构建links数组
List<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?pageNum=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
links.add(nextLink);
responseData.put("links", links);
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
logger.error("查询我的次卡失败:", e);
return AppletControllerUtil.appletError("查询我的次卡失败:" + e.getMessage());
}
}
/**
* 查询我的次卡列表(分页)
* @param pageNum 页码
* @param pageSize 每页数量
* @param request HTTP请求对象
* @return 我的次卡列表
*/
@GetMapping("/api/secondary/carddata/mylist")
public AjaxResult getMySecondaryCarddataList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
HttpServletRequest request) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 校验用户登录
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 查询用户全部次卡
UserUseSecondaryCard queryCard = new UserUseSecondaryCard();
queryCard.setUid(user.getId());
queryCard.setNostatus("1");
List<UserUseSecondaryCard> allCardList = userUseSecondaryCardService.selectUserUseSecondaryCardList(queryCard);
int total = allCardList.size();
int fromIndex = Math.max(0, (pageNum - 1) * pageSize);
int toIndex = Math.min(fromIndex + pageSize, total);
List<UserUseSecondaryCard> cardList = fromIndex < toIndex ? allCardList.subList(fromIndex, toIndex) : new ArrayList<>();
List<Map<String, Object>> resultList = new ArrayList<>();
for (UserUseSecondaryCard card : cardList) {
Map<String, Object> map = new HashMap<>();
// 查询次卡基本信息
UserSecondaryCard cardInfo = userSecondaryCardService.selectUserSecondaryCardById(Long.valueOf(card.getCarid()));
if (cardInfo != null) {
map.put("icon", AppletControllerUtil.buildImageUrl(cardInfo.getShowimage()));
map.put("price", cardInfo.getRealMoney());
map.put("title", cardInfo.getTitle());
if (card.getUsenum()==0){
map.put("iscanback", "1");
}else{
map.put("iscanback", "2");
}
} else {
map.put("icon", "");
map.put("price", "");
map.put("title", "");
}
map.put("num", "1");
map.put("id", card.getId());
map.put("canusenum", card.getNum());
map.put("buyTime",sdf.format(card.getCreatedAt()));
map.put("status", card.getStatus());
resultList.add(map);
}
// 6. 获取分页信息并构建响应
TableDataInfo tableDataInfo = getDataTable(resultList);
// 7. 构建符合要求的分页响应格式
Map<String, Object> pageData = PageUtil.buildPageResponse(tableDataInfo, pageNum, pageSize);
return AppletControllerUtil.appletSuccess(pageData);
// Map<String, Object> pageData = new HashMap<>();
// pageData.put("total", total);
// pageData.put("data", resultList);
// pageData.put("pageNum", pageNum);
// pageData.put("pageSize", pageSize);
// return AppletControllerUtil.appletSuccess(pageData);
} catch (Exception e) {
logger.error("查询我的次卡失败:", e);
return AppletControllerUtil.appletError("查询我的次卡失败:" + e.getMessage());
}
}
/**
* 查询我的次卡详情
* @param cardid 次卡使用记录ID
* @param request HTTP请求对象
* @return 次卡详情(卡片信息、服务预约情况、订单信息)
*/
@GetMapping("/api/secondary/card/detail")
public AjaxResult getMySecondaryCardDetail(@RequestParam("cardid") Long cardid, HttpServletRequest request) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 校验用户登录
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 1. 查次卡使用记录
UserUseSecondaryCard card = userUseSecondaryCardService.selectUserUseSecondaryCardById(cardid);
if (card == null || !user.getId().equals(card.getUid())) {
return AppletControllerUtil.appletWarning("次卡不存在或无权查看");
}
// 2. 查次卡基本信息
UserSecondaryCard cardInfo = userSecondaryCardService.selectUserSecondaryCardById(Long.valueOf(card.getCarid()));
// 3. 解析服务ID列表
List<Long> goodsIds = new ArrayList<>();
try {
List<String> goodsIdStrs = JSONArray.parseArray(card.getGoodsids(), String.class);
for (String gid : goodsIdStrs) {
goodsIds.add(Long.valueOf(gid));
}
} catch (Exception e) {
return AppletControllerUtil.appletWarning("次卡服务ID解析失败");
}
// 4. 查该次卡下所有订单通过cartid过滤
Order orderQuery = new Order();
orderQuery.setCartid(card.getOrderid());
List<Order> orderList = orderService.selectOrderList(orderQuery);
List<Map<String, Object>> serviceOrderMap = new ArrayList<>();
// 5. 先处理已预约的服务(有订单的)
for (Order o : orderList) {
if (o.getProductId() != null && goodsIds.contains(o.getProductId())) {
ServiceGoods goods = serviceGoodsService.selectServiceGoodsById(o.getProductId());
Map<String, Object> map = new HashMap<>();
map.put("type", "order");
map.put("serviceid", o.getProductId());
map.put("serviceName", goods != null ? goods.getTitle() : "");
map.put("status",o.getStatus());
map.put("orderid", o.getOrderId());
map.put("oid", o.getId());
serviceOrderMap.add(map);
goodsIds.remove(o.getProductId()); // 剔除已预约的服务
}
}
// 6. 再处理未预约的服务
for (Long gid : goodsIds) {
ServiceGoods goods = serviceGoodsService.selectServiceGoodsById(gid);
Map<String, Object> map = new HashMap<>();
map.put("type", "service");
map.put("serviceid", gid);
map.put("serviceName", goods != null ? goods.getTitle() : "");
serviceOrderMap.add(map);
}
// 7. 组装返回
Map<String, Object> result = new HashMap<>();
if (Objects.equals(card.getNum(), cardInfo.getNum())) {
result.put("iscanback", "1");
}else{
result.put("iscanback", "2");
}
result.put("icon", cardInfo != null ? AppletControllerUtil.buildImageUrl(cardInfo.getShowimage()) : "");
result.put("title", cardInfo != null ? cardInfo.getTitle() : "");
result.put("num", "1");
result.put("orderNo", card.getOrderid());
result.put("status", card.getStatus());
result.put("buyTime",sdf.format(card.getCreatedAt()));
result.put("serviceList", serviceOrderMap);
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("查询我的次卡详情失败:", e);
return AppletControllerUtil.appletError("查询我的次卡详情失败:" + e.getMessage());
}
}
/**
* 查询所有状态为1的店铺地址
*/
@GetMapping("/api/shopAddress/activeData")
public AjaxResult getActiveShopAddressList() {
ShopAddress query = new ShopAddress();
query.setAddressStatus(1L);
List<ShopAddress> list = shopAddressService.selectShopAddressList(query);
if (list == null || list.isEmpty()) {
return AppletControllerUtil.appletWarning("暂无可用店铺地址");
}
ShopAddress shopAddress = list.get(0);
Map<String, Object> result = new HashMap<>();
result.put("id", shopAddress.getId());
result.put("shopName", shopAddress.getShopName());
result.put("shopAddress", shopAddress.getShopAddress());
result.put("contactPhone", shopAddress.getContactPhone());
result.put("longitude", shopAddress.getLongitude());
result.put("latitude", shopAddress.getLatitude());
result.put("contactPerson", shopAddress.getContactPerson());
result.put("addressStatus", shopAddress.getAddressStatus());
return AppletControllerUtil.appletSuccess(result);
}
/**
* 随机获取6个一口价服务或商城商品
* @param type 1服务,2商品
* @return 图片、价格、一口价价格、标题
*/
@GetMapping("/api/goods/random/list")
public AjaxResult getRandomGoodsList(@RequestParam("type") int type) {
try {
ServiceGoods query = new ServiceGoods();
query.setStatus("1"); // 只查启用
if (type == 1) {
// 一口价服务商品type=2一口价 isfixed=1
query.setType(1);
query.setIsfixed(1);
} else if (type == 2) {
// 商城商品type=3
query.setType(2);
} else {
return AppletControllerUtil.appletWarning("type参数无效");
}
List<ServiceGoods> goodsList = serviceGoodsService.selectServiceGoodsList(query);
Collections.shuffle(goodsList);
List<ServiceGoods> resultList = goodsList.size() > 6 ? goodsList.subList(0, 6) : goodsList;
List<Map<String, Object>> result = new ArrayList<>();
for (ServiceGoods g : resultList) {
Map<String, Object> map = new HashMap<>();
map.put("img", AppletControllerUtil.buildImageUrl(g.getIcon()));
map.put("price", g.getPrice());
map.put("id", g.getId());
map.put("fixedprice", g.getFixedprice());
map.put("title", g.getTitle());
result.add(map);
}
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("随机获取商品失败:", e);
return AppletControllerUtil.appletError("随机获取商品失败:" + e.getMessage());
}
}
/**
* 根据ID查询预支付记录并计算支付金额
*
* @param id 预支付记录ID
* @param params 请求参数包含paytype、coupon_id、mtcode
* @param request HTTP请求对象
* @return 预支付记录详情和计算后的支付金额
*
*/
@PostMapping("/api/paybefor/info/{id}")
public AjaxResult getPayBeforInfo(@PathVariable("id") String id, @RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 2. 参数验证
if (com.ruoyi.common.utils.StringUtils.isBlank(id)) {
return AppletControllerUtil.appletWarning("预支付记录ID不能为空");
}
// 3. 获取请求参数
Integer paytype = params.get("paytype") != null ? Integer.parseInt(params.get("paytype").toString()) : 1;
Long couponId = params.get("coupon_id") != null ? Long.parseLong(params.get("coupon_id").toString()) : null;
String mtcode = params.get("mtcode") != null ? params.get("mtcode").toString() : null;
// 4. 查询预支付记录
UsersPayBefor payBefor = usersPayBeforService.selectUsersPayBeforByOrderId(id);
if (payBefor == null) {
return AppletControllerUtil.appletWarning("预支付记录不存在");
}
// 5. 验证记录归属权(只能查看自己的记录)
if (!payBefor.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("无权查看该预支付记录");
}
// 6. 获取原始总金额allmoney是固定的永远不会改变
BigDecimal originalAmount = payBefor.getAllmoney();
if (originalAmount == null) {
originalAmount = BigDecimal.ZERO;
}
// 获取会员优惠金额(固定不变)
BigDecimal memberMoney = payBefor.getMembermoney();
if (memberMoney == null) {
memberMoney = BigDecimal.ZERO;
}
// 获取服务金抵扣金额(需要智能限制)
BigDecimal serviceMoney = payBefor.getServicemoney();
if (serviceMoney == null) {
serviceMoney = BigDecimal.ZERO;
}
// 获取购物金抵扣金额(需要智能限制)
BigDecimal shopMoney = payBefor.getShopmoney();
if (shopMoney == null) {
shopMoney = BigDecimal.ZERO;
}
// 智能限制消费金和服务金抵扣金额
BigDecimal maxDeductibleAmount = originalAmount.subtract(memberMoney);
if (maxDeductibleAmount.compareTo(BigDecimal.ZERO) < 0) {
maxDeductibleAmount = BigDecimal.ZERO;
}
// 检查用户实际拥有的消费金和服务金余额
BigDecimal userServiceBalance = user.getServicefee() != null ? user.getServicefee() : BigDecimal.ZERO;
BigDecimal userShopBalance = user.getConsumption() != null ? user.getConsumption() : BigDecimal.ZERO;
// 限制服务金抵扣金额(不能超过用户余额和最大可抵扣金额)
BigDecimal maxServiceDeductible = userServiceBalance.compareTo(maxDeductibleAmount) > 0 ?
maxDeductibleAmount : userServiceBalance;
if (serviceMoney.compareTo(maxServiceDeductible) > 0) {
logger.info("服务金抵扣金额 {} 超过最大可抵扣金额 {},已自动调整为 {}",
serviceMoney, maxServiceDeductible, maxServiceDeductible);
serviceMoney = maxServiceDeductible;
}
// 限制购物金抵扣金额(在服务金抵扣后的剩余金额内,且不能超过用户余额)
BigDecimal remainingDeductible = maxDeductibleAmount.subtract(serviceMoney);
if (remainingDeductible.compareTo(BigDecimal.ZERO) < 0) {
remainingDeductible = BigDecimal.ZERO;
}
BigDecimal maxShopDeductible = userShopBalance.compareTo(remainingDeductible) > 0 ?
remainingDeductible : userShopBalance;
if (shopMoney.compareTo(maxShopDeductible) > 0) {
logger.info("购物金抵扣金额 {} 超过最大可抵扣金额 {},已自动调整为 {}",
shopMoney, maxShopDeductible, maxShopDeductible);
shopMoney = maxShopDeductible;
}
// 7. 计算优惠券金额(每次重新计算)
BigDecimal couponMoney = BigDecimal.ZERO;
if (couponId != null) {
CouponUser couponUser = couponUserService.selectCouponUserById(couponId);
if (couponUser != null && couponUser.getStatus() != null && couponUser.getStatus() == 1L) {
// 验证优惠券是否属于当前用户
if (!couponUser.getUid().equals(user.getId())) {
return AppletControllerUtil.appletWarning("优惠券不属于当前用户");
}
// 验证优惠券是否过期
if (couponUser.getLoseTime() != null && !"永久有效".equals(couponUser.getLoseTime())) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date loseTime = sdf.parse(couponUser.getLoseTime());
if (new Date().after(loseTime)) {
return AppletControllerUtil.appletWarning("优惠券已过期");
}
} catch (Exception e) {
logger.warn("解析优惠券过期时间失败: " + e.getMessage());
}
}
// 验证最低消费(基于原始金额)
if (couponUser.getMinPrice() != null && originalAmount.compareTo(BigDecimal.valueOf(couponUser.getMinPrice())) < 0) {
return AppletControllerUtil.appletWarning("订单金额未达到优惠券使用条件");
}
couponMoney = BigDecimal.valueOf(couponUser.getCouponPrice());
} else {
return AppletControllerUtil.appletWarning("优惠券无效或已被使用");
}
}
// 8. 计算美团优惠金额每次重新计算2至15的随机整数用于测试
BigDecimal mtMoney = BigDecimal.ZERO;
if (mtcode != null && !mtcode.trim().isEmpty()) {
// 生成2至15的随机整数
Random random = new Random();
int randomDiscount = random.nextInt(14) + 2; // 2到15的随机数
mtMoney = new BigDecimal(randomDiscount);
}
// 9. 计算实际应付金额基于allmoney减去所有优惠
BigDecimal actualAmount = originalAmount
.subtract(memberMoney) // 减去会员优惠
.subtract(serviceMoney) // 减去服务金抵扣
.subtract(shopMoney) // 减去购物金抵扣
.subtract(couponMoney) // 减去优惠券金额
.subtract(mtMoney); // 减去美团优惠
if (actualAmount.compareTo(BigDecimal.ZERO) < 0) {
actualAmount = BigDecimal.ZERO;
}
// 10. 根据支付方式计算各支付渠道金额
BigDecimal wxMoney = BigDecimal.ZERO;
BigDecimal yeMoney = BigDecimal.ZERO;
if (paytype == 1) {
// 微信支付
wxMoney = actualAmount;
yeMoney = BigDecimal.ZERO;
} else if (paytype == 2) {
// 余额支付
if (user.getBalance() != null && user.getBalance().compareTo(actualAmount) >= 0) {
wxMoney = BigDecimal.ZERO;
yeMoney = actualAmount;
} else {
return AppletControllerUtil.appletWarning("余额不足,无法完成支付");
}
} else if (paytype == 3) {
// 组合支付:优先使用余额,不足部分用微信支付
if (user.getBalance() != null && user.getBalance().compareTo(actualAmount) >= 0) {
// 余额足够,全部用余额支付
wxMoney = BigDecimal.ZERO;
yeMoney = actualAmount;
} else if (user.getBalance() != null && user.getBalance().compareTo(BigDecimal.ZERO) > 0) {
// 余额不足,优先扣除用户所有余额,剩余部分用微信支付
yeMoney = user.getBalance();
wxMoney = actualAmount.subtract(yeMoney);
} else {
// 无余额,全部微信支付
wxMoney = actualAmount;
yeMoney = BigDecimal.ZERO;
}
} else {
return AppletControllerUtil.appletWarning("无效的支付方式");
}
// 11. 更新预支付记录注意allmoney保持不变只更新其他字段
payBefor.setPaytype(Long.valueOf(paytype));
payBefor.setCouponid(couponId);
payBefor.setCouponmoney(couponMoney);
payBefor.setMtcode(mtcode);
payBefor.setMtmoney(mtMoney);
payBefor.setWxmoney(wxMoney);
payBefor.setYemoney(yeMoney);
// 注意allmoney保持不变这是原始总金额
int updateResult = usersPayBeforService.updateUsersPayBefor(payBefor);
if (updateResult <= 0) {
return AppletControllerUtil.appletWarning("更新预支付记录失败");
}
// 12. 构建支付公式
StringBuilder paymentFormula = new StringBuilder();
paymentFormula.append("总金额(").append(originalAmount).append(")");
// 添加各种优惠项
if (memberMoney.compareTo(BigDecimal.ZERO) > 0) {
paymentFormula.append("-会员优惠(").append(memberMoney).append(")");
}
if (serviceMoney.compareTo(BigDecimal.ZERO) > 0) {
paymentFormula.append("-服务金抵扣(").append(serviceMoney).append(")");
}
if (shopMoney.compareTo(BigDecimal.ZERO) > 0) {
paymentFormula.append("-购物金抵扣(").append(shopMoney).append(")");
}
if (couponMoney.compareTo(BigDecimal.ZERO) > 0) {
paymentFormula.append("-优惠券(").append(couponMoney).append(")");
}
if (mtMoney.compareTo(BigDecimal.ZERO) > 0) {
paymentFormula.append("-美团优惠(").append(mtMoney).append(")");
}
paymentFormula.append("=").append(actualAmount).append("=");
// 添加支付方式
if (wxMoney.compareTo(BigDecimal.ZERO) > 0 && yeMoney.compareTo(BigDecimal.ZERO) > 0) {
// 组合支付
paymentFormula.append("微信支付(").append(wxMoney).append(")+余额支付(").append(yeMoney).append(")");
} else if (wxMoney.compareTo(BigDecimal.ZERO) > 0) {
// 纯微信支付
paymentFormula.append("微信支付(").append(wxMoney).append(")");
} else if (yeMoney.compareTo(BigDecimal.ZERO) > 0) {
// 纯余额支付
paymentFormula.append("余额支付(").append(yeMoney).append(")");
}
// 13. 构建返回数据
Map<String, Object> result = new HashMap<>();
result.put("id", payBefor.getId());
result.put("orderId", payBefor.getOrderid());
result.put("paycode", payBefor.getPaycode());
result.put("allmoney", originalAmount); // 原始总金额(固定不变,这是您最初存储的金额)
result.put("finalAmount", actualAmount); // 实际应付金额基于allmoney计算得出
result.put("wxmoney", wxMoney); // 微信支付金额
result.put("status", payBefor.getStatus());
result.put("oid", payBefor.getOid());
result.put("yemoney", yeMoney); // 余额支付金额
result.put("membermoney", memberMoney); // 会员优惠金额(固定不变)
result.put("shopmoney", shopMoney); // 购物金抵扣金额(智能限制后)
result.put("servicemoney", serviceMoney); // 服务金抵扣金额(智能限制后)
result.put("couponmoney", couponMoney); // 优惠券金额(实时计算)
result.put("mtmoney", mtMoney); // 美团优惠金额(实时计算)
result.put("type", payBefor.getType());
result.put("paytype", paytype);
result.put("usersBalance", user.getBalance());
result.put("couponId", couponId);
result.put("mtcode", mtcode);
result.put("servicetype", payBefor.getServicetype());
result.put("paymentFormula", paymentFormula.toString()); // 支付公式
// 添加抵扣限制说明
Map<String, Object> deductionInfo = new HashMap<>();
deductionInfo.put("maxDeductibleAmount", maxDeductibleAmount); // 最大可抵扣金额
deductionInfo.put("remainingDeductible", remainingDeductible); // 剩余可抵扣金额
deductionInfo.put("userServiceBalance", userServiceBalance); // 用户服务金余额
deductionInfo.put("userShopBalance", userShopBalance); // 用户购物金余额
deductionInfo.put("maxServiceDeductible", maxServiceDeductible); // 服务金最大可抵扣金额
deductionInfo.put("maxShopDeductible", maxShopDeductible); // 购物金最大可抵扣金额
deductionInfo.put("deductionRule", "消费金和服务金抵扣不能超过订单金额减去会员优惠后的金额,且不能超过用户实际余额");
result.put("deductionInfo", deductionInfo);
// // 添加计算明细,方便前端理解金额构成
// Map<String, Object> calculationDetail = new HashMap<>();
// calculationDetail.put("originalAmount", originalAmount);
// calculationDetail.put("memberDiscount", memberMoney);
// calculationDetail.put("serviceDiscount", serviceMoney);
// calculationDetail.put("shopDiscount", shopMoney);
// calculationDetail.put("couponDiscount", couponMoney);
// calculationDetail.put("mtDiscount", mtMoney);
// calculationDetail.put("finalAmount", actualAmount);
// result.put("calculationDetail", calculationDetail);
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("查询预支付记录失败:", e);
return AppletControllerUtil.appletError("查询预支付记录失败:" + e.getMessage());
}
}
/**
* 购物车下单接口
* @param params {"carid":[购物车id数组], "address_id":地址id, "make_time":预约时间}
* @param request HTTP请求对象
* @return 下单结果
*/
@PostMapping("/api/service/create/order")
public AjaxResult submitCartOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 兼容前端传 {"0":{...}} 的情况
// if (!params.containsKey("carid") && params.size() == 1 && params.containsKey("0") && params.get("0") instanceof Map) {
// params = (Map<String, Object>) params.get("0");
// }
// 打印前端传递的参数
System.out.println("submitCartOrder params: " + params);
PayBeforeUtil payBeforeUtil = new PayBeforeUtil();
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
String maincorid=GenerateCustomCode.generCreateOrder("ALL");
Users user = (Users) userValidation.get("user");
if (user == null) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
// 检查carid和address_id参数
Object carIdsObj = params.get("carid");
Object addressIdObj = params.get("address_id");
Object isselfObj = params.get("isself");
if (isselfObj == null) {
isselfObj=2L;
}
// if (params.get("product_id") == null || params.get("num") == null) {
// return AppletControllerUtil.appletWarning("单品下单参数(product_id, num, sku, mark)不能为空");
// }
if (addressIdObj == null||addressIdObj == "") {
if ( params.get("product_id") != null) {
long isself= Long.parseLong(params.get("isself").toString());
if (params.get("isself")==null) {
isself=2L;
}
Long product_id=Long.valueOf(params.get("product_id").toString());
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(product_id);
if (serviceGoods.getIsforservice()==1) {
if (serviceGoods != null||isself==1) {
int num=Integer.valueOf(params.get("num").toString());
String sku = params.get("sku").toString();
String mark = params.get("mark").toString();
if (serviceGoods.getType() == 2) {
BigDecimal totalAmount2 = BigDecimal.ZERO;
Map<String, Object> orderResult = Map.of();
UserAddress userAddress=new UserAddress();
orderResult= CartOrderUtil.createGoodsOrderFromOnes(user, sku,num, mark,serviceGoods, userAddress, goodsOrderService,maincorid,isself) ;
totalAmount2 = totalAmount2.add(new BigDecimal(orderResult.get("allprice").toString()));
if (totalAmount2.compareTo(BigDecimal.ZERO) > 0) {
String orderid= orderResult.get("orderId").toString();
String payBeforeId = payBeforeUtil.createPayBefore(user, totalAmount2, orderid, null, null, 11L, null, null, null, null, null, Long.valueOf(serviceGoods.getType()),null,null);
Map<String, Object> result1 = new HashMap<>();
result1.put("type", "2");
result1.put("orderid", payBeforeId);
return AppletControllerUtil.appletSuccess(result1);
}
}
}
}
}
return AppletControllerUtil.appletWarning("address_id不能为空");
}
Long addressId;
try {
addressId = Long.valueOf(addressIdObj.toString());
} catch (Exception e) {
return AppletControllerUtil.appletWarning("address_id格式错误");
}
UserAddress userAddress = userAddressService.selectUserAddressById(addressId);
if (userAddress == null) {
return AppletControllerUtil.appletWarning("地址不存在");
}
List<Map<String, Object>> orderList = new ArrayList<>();
BigDecimal totalAmount = BigDecimal.ZERO;
if(carIdsObj==null){
// 单品下单参数校验
if (params.get("num") == null || params.get("product_id") == null || params.get("sku") == null || params.get("mark") == null) {
return AppletControllerUtil.appletWarning("num、product_id、sku、mark参数不能为空");
}
int num;
try { num = Integer.parseInt(params.get("num").toString()); } catch (Exception e) { return AppletControllerUtil.appletWarning("num格式错误"); }
Long product_id;
try { product_id = Long.valueOf(params.get("product_id").toString()); } catch (Exception e) { return AppletControllerUtil.appletWarning("product_id格式错误"); }
String sku = params.get("sku").toString();
String mark = params.get("mark").toString();
String orderid="";
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(product_id);
if (serviceGoods == null) {
return AppletControllerUtil.appletWarning("商品ID " + product_id + " 不存在");
}
Map<String, Object> orderResult = Map.of();
if (serviceGoods.getType() == 2) {
orderResult= CartOrderUtil.createGoodsOrderFromOnes(user, sku,num, mark,serviceGoods, userAddress, goodsOrderService,maincorid,Long.parseLong(isselfObj.toString())) ;
}
if (!(Boolean) orderResult.getOrDefault("success", false)) {
return AppletControllerUtil.appletWarning(orderResult.getOrDefault("msg", "下单失败").toString());
}
orderid= orderResult.get("orderId").toString();
orderList.add(orderResult);
totalAmount = totalAmount.add(new BigDecimal(orderResult.get("allprice").toString()));
if (totalAmount.compareTo(BigDecimal.ZERO) > 0) {
String payBeforeId = payBeforeUtil.createPayBefore(user, totalAmount, maincorid, null, null, 5L, null, null, null, null, null, Long.valueOf(serviceGoods.getType()),null,null);
Map<String, Object> result1 = new HashMap<>();
result1.put("type", "2");
result1.put("orderid", payBeforeId);
return AppletControllerUtil.appletSuccess(result1);
}
}else{
List<Integer> carIds;
try {
carIds = (List<Integer>) carIdsObj;
} catch (Exception e) {
return AppletControllerUtil.appletWarning("carid参数格式错误必须为整型数组");
}
String makeTime = params.get("make_time") != null ? params.get("make_time").toString() : "";
for (Integer carId : carIds) {
GoodsCart cart = goodsCartService.selectGoodsCartById(carId);
if (cart == null || !user.getId().equals(cart.getUid())) {
return AppletControllerUtil.appletWarning("购物车ID " + carId + " 不存在或无权操作");
}
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(cart.getGoodId());
if (serviceGoods == null) {
return AppletControllerUtil.appletWarning("商品ID " + cart.getGoodId() + " 不存在");
}
Map<String, Object> orderResult;
if (cart.getGoodstype() != null && cart.getGoodstype() == 2) {
orderResult = CartOrderUtil.createGoodsOrderFromCart(user, cart, serviceGoods, userAddress, goodsOrderService,maincorid,Long.parseLong(isselfObj.toString()));
// String payBeforeId = payBeforeUtil.createPayBefore(user, totalAmount, maincorid, null, cart.getGoodId(), 6L, cart.getSku(), null, null, null, null,1L, null, null);
} else {
orderResult = CartOrderUtil.createServiceOrderFromCart(user, cart, serviceGoods, userAddress, makeTime, orderService, orderLogService,maincorid);
//String payBeforeId = payBeforeUtil.createPayBefore(user, totalAmount, maincorid, null, cart.getGoodId(), 6L, cart.getSku(), null, null, null, null,1L, null, null);
}
if (!(Boolean) orderResult.getOrDefault("success", false)) {
//删除购物车记录
return AppletControllerUtil.appletWarning(orderResult.getOrDefault("msg", "下单失败").toString());
}
orderList.add(orderResult);
goodsCartService.deleteGoodsCartById(cart.getId());
//只有一口价服务才会有支付
if (serviceGoods.getServicetype()==3||serviceGoods.getType()==2){
totalAmount = totalAmount.add(new BigDecimal(orderResult.get("allprice").toString()));
}
if (cart.getGoodstype()==1&&totalAmount.compareTo(BigDecimal.ZERO) > 0){
String orderid= orderResult.get("orderId").toString();
String payBeforeId = payBeforeUtil.createPayBefore(user, totalAmount, orderid, null, cart.getGoodId(), 6L, cart.getSku(), null, null, null, null,1L, null, null);
Map<String, Object> result1 = new HashMap<>();
result1.put("type", "2");
result1.put("orderid", orderid);
return AppletControllerUtil.appletSuccess(result1);
}
}
}
if (totalAmount.compareTo(BigDecimal.ZERO) > 0) {
com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
jsonObject.put("name", "订单创建成功");
OrderUtil.addgoodsorderlog(999L,maincorid,"订单生成","1",jsonObject,2L);
String payBeforeId = payBeforeUtil.createPayBefore(user, totalAmount, maincorid, null, null, 5L, null, null, null, null, null,2L,null,null);
Map<String, Object> result1 = new HashMap<>();
result1.put("type", "2");
result1.put("orderid", maincorid);
return AppletControllerUtil.appletSuccess(result1);
}else{
Map<String, Object> result1 = new HashMap<>();
result1.put("type", "1");
result1.put("orderid", maincorid);
return AppletControllerUtil.appletSuccess(result1);
}
} catch (Exception e) {
logger.error("购物车下单失败:", e);
return AppletControllerUtil.appletError("购物车下单失败:" + e.getMessage());
}
}
/**
* 查询服务订单列表
* @param bigtype 订单类型1=预约下单 2=报价下单 3=一口价
* @param status 订单状态1=待接单 2=待服务 3=服务中 4=已结束 5=已取消 6=师傅完成服务 7=未服务提前结束订单 8=待报价 9=待成团 10=已成团 11=待支付
* @param pageNum 页码
* @param pageSize 每页数量
* @param request HTTP请求对象
* @return 订单列表
*/
@GetMapping("/api/service/order/list")
public AjaxResult getServiceOrderList(
@RequestParam(value = "bigtype", required = false) Integer bigtype,
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
HttpServletRequest request) {
try {
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(pageNum, pageSize);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning((String) pageValidation.get("message"));
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 3. 构建查询条件
Order queryOrder = new Order();
queryOrder.setUid(user.getId());
//queryOrder.setWorkerId(user.getId());
// 根据bigtype筛选订单类型
if (bigtype != null) {
switch (bigtype) {
case 1: // 预约下单
queryOrder.setBigtype(1);
break;
case 2: // 报价下单
queryOrder.setBigtype(2);
break;
case 3: // 一口价
queryOrder.setBigtype(3);
break;
default:
return AppletControllerUtil.appletWarning("订单类型参数无效");
}
}
// 根据status筛选订单状态
if (status != null) {
if (status == 12){
queryOrder.setBaojiayh(user.getId());
}else{
if (status == 4){
// List<String> idslist=new ArrayList<>();
// idslist.add("4");
// idslist.add("7");
// queryOrder.setIds(idslist);
queryOrder.setStatus(4L);
queryOrder.setIsComment(1);
}else if (status == 13){
queryOrder.setStatus(4L);
queryOrder.setIsComment(0);
queryOrder.setIspay("1");
}else {
queryOrder.setStatus(Long.valueOf(status));
}
// queryOrder.setStatus(Long.valueOf(status));
}
}
// 4. 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 5. 查询订单列表
List<Order> orderList = orderService.selectOrderList(queryOrder);
// 6. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Order order : orderList) {
Map<String, Object> orderMap = new HashMap<>();
UsersPayBefor payBefore = new UsersPayBefor();
payBefore.setLastorderid(order.getOrderId());
payBefore.setStatus(1L);
List<UsersPayBefor> payBeforeList = usersPayBeforService.selectUsersPayBeforList(payBefore);
if (!payBeforeList.isEmpty()) {
orderMap.put("istopay", 1);
}else{
orderMap.put("istopay", 2);
}
UserGroupBuying groupBuying =userGroupBuyingService.selectUserGroupBuyingByptorderid(order.getOrderId());
if (groupBuying != null){
orderMap.put("groupid", groupBuying.getOrderid());
}
orderMap.put("is_comment", order.getIsComment());
// 基本信息
orderMap.put("goodsid", order.getProductId());
orderMap.put("id", order.getId());
orderMap.put("orderId", order.getOrderId());
orderMap.put("odertype", order.getOdertype()); // 添加odertype字段
orderMap.put("totalPrice", order.getTotalPrice());
orderMap.put("status", order.getStatus());
orderMap.put("orcerCrateTime", sdf.format(order.getCreatedAt()));
orderMap.put("num", order.getNum());
orderMap.put("jsonStatus", order.getJsonStatus());
orderMap.put("statusText", getOrderStatusText(order.getStatus()));
// orderMap.put("createTime", sdf.format(order.getCreateTime()));
// 订单类型
orderMap.put("bigtype", getOrderBigType(order.getBigtype()));
orderMap.put("bigtypeText", getOrderBigTypeText(order.getBigtype()));
// 商品信息
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (serviceGoods != null) {
orderMap.put("productName", serviceGoods.getTitle());
orderMap.put("productIcon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon()));
orderMap.put("productPrice", serviceGoods.getPrice());
orderMap.put("productFixedPrice", serviceGoods.getFixedprice());
}
// 地址信息
if (order.getAddressId() != null) {
UserAddress userAddress = userAddressService.selectUserAddressById(order.getAddressId());
if (userAddress != null) {
orderMap.put("address", userAddress.getAddressInfo());
orderMap.put("contactName", userAddress.getName());
orderMap.put("contactPhone", userAddress.getPhone());
}
}
// 预约时间
if (order.getMakeTime() != null) {
Date makeDate = new Date(order.getMakeTime() * 1000);
orderMap.put("makeTime", sdf.format(makeDate));
orderMap.put("makeHour", order.getMakeHour());
}
// 报价相关信息(仅报价订单)
if (order.getBigtype() == 2) {
// 当订单状态为8待报价或12待选择返回截止时间毫秒数
if (order.getStatus() == 8 && order.getCreatedAt() != null) {
// 计算报价截止时间(创建时间+3天的毫秒数
Calendar calendar = Calendar.getInstance();
calendar.setTime(order.getCreatedAt());
calendar.add(Calendar.DAY_OF_MONTH, 3);
long deadlineTime = calendar.getTimeInMillis();
orderMap.put("quoteDeadlineTime", deadlineTime);
} else {
// 其他状态或没有创建时间返回0
orderMap.put("quoteDeadlineTime", 0L);
}
// 查询报价师傅数量和详情
List<UserDemandQuotation> quotationList = getQuotationList(order.getOrderId());
orderMap.put("quoteCount", quotationList.size());
orderMap.put("quotationList", buildQuotationList(quotationList));
// // 师傅信息(如果已派单)
// if (order.getWorkerId() != null) {
// Users worker = usersService.selectUsersById(order.getWorkerId());
// if (worker != null) {
// Map<String, Object> workerMap = new HashMap<>();
// workerMap.put("workerName", worker.getName());
// workerMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
// workerMap.put("workerPhone", worker.getPhone());
// orderMap.put("workerMap", workerMap);
// }
// }
}
// 师傅信息(如果已派单)
if (order.getWorkerId() != null) {
Users worker = usersService.selectUsersById(order.getWorkerId());
if (worker != null&&order.getIsAccept()==1) {
Map<String, Object> workerMap = new HashMap<>();
workerMap.put("workerName", worker.getName());
workerMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
workerMap.put("workerPhone", worker.getPhone());
orderMap.put("workerMap", workerMap);
}
}
// 师傅信息(如果已派单)
if (order.getWorkerId() != null&&order.getIsAccept()==1) {
Users worker = usersService.selectUsersById(order.getWorkerId());
if (worker != null) {
orderMap.put("workerName", worker.getName());
orderMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
orderMap.put("workerPhone", worker.getPhone());
}
}
// 附件信息
if (order.getFileData() != null && !order.getFileData().trim().isEmpty()) {
try {
List<String> attachments = JSONArray.parseArray(order.getFileData(), String.class);
orderMap.put("attachments", attachments);
orderMap.put("attachmentCount", attachments.size());
} catch (Exception e) {
orderMap.put("attachments", new ArrayList<>());
orderMap.put("attachmentCount", 0);
}
} else {
orderMap.put("attachments", new ArrayList<>());
orderMap.put("attachmentCount", 0);
}
resultList.add(orderMap);
}
// 7. 构建分页信息
PageInfo<Order> pageInfo = new PageInfo<>(orderList);
// 8. 构建返回数据格式
Map<String, Object> 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/service/order/list";
responseData.put("first_page_url", baseUrl + "?pageNum=1");
responseData.put("last_page_url", baseUrl + "?pageNum=" + pageInfo.getPages());
responseData.put("next_page_url", pageInfo.isHasNextPage() ?
baseUrl + "?pageNum=" + pageInfo.getNextPage() : null);
responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
responseData.put("path", baseUrl);
// 构建links数组
List<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?pageNum=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
links.add(nextLink);
responseData.put("links", links);
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
logger.error("查询服务订单列表失败:", e);
return AppletControllerUtil.appletError("查询服务订单列表失败:" + e.getMessage());
}
}
/**
* 获取订单状态文本
*/
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 "待报价";
case 9: return "待成团";
case 10: return "已成团";
case 11: return "待支付";
case 12: return "待选择";
default: return "未知状态";
}
}
/**
* 获取订单大类型
*/
private Integer getOrderBigType(int odertype) {
switch (odertype) {
case 1: return 1; // 预约下单
case 2: return 2; // 报价下单
case 3: return 3; // 一口价
default: return null;
}
}
/**
* 获取订单大类型文本
*/
private String getOrderBigTypeText(int odertype) {
switch (odertype) {
case 1: return "预约订单";
case 2: return "报价订单";
case 3: return "一口价订单";
default: return "未知类型";
}
}
/**
* 获取报价列表
*/
private List<UserDemandQuotation> getQuotationList(String orderId) {
try {
UserDemandQuotation queryParams = new UserDemandQuotation();
queryParams.setOrderid(orderId);
List<UserDemandQuotation> quotationList = userDemandQuotationService.selectUserDemandQuotationList(queryParams);
return quotationList != null ? quotationList : new ArrayList<>();
} catch (Exception e) {
logger.warn("查询报价列表失败订单ID: " + orderId + ", 错误: " + e.getMessage());
return new ArrayList<>();
}
}
/**
* 构建报价列表数据
*/
private List<Map<String, Object>> buildQuotationList(List<UserDemandQuotation> quotationList) {
List<Map<String, Object>> result = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (UserDemandQuotation quotation : quotationList) {
Map<String, Object> quoteMap = new HashMap<>();
quoteMap.put("id", quotation.getId());
quoteMap.put("orderId", quotation.getOrderid());
quoteMap.put("money", quotation.getMoney());
quoteMap.put("workerId", quotation.getWorkerid());
quoteMap.put("workerName", quotation.getWorkername());
quoteMap.put("workerImage", AppletControllerUtil.buildImageUrl(quotation.getWorkerimage()));
quoteMap.put("status", quotation.getStatus());
quoteMap.put("quotationTime", quotation.getQuotationTime() != null ? sdf.format(quotation.getQuotationTime()) : "");
quoteMap.put("createTime", quotation.getCreatedAt() != null ? sdf.format(quotation.getCreatedAt()) : "");
// 获取师傅详细信息
if (quotation.getWorkerid() != null) {
Users worker = usersService.selectUsersById(quotation.getWorkerid());
if (worker != null) {
quoteMap.put("workerPhone", worker.getPhone());
quoteMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
// 注意如果Users类没有level和experience字段可以注释掉这两行
// quoteMap.put("workerLevel", worker.getLevel()); // 师傅等级
// quoteMap.put("workerExperience", worker.getExperience()); // 师傅经验
}
}
result.add(quoteMap);
}
return result;
}
/**
* 查询订单师傅报价详情
* @param orderId 订单号
* @param request HTTP请求对象
* @return 师傅报价详情列表
*/
@GetMapping("/api/service/order/quotation/detail")
public AjaxResult getOrderQuotationDetail(@RequestParam("orderId") String orderId, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 验证订单是否存在且属于当前用户
Order order = orderService.selectOrderByOrderId(orderId);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
if (!user.getId().equals(order.getUid())) {
return AppletControllerUtil.appletWarning("无权查看此订单");
}
// 3. 查询报价列表
List<UserDemandQuotation> quotationList = getQuotationList(orderId);
// 4. 构建返回数据
Map<String, Object> result = new HashMap<>();
result.put("orderId", orderId);
result.put("orderStatus", order.getStatus());
result.put("orderStatusText", getOrderStatusText(order.getStatus()));
result.put("totalQuotations", quotationList.size());
result.put("quotationList", buildQuotationList(quotationList));
// 5. 如果是报价订单且状态为8待报价或12待选择添加报价截止时间
if (order.getBigtype() == 2 && (order.getStatus() == 8 || order.getStatus() == 12)) {
if (order.getCreatedAt() != null) {
// 计算报价截止时间(创建时间+3天的毫秒数
Calendar calendar = Calendar.getInstance();
calendar.setTime(order.getCreatedAt());
calendar.add(Calendar.DAY_OF_MONTH, 3);
long deadlineTime = calendar.getTimeInMillis();
result.put("quoteDeadlineTime", deadlineTime);
} else {
result.put("quoteDeadlineTime", 0L);
}
} else {
result.put("quoteDeadlineTime", 0L);
}
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("查询订单报价详情失败:", e);
return AppletControllerUtil.appletError("查询订单报价详情失败:" + e.getMessage());
}
}
/**..
* 确认报价接口
* @param params 请求参数 {"orderid": "订单号", "baojiaid": "报价ID"}
* @param request HTTP请求对象
* @return 预支付信息
*/
@PostMapping("/api/service/confirm/quotation")
public AjaxResult confirmQuotation(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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 (params == null || params.get("orderid") == null || params.get("baojiaid") == null) {
return AppletControllerUtil.appletWarning("订单号和报价ID不能为空");
}
String orderId = params.get("orderid").toString();
Long baojiaId = Long.valueOf(params.get("baojiaid").toString());
// 3. 查询报价数据
UserDemandQuotation quotation = userDemandQuotationService.selectUserDemandQuotationById(baojiaId);
if (quotation == null) {
return AppletControllerUtil.appletWarning("报价记录不存在");
}
// 4. 验证报价是否属于指定订单
if (!orderId.equals(quotation.getOrderid())) {
return AppletControllerUtil.appletWarning("报价记录与订单不匹配");
}
// 5. 查询订单信息
Order order = orderService.selectOrderByOrderId(orderId);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 6. 验证订单是否属于当前用户
if (!user.getId().equals(order.getUid())) {
return AppletControllerUtil.appletWarning("无权操作此订单");
}
// 7. 验证订单状态是否为待选择12
if (order.getStatus() != 8) {
return AppletControllerUtil.appletWarning("订单状态不正确,无法确认报价");
}
// 8. 验证报价状态是否为已报价1
if (quotation.getStatus() != 1) {
return AppletControllerUtil.appletWarning("报价状态不正确");
}
// 9. 更新报价状态为被选中2
// quotation.setStatus(2L);
// int updateResult = userDemandQuotationService.updateUserDemandQuotation(quotation);
// if (updateResult <= 0) {
// return AppletControllerUtil.appletWarning("更新报价状态失败");
// }
if (order.getOdertype()==4&&order.getStatus()==8){
UsersPayBefor payBefore = new UsersPayBefor();
payBefore.setOrderid(order.getOrderId());
payBefore.setStatus(1L);
List<UsersPayBefor> payBeforeList = usersPayBeforService.selectUsersPayBeforList(payBefore);
if (!payBeforeList.isEmpty()) {
for (UsersPayBefor payBefore1 : payBeforeList) {
usersPayBeforService.deleteUsersPayBeforById(payBefore1.getId());
}
}
// UserDemandQuotation quotation1=new UserDemandQuotation();
// quotation1.setOrderid(order.getOrderId());
// quotation1.setStatus(1L);
// List<UserDemandQuotation> quotationList = userDemandQuotationService.selectUserDemandQuotationList(quotation1);
// if (!quotationList.isEmpty()) {
// for (UserDemandQuotation quotation2 : quotationList) {
// userDemandQuotationService.deleteUserDemandQuotationById(quotation2.getId());
// }
// }
}
// 10. 更新订单状态为待支付11
//为了防止出现支付多条订单为同一个订单号的情况,就需要重新生成订单号
// orderId=GenerateCustomCode.generCreateOrder("XQ");
// orderId=order.getOrderId();
// order.setStatus(11L);
// order.setOrderId(orderId);
// // order.setWorkerId(quotation.getWorkerid());
// int orderUpdateResult = orderService.updateOrder(order);
// if (orderUpdateResult <= 0) {
// return AppletControllerUtil.appletWarning("更新订单状态失败");
// }
// 11. 创建预支付记录
PayBeforeUtil payBeforeUtil = new PayBeforeUtil();
String payOrderId = payBeforeUtil.createPayBefore(
user,
quotation.getMoney(),
orderId,
order.getId(),
order.getProductId() != null ? order.getProductId().longValue() : 0L,
4L, // 4=报价订单
order.getSku() != null ? order.getSku() : "",
"", // grouporderid为空
order.getAddressId(),
order.getMakeTime() != null ? order.getMakeTime().toString() : "",
order.getFileData() != null ? order.getFileData() : "",
1L, // servicetype=2表示服务类型
quotation.getId(), order.getOrderId()
);
if (payOrderId == null) {
return AppletControllerUtil.appletWarning("预支付记录创建失败");
}
// 12. 返回预支付信息
Map<String, Object> result = new HashMap<>();
result.put("orderid", payOrderId);
result.put("type", "2"); // 1表示需要调起支付
result.put("totalAmount", quotation.getMoney());
result.put("workerName", quotation.getWorkername());
result.put("quotationId", baojiaId);
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("确认报价失败:", e);
return AppletControllerUtil.appletError("确认报价失败:" + e.getMessage());
}
}
/**
* 师傅--我的订单查看
* 查询当前登录师傅(workerId)的所有订单支持status订单状态筛选返回格式与/api/service/order/list一致
* @param status 订单状态筛选
* @param pageNum 页码
* @param pageSize 每页数量
* @param request HTTP请求对象
* @return 订单列表
*/
@GetMapping("/api/worker/order/list1")
public AjaxResult getWorkerOrderList1(
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
@RequestParam(value = "dayDate", required = false) String dayDate,
@RequestParam(value = "day", required = false) String day,
HttpServletRequest request) {
try {
Map<String, Object> allMap = new HashMap<>();
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
List<Order> orderList = new ArrayList<>();
Order queryOrder = new Order();
// 直接用dayDate字符串查
if (StringUtils.isNotBlank(dayDate)) {
queryOrder.setDayDate(dayDate);
} else if (StringUtils.isNotBlank(day)) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long todayStart = cal.getTimeInMillis() / 1000;
long tomorrowStart = todayStart + 24 * 60 * 60;
if ("today".equals(day)) {
queryOrder.setMakeTimeStart(todayStart);
queryOrder.setMakeTimeEnd(tomorrowStart);
} else if ("tomorrow".equals(day)) {
queryOrder.setMakeTimeStart(tomorrowStart);
queryOrder.setMakeTimeEnd(tomorrowStart + 24 * 60 * 60);
}
}
// ... existing code ...
if (status != null && (status == 8 || status == 12)) {
if (status == 8){
//queryOrder.setWorkerId(user.getId());
queryOrder.setStatus(8L);
orderList = orderService.selectOrderList(queryOrder);
}
if (status == 12){{
//queryOrder.setWorkerId(user.getId());
queryOrder.setBaojiasf(user.getId());
orderList = orderService.selectOrderList(queryOrder);
}
}
}else{
queryOrder.setWorkerId(user.getId());
if (status != null) {
if (status == 4){
List<String> idslist=new ArrayList<>();
idslist.add("4");
idslist.add("7");
queryOrder.setIds(idslist);
}else{
queryOrder.setStatus(Long.valueOf(status));
}
}
orderList = orderService.selectOrderList(queryOrder);
}
// 3. 分页处理
int total = orderList.size();
int fromIndex = Math.max(0, (pageNum - 1) * pageSize);
int toIndex = Math.min(fromIndex + pageSize, total);
List<Order> pageOrderList = fromIndex < toIndex ? orderList.subList(fromIndex, toIndex) : new ArrayList<>();
Map<String, Object> dayMap = new HashMap<>();
if(status!=null){
Order queryOrderday = new Order();
queryOrderday.setStatus(Long.valueOf(status));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long todayStart = cal.getTimeInMillis() / 1000;
long tomorrowStart = todayStart + 24 * 60 * 60;
queryOrderday.setMakeTimeStart(todayStart);
queryOrderday.setMakeTimeEnd(tomorrowStart);
List<Order> dayOrderList = orderService.selectOrderList(queryOrderday);
dayMap.put("today", dayOrderList.size());
queryOrder.setMakeTimeStart(tomorrowStart);
queryOrder.setMakeTimeEnd(tomorrowStart + 24 * 60 * 60);
List<Order> tomorrowOrderList1 = orderService.selectOrderList(queryOrderday);
dayMap.put("tomorrow", tomorrowOrderList1.size());
}
// 4. 构建返回数据(与/api/service/order/list一致
List<Map<String, Object>> resultList = new ArrayList<>();
//resultList.add(dayMap);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd");
for (Order order : pageOrderList) {
Map<String, Object> orderMap = new HashMap<>();
// 基本信息
orderMap.put("id", order.getId());
orderMap.put("sku",AppletControllerUtil.parseSkuStringToObject(order.getSku()));
orderMap.put("orderId", order.getOrderId());
orderMap.put("odertype", order.getOdertype());
orderMap.put("totalPrice", order.getTotalPrice());
orderMap.put("status", order.getStatus());
orderMap.put("orcerCrateTime", sdf.format(order.getCreatedAt()));
orderMap.put("num", order.getNum());
orderMap.put("statusText", getOrderStatusText(order.getStatus()));
// 订单类型
orderMap.put("bigtype", getOrderBigType(order.getBigtype()));
orderMap.put("bigtypeText", getOrderBigTypeText(order.getBigtype()));
if (order.getWorkerId() != null) {
Users worker = usersService.selectUsersById(order.getWorkerId());
if (worker != null) {
Map<String, Object> workerMap = new HashMap<>();
workerMap.put("workerName", worker.getName());
workerMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
workerMap.put("workerPhone", worker.getPhone());
orderMap.put("workerMap", workerMap);
}
}
// 商品信息
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (serviceGoods != null) {
orderMap.put("productName", serviceGoods.getTitle());
orderMap.put("productIcon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon()));
orderMap.put("productPrice", serviceGoods.getPrice());
orderMap.put("productFixedPrice", serviceGoods.getFixedprice());
}
// 地址信息
if (order.getAddressId() != null) {
UserAddress userAddress = userAddressService.selectUserAddressById(order.getAddressId());
if (userAddress != null) {
orderMap.put("address", userAddress.getAddressInfo());
orderMap.put("contactName", userAddress.getName());
orderMap.put("contactPhone", userAddress.getPhone());
}
}
// 预约时间
if (order.getMakeTime() != null) {
Date makeDate = new Date(order.getMakeTime() * 1000);
orderMap.put("makeTime", sdfday.format(makeDate));
orderMap.put("makeHour", order.getMakeHour());
}
// 报价相关信息(仅报价订单)
if (order.getBigtype() == 2) {
if ((order.getStatus() == 8 || order.getStatus() == 12) && order.getCreatedAt() != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(order.getCreatedAt());
calendar.add(Calendar.DAY_OF_MONTH, 3);
long deadlineTime = calendar.getTimeInMillis();
orderMap.put("quoteDeadlineTime", deadlineTime);
} else {
orderMap.put("quoteDeadlineTime", 0L);
}
UserDemandQuotation quotation = new UserDemandQuotation();
quotation.setWorkerid(user.getId());
List<UserDemandQuotation> quotationList =userDemandQuotationService.selectUserDemandQuotationList(quotation);
orderMap.put("quoteCount", quotationList.size());
orderMap.put("quotationList", buildQuotationList(quotationList));
// if (order.getWorkerId() != null) {
// Users worker = usersService.selectUsersById(order.getWorkerId());
// if (worker != null) {
// Map<String, Object> workerMap = new HashMap<>();
// workerMap.put("workerName", worker.getName());
// workerMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
// workerMap.put("workerPhone", worker.getPhone());
// orderMap.put("workerMap", workerMap);
// }
// }
}
if (order.getFileData() != null && !order.getFileData().trim().isEmpty()) {
try {
List<String> attachments = JSONArray.parseArray(order.getFileData(), String.class);
orderMap.put("attachments", attachments);
orderMap.put("attachmentCount", attachments.size());
} catch (Exception e) {
orderMap.put("attachments", new ArrayList<>());
orderMap.put("attachmentCount", 0);
}
} else {
orderMap.put("attachments", new ArrayList<>());
orderMap.put("attachmentCount", 0);
}
resultList.add(orderMap);
}
Map<String, Object> pageResult = new HashMap<>();
// pageResult.put("total", total);
//
// pageResult.put("pageNum", pageNum);
// pageResult.put("pageSize", pageSize);
// pageResult.put("data", resultList);
// return AppletControllerUtil.appletSuccess(pageResult);
pageResult.put("pageNum", pageNum);
pageResult.put("pageSize", pageSize);
pageResult.put("data", resultList);
Map<String, Object> pageResult1 = new HashMap<>();
pageResult1.put("data", pageResult);
pageResult1.put("total", dayMap);
return AppletControllerUtil.appletSuccess(pageResult1);
} catch (Exception e) {
logger.error("查询师傅订单列表失败:", e);
return AppletControllerUtil.appletError("查询师傅订单列表失败:" + e.getMessage());
}
}
/**
* 师傅--我的订单查看
* 查询当前登录师傅(workerId)的所有订单支持status订单状态筛选返回格式与/api/service/order/list一致
* @param status 订单状态筛选
* @param request HTTP请求对象
* @return 订单列表
*/
@GetMapping("/api/worker/order/list")
public AjaxResult getWorkerOrderList(
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "page", defaultValue = "1") int page,
@RequestParam(value = "limit", defaultValue = "10") int limit,
@RequestParam(value = "dayDate", required = false) String dayDate,
@RequestParam(value = "day", required = false) String day,
HttpServletRequest request) {
try {
int pageNum=page;
int pageSize=limit;
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(pageNum, pageSize);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning((String) pageValidation.get("message"));
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 3. 构建查询条件
Order queryOrder = new Order();
// 直接用dayDate字符串查
if (StringUtils.isNotBlank(dayDate)) {
queryOrder.setDayDate(dayDate);
} else if (StringUtils.isNotBlank(day)) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long todayStart = cal.getTimeInMillis() / 1000;
long tomorrowStart = todayStart + 24 * 60 * 60;
if ("today".equals(day)) {
queryOrder.setMakeTimeStart(todayStart);
queryOrder.setMakeTimeEnd(tomorrowStart);
} else if ("tomorrow".equals(day)) {
queryOrder.setMakeTimeStart(tomorrowStart);
queryOrder.setMakeTimeEnd(tomorrowStart + 24 * 60 * 60);
}
}
if (status != null && (status == 8 || status == 12)) {
if (status == 8){
queryOrder.setStatus(8L);
}
if (status == 12){
queryOrder.setBaojiasf(user.getId());
}
} else {
queryOrder.setWorkerId(user.getId());
if (status != null) {
if (status == 4){
List<String> idslist=new ArrayList<>();
idslist.add("4");
idslist.add("7");
queryOrder.setIds(idslist);
} else {
queryOrder.setStatus(Long.valueOf(status));
}
}
}
Map<String, Object> dayMap = new HashMap<>();
// 4. 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 5. 查询订单列表
List<Order> orderList = orderService.selectOrderList(queryOrder);
// 6. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd");
for (Order order : orderList) {
Map<String, Object> orderMap = new HashMap<>();
// 基本信息
orderMap.put("id", order.getId());
orderMap.put("sku",AppletControllerUtil.parseSkuStringToObject(order.getSku()));
orderMap.put("orderId", order.getOrderId());
orderMap.put("odertype", order.getOdertype());
orderMap.put("totalPrice", order.getTotalPrice());
orderMap.put("status", order.getStatus());
orderMap.put("orcerCrateTime", sdf.format(order.getCreatedAt()));
orderMap.put("num", order.getNum());
orderMap.put("statusText", getOrderStatusText(order.getStatus()));
// 订单类型
orderMap.put("bigtype", getOrderBigType(order.getBigtype()));
orderMap.put("bigtypeText", getOrderBigTypeText(order.getBigtype()));
if (order.getWorkerId() != null) {
Users worker = usersService.selectUsersById(order.getWorkerId());
if (worker != null) {
Map<String, Object> workerMap = new HashMap<>();
workerMap.put("workerName", worker.getName());
workerMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
workerMap.put("workerPhone", worker.getPhone());
orderMap.put("workerMap", workerMap);
}
}
// 商品信息
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(order.getProductId());
if (serviceGoods != null) {
orderMap.put("productName", serviceGoods.getTitle());
orderMap.put("productIcon", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon()));
orderMap.put("productPrice", serviceGoods.getPrice());
orderMap.put("productFixedPrice", serviceGoods.getFixedprice());
}
// 地址信息
if (order.getAddressId() != null) {
UserAddress userAddress = userAddressService.selectUserAddressById(order.getAddressId());
if (userAddress != null) {
orderMap.put("address", userAddress.getAddressInfo());
orderMap.put("contactName", userAddress.getName());
orderMap.put("contactPhone", userAddress.getPhone());
}
}
// 预约时间
if (order.getMakeTime() != null) {
Date makeDate = new Date(order.getMakeTime() * 1000);
orderMap.put("makeTime", sdfday.format(makeDate));
orderMap.put("makeHour", order.getMakeHour());
}
// 报价相关信息(仅报价订单)
if (order.getBigtype() == 2) {
if ((order.getStatus() == 8 || order.getStatus() == 12) && order.getCreatedAt() != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(order.getCreatedAt());
calendar.add(Calendar.DAY_OF_MONTH, 3);
long deadlineTime = calendar.getTimeInMillis();
orderMap.put("quoteDeadlineTime", deadlineTime);
} else {
orderMap.put("quoteDeadlineTime", 0L);
}
UserDemandQuotation quotation = new UserDemandQuotation();
quotation.setWorkerid(user.getId());
List<UserDemandQuotation> quotationList =userDemandQuotationService.selectUserDemandQuotationList(quotation);
orderMap.put("quoteCount", quotationList.size());
orderMap.put("quotationList", buildQuotationList(quotationList));
}
if (order.getFileData() != null && !order.getFileData().trim().isEmpty()) {
try {
List<String> attachments = JSONArray.parseArray(order.getFileData(), String.class);
orderMap.put("attachments", attachments);
orderMap.put("attachmentCount", attachments.size());
} catch (Exception e) {
orderMap.put("attachments", new ArrayList<>());
orderMap.put("attachmentCount", 0);
}
} else {
orderMap.put("attachments", new ArrayList<>());
orderMap.put("attachmentCount", 0);
}
resultList.add(orderMap);
}
// 7. 构建分页信息
PageInfo<Order> pageInfo = new PageInfo<>(orderList);
System.out.println("##########################################"+pageInfo.getPageNum());
System.out.println("##########################################"+pageInfo.getPageSize());
// 8. 构建返回数据格式
Map<String, Object> 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/worker/order/list";
responseData.put("first_page_url", baseUrl + "?pageNum=1");
responseData.put("last_page_url", baseUrl + "?pageNum=" + pageInfo.getPages());
// 判断是否为最后一页如果是最后一页则next_page_url为null
String nextPageUrl = null;
// 直接判断:当前页码是否等于总页数,如果相等说明是最后一页
if (pageInfo.getPageNum() < pageInfo.getPages()) {
nextPageUrl = baseUrl + "?pageNum=" + (pageInfo.getPageNum() + 1);
}
responseData.put("next_page_url", nextPageUrl);
responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
responseData.put("path", baseUrl);
// 构建links数组
List<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", nextPageUrl);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
links.add(nextLink);
responseData.put("links", links);
Map<String, Object> pageResult1 = new HashMap<>();
if(status!=null){
Order queryOrderday = new Order();
queryOrderday.setStatus(Long.valueOf(status));
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long todayStart = cal.getTimeInMillis() / 1000;
long tomorrowStart = todayStart + 24 * 60 * 60;
queryOrderday.setMakeTimeStart(todayStart);
queryOrderday.setMakeTimeEnd(tomorrowStart);
List<Order> dayOrderList = orderService.selectOrderList(queryOrderday);
dayMap.put("today", dayOrderList.size());
queryOrder.setMakeTimeStart(tomorrowStart);
queryOrder.setMakeTimeEnd(tomorrowStart + 24 * 60 * 60);
List<Order> tomorrowOrderList1 = orderService.selectOrderList(queryOrderday);
dayMap.put("tomorrow", tomorrowOrderList1.size());
}
pageResult1.put("data", responseData);
pageResult1.put("total", dayMap);
return AppletControllerUtil.appletSuccess(pageResult1);
} catch (Exception e) {
logger.error("查询师傅订单列表失败:", e);
return AppletControllerUtil.appletError("查询师傅订单列表失败:" + e.getMessage());
}
}
/**
* 查询师傅详情
* @param id 师傅id
* @return 师傅详情
*/
@GetMapping("/api/worker/detail")
public AjaxResult getWorkerDetail(@RequestParam("id") Long id) {
try {
// 1. 查询师傅基本信息
Users worker = usersService.selectUsersById(id);
if (worker == null) {
return AppletControllerUtil.appletWarning("师傅不存在");
}
Map<String, Object> result = new HashMap<>();
// 基本信息
result.put("id", worker.getId());
result.put("name", worker.getName());
result.put("avatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
result.put("jobNo", worker.getJobNumber());
result.put("level", worker.getLevel());
result.put("phone", worker.getPhone());
//IWorkerLevelService workerLevelService;
if ( worker.getLevel()!=null){
WorkerLevel workerLevel = workerLevelService.selectWorkerLevelByLevel(Long.valueOf(worker.getLevel()));
if (workerLevel != null){
result.put("levelName", workerLevel.getTitle());
result.put("levelImage",AppletControllerUtil.buildImageUrl(workerLevel.getImage()));
}else{
result.put("levelName", "");
result.put("levelImage","");
}
}
// 2. 服务区域
List<Map<String, Object>> cityList = new ArrayList<>();
try {
if (worker.getServiceCityIds() != null && !worker.getServiceCityIds().trim().isEmpty()) {
List<String> cityIds;
String cityIdsStr = worker.getServiceCityIds().trim();
if (cityIdsStr.startsWith("[") && cityIdsStr.endsWith("]")) {
cityIds = JSON.parseArray(cityIdsStr, String.class);
} else {
cityIds = Arrays.asList(cityIdsStr.split(","));
}
for (String cityId : cityIds) {
if (cityId != null && !cityId.trim().isEmpty()) {
DiyCity city = diyCityService.selectDiyCityById(Long.valueOf(cityId.replaceAll("\"", "").trim()).intValue());
if (city != null) {
Map<String, Object> cityMap = new HashMap<>();
cityMap.put("id", city.getId());
cityMap.put("name", city.getTitle());
cityList.add(cityMap);
}
}
}
}
} catch (Exception e) {
logger.warn("解析师傅服务区域失败:" + e.getMessage());
}
result.put("serviceCityList", cityList);
// 3. 服务技能
List<Map<String, Object>> skillList = new ArrayList<>();
try {
if (worker.getSkillIds() != null && !worker.getSkillIds().trim().isEmpty()) {
List<String> skillIds;
String skillIdsStr = worker.getSkillIds().trim();
if (skillIdsStr.startsWith("[") && skillIdsStr.endsWith("]")) {
skillIds = JSON.parseArray(skillIdsStr, String.class);
} else {
skillIds = Arrays.asList(skillIdsStr.split(","));
}
for (String skillId : skillIds) {
if (skillId != null && !skillId.trim().isEmpty()) {
SiteSkill skill = siteSkillService.selectSiteSkillById(Long.parseLong(skillId.replaceAll("\"", "").trim()));
if (skill != null) {
Map<String, Object> skillMap = new HashMap<>();
skillMap.put("id", skill.getId());
skillMap.put("name", skill.getTitle());
skillList.add(skillMap);
}
}
}
}
} catch (Exception e) {
logger.warn("解析师傅技能失败:" + e.getMessage());
}
result.put("skillList", skillList);
// 4. 服务评价统计和评价列表
Map<String, Object> commentStat = new HashMap<>();
int goodNum = 0, midNum = 0, badNum = 0, totalNum = 0;
List<Map<String, Object>> commentList = new ArrayList<>();
OrderComment query = new OrderComment();
query.setWorkerId(id);
List<OrderComment> comments = orderCommentService.selectOrderCommentList(query);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (OrderComment c : comments) {
if (c.getNumType() != null) {
if (c.getNumType() == 1) goodNum++;
else if (c.getNumType() == 2) midNum++;
else if (c.getNumType() == 3) badNum++;
}
}
totalNum = comments.size();
commentStat.put("total", totalNum);
commentStat.put("good", goodNum);
commentStat.put("mid", midNum);
commentStat.put("bad", badNum);
//获取这个产品当前的第一条好评
OrderComment orderComment =new OrderComment();
orderComment.setWorkerId(id);
orderComment.setStatus(1);
orderComment.setNumType(1L);
List<OrderComment> orderCommentslist = orderCommentService.selectOrderCommentList(orderComment);
if(!orderCommentslist.isEmpty()){
JSONObject comment = new JSONObject();
comment.put("content", orderCommentslist.getFirst().getContent());
comment.put("id", orderCommentslist.getFirst().getId());
comment.put("labels", JSONArray.parseArray(orderCommentslist.getFirst().getLabels()) );
comment.put("num", orderCommentslist.getFirst().getNum());
comment.put("uid", orderCommentslist.getFirst().getUid());
comment.put("images",JSONArray.parseArray(orderCommentslist.getFirst().getImages()) );
//comment.put("images",parseImagesStringToArray(orderCommentslist.getFirst().getImages()));
comment.put("commenttime", sdf.format(orderCommentslist.getFirst().getCreatedAt()));
Users u = usersService.selectUsersById(orderCommentslist.getFirst().getUid());
if (u != null){
JSONObject user = new JSONObject();
user.put("id", u.getId());
user.put("name", u.getName());
user.put("avatar", u.getAvatar());
comment.put("user", user);
}
result.put("comment", comment);
}else{
result.put("comment", null);
}
result.put("commentStat", commentStat);
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("查询师傅详情失败:", e);
return AppletControllerUtil.appletError("查询师傅详情失败:" + e.getMessage());
}
}
/**
* 查询评价接口
* @param orderId 订单id
* @param productId 商品id
* @param uid 用户id
* @param workerId 师傅id
* @param numType 评价类型 1好评 2中评 3差评
* @param pageNum 页码
* @param pageSize 每页数量
* @return 评价分页列表
*/
@GetMapping("/api/comment/list")
public AjaxResult getCommentList(
@RequestParam(value = "orderid", required = false) String orderId,
@RequestParam(value = "productid", required = false) Long productId,
@RequestParam(value = "uid", required = false) Long uid,
@RequestParam(value = "workerid", required = false) Long workerId,
@RequestParam(value = "numtype", required = false) Long numType,
@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize
) {
try {
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(pageNum, pageSize);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning((String) pageValidation.get("message"));
}
// 2. 构建查询条件
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
OrderComment query = new OrderComment();
if (orderId != null && !orderId.isEmpty()) {
query.setOrderId(orderId);
}
if (productId != null) {
query.setProductId(productId);
}
if (uid != null) {
query.setUid(uid);
}
if (workerId != null) {
query.setWorkerId(workerId);
}
if (numType != null) {
query.setNumType(numType);
}
// 3. 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 4. 查询评价列表
List<OrderComment> commentList = orderCommentService.selectOrderCommentList(query);
// 5. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
for (OrderComment comment : commentList) {
Map<String, Object> commentData = new HashMap<>();
commentData.put("id", comment.getId());
commentData.put("orderId", comment.getOrderId());
commentData.put("productId", comment.getProductId());
commentData.put("uid", comment.getUid());
commentData.put("workerId", comment.getWorkerId());
commentData.put("numType", comment.getNumType());
commentData.put("content", comment.getContent());
commentData.put("createdAt",comment.getCreatedAt() != null ? sdf.format(comment.getCreatedAt()) : "");
if (comment.getImages()!=null){
commentData.put("image",JSONArray.parseArray(comment.getImages()));
}else{
commentData.put("image",JSONArray.parseArray("[]"));
}
if (comment.getLabels()!=null){
commentData.put("labels",JSONArray.parseArray(comment.getLabels()));
}else{
commentData.put("labels",JSONArray.parseArray("[]"));
}
// 获取用户信息
if (comment.getUid() != null) {
Users user = usersService.selectUsersById(comment.getUid());
if (user != null) {
Map<String, Object> userData = new HashMap<>();
userData.put("id", user.getId());
userData.put("nickname", user.getName());
userData.put("avatar", AppletControllerUtil.buildImageUrl(user.getAvatar()));
commentData.put("user", userData);
}
}
resultList.add(commentData);
}
// 6. 构建分页信息
PageInfo<OrderComment> pageInfo = new PageInfo<>(commentList);
// 7. 构建返回数据格式
Map<String, Object> 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/comment/list";
responseData.put("first_page_url", baseUrl + "?pageNum=1");
responseData.put("last_page_url", baseUrl + "?pageNum=" + pageInfo.getPages());
responseData.put("next_page_url", pageInfo.isHasNextPage() ?
baseUrl + "?pageNum=" + pageInfo.getNextPage() : null);
responseData.put("prev_page_url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
responseData.put("path", baseUrl);
// 构建links数组
List<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?pageNum=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?pageNum=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
links.add(nextLink);
responseData.put("links", links);
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
logger.error("查询评价列表失败:", e);
return AppletControllerUtil.appletError("查询评价列表失败:" + e.getMessage());
}
}
/**
* 首页推荐栏目接口
* 返回树状结构的一级目录和二级目录数据
* 一级目录来自IServiceCateService二级目录来自IServiceGoodsService
*
* @return 推荐栏目树状数据
*/
@GetMapping("/api/home/recommend/categories")
public AjaxResult getHomeRecommendCategories() {
try {
// 1. 查询所有启用的一级分类
ServiceCate queryCate = new ServiceCate();
queryCate.setStatus(1L); // 启用状态
queryCate.setType(1L); // 服务类型
queryCate.setParentId(0L); // 一级分类
List<ServiceCate> firstCategories = serviceCateService.selectServiceCateList(queryCate);
// 2. 查询销量排名前50的服务
List<ServiceGoods> topSalesGoods = serviceGoodsService.selectServiceGoodsListBySales(100);
// 3. 按一级分类ID分组服务
Map<Long, List<ServiceGoods>> goodsByFirstCate = topSalesGoods.stream()
.filter(goods -> goods.getFirstCateId() != null)
.collect(Collectors.groupingBy(ServiceGoods::getFirstCateId));
// 4. 构建树状结构
List<Map<String, Object>> treeData = new ArrayList<>();
for (ServiceCate firstCate : firstCategories) {
// 检查该一级分类是否有热门服务
List<ServiceGoods> relatedGoods = goodsByFirstCate.get(firstCate.getId());
if (relatedGoods != null && !relatedGoods.isEmpty()) {
Map<String, Object> firstCateData = new HashMap<>();
firstCateData.put("id", firstCate.getId());
firstCateData.put("title", firstCate.getTitle());
firstCateData.put("type", "category"); // 标识为分类
// 构建二级服务列表
List<Map<String, Object>> secondLevel = new ArrayList<>();
for (ServiceGoods goods : relatedGoods) {
Map<String, Object> goodsData = new HashMap<>();
goodsData.put("id", goods.getId());
goodsData.put("title", goods.getTitle());
goodsData.put("price", goods.getPrice());
goodsData.put("sales", goods.getSales());
goodsData.put("type", "service"); // 标识为服务
secondLevel.add(goodsData);
}
firstCateData.put("children", secondLevel);
treeData.add(firstCateData);
}
}
// 5. 按一级分类下的服务数量排序
treeData.sort((a, b) -> {
List<Map<String, Object>> childrenA = (List<Map<String, Object>>) a.get("children");
List<Map<String, Object>> childrenB = (List<Map<String, Object>>) b.get("children");
return Integer.compare(childrenB.size(), childrenA.size());
});
// 6. 限制返回数量前10个一级分类
if (treeData.size() > 10) {
treeData = treeData.subList(0, 10);
}
// 7. 限制每个一级分类下的服务数量最多5个
for (Map<String, Object> firstCateData : treeData) {
List<Map<String, Object>> children = (List<Map<String, Object>>) firstCateData.get("children");
if (children.size() > 5) {
firstCateData.put("children", children.subList(0, 5));
}
}
return AppletControllerUtil.appletSuccess(treeData);
} catch (Exception e) {
logger.error("获取首页推荐栏目失败:", e);
return AppletControllerUtil.appletError("获取首页推荐栏目失败:" + e.getMessage());
}
}
/**
* 报价查看接口
* 查询指定订单下的所有报价,支持价格和时间共存排序
* @param oid 订单ID
* @param priceSort 价格排序1-升序2-降序0-不排序
* @param timeSort 时间排序1-升序2-降序0-不排序
* @param groupBy 分组方式1-按师傅等级分组2-按价格区间分组3-按评价等级分组0-不分组
* @param pageNum 页码
* @param pageSize 每页数量
* @param request HTTP请求对象
* @return 报价列表
*/
@GetMapping("/api/quotation/list")
public AjaxResult getQuotationList(
@RequestParam("oid") Long oid,
@RequestParam(value = "priceSort", defaultValue = "0") Integer priceSort,
@RequestParam(value = "timeSort", defaultValue = "0") Integer timeSort,
@RequestParam(value = "groupBy", defaultValue = "0") Integer groupBy,
@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
HttpServletRequest request) {
try {
// 1. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(pageNum, pageSize);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning((String) pageValidation.get("message"));
}
// 2. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// 3. 查询订单信息,验证订单是否存在
Order order = orderService.selectOrderById(oid);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 4. 查询该订单下的所有报价
UserDemandQuotation query = new UserDemandQuotation();
query.setOid(oid);
List<UserDemandQuotation> allQuotations = userDemandQuotationService.selectUserDemandQuotationList(query);
// 5. 根据排序参数进行排序(价格和时间共存排序)
if ((priceSort != null && priceSort > 0) || (timeSort != null && timeSort > 0)) {
allQuotations.sort((q1, q2) -> {
int result = 0;
// 价格排序(优先级高)
if (priceSort != null && priceSort > 0) {
BigDecimal price1 = q1.getMoney() != null ? q1.getMoney() : BigDecimal.ZERO;
BigDecimal price2 = q2.getMoney() != null ? q2.getMoney() : BigDecimal.ZERO;
result = price1.compareTo(price2);
// 如果价格排序是降序,则反转结果
if (priceSort == 2) {
result = -result;
}
}
// 如果价格相同或没有价格排序,则按时间排序
if (result == 0 && timeSort != null && timeSort > 0) {
Date time1 = q1.getQuotationTime() != null ? q1.getQuotationTime() : new Date(0);
Date time2 = q2.getQuotationTime() != null ? q2.getQuotationTime() : new Date(0);
result = time1.compareTo(time2);
// 如果时间排序是降序,则反转结果
if (timeSort == 2) {
result = -result;
}
}
return result;
});
}
// 6. 根据分组参数进行分组
Map<String, List<UserDemandQuotation>> groupedQuotations = new HashMap<>();
boolean hasGrouping = false;
if (groupBy != null && groupBy > 0) {
hasGrouping = true;
if (groupBy == 1) {
// 按师傅等级分组
for (UserDemandQuotation quotation : allQuotations) {
Users worker = usersService.selectUsersById(quotation.getWorkerid());
String groupKey = "等级" + (worker != null && worker.getLevel() != null ? worker.getLevel() : "未知");
groupedQuotations.computeIfAbsent(groupKey, k -> new ArrayList<>()).add(quotation);
}
} else if (groupBy == 2) {
// 按价格区间分组
for (UserDemandQuotation quotation : allQuotations) {
BigDecimal price = quotation.getMoney() != null ? quotation.getMoney() : BigDecimal.ZERO;
String groupKey = getPriceRangeGroup(price);
groupedQuotations.computeIfAbsent(groupKey, k -> new ArrayList<>()).add(quotation);
}
} else if (groupBy == 3) {
// 按评价等级分组
for (UserDemandQuotation quotation : allQuotations) {
double goodRate = getWorkerGoodRate(quotation.getWorkerid());
String groupKey = getRatingGroup(goodRate);
groupedQuotations.computeIfAbsent(groupKey, k -> new ArrayList<>()).add(quotation);
}
}
// 对分组后的数据进行排序
List<UserDemandQuotation> sortedGroupedQuotations = new ArrayList<>();
List<String> sortedGroupKeys = new ArrayList<>(groupedQuotations.keySet());
// 根据分组类型对分组键进行排序(默认按升序)
if (groupBy == 1) {
// 按等级数字排序
sortedGroupKeys.sort((k1, k2) -> {
try {
int level1 = Integer.parseInt(k1.replace("等级", ""));
int level2 = Integer.parseInt(k2.replace("等级", ""));
return level1 - level2; // 默认升序
} catch (NumberFormatException e) {
return k1.compareTo(k2);
}
});
} else if (groupBy == 2) {
// 按价格区间排序
sortedGroupKeys.sort((k1, k2) -> {
BigDecimal min1 = getPriceRangeMin(k1);
BigDecimal min2 = getPriceRangeMin(k2);
return min1.compareTo(min2); // 默认升序
});
} else if (groupBy == 3) {
// 按评价等级排序
sortedGroupKeys.sort((k1, k2) -> {
double rate1 = getRatingGroupRate(k1);
double rate2 = getRatingGroupRate(k2);
return Double.compare(rate1, rate2); // 默认升序
});
}
// 按排序后的分组键重新组装数据
for (String groupKey : sortedGroupKeys) {
sortedGroupedQuotations.addAll(groupedQuotations.get(groupKey));
}
allQuotations = sortedGroupedQuotations;
}
// 7. 手动分页处理(因为需要先排序和分组)
int total = allQuotations.size();
int fromIndex = Math.max(0, (pageNum - 1) * pageSize);
int toIndex = Math.min(fromIndex + pageSize, total);
List<UserDemandQuotation> pageQuotations = fromIndex < toIndex ?
allQuotations.subList(fromIndex, toIndex) : new ArrayList<>();
// 8. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
for (UserDemandQuotation quotation : pageQuotations) {
Map<String, Object> quoteMap = new HashMap<>();
// 基本信息
quoteMap.put("id", quotation.getId());
quoteMap.put("orderId", quotation.getOrderid());
quoteMap.put("money", quotation.getMoney());
quoteMap.put("status", quotation.getStatus());
quoteMap.put("statusText", getQuotationStatusText(quotation.getStatus()));
// 时间信息
quoteMap.put("quotationTime", quotation.getQuotationTime() != null ? sdf.format(quotation.getQuotationTime()) : "");
// 师傅信息
if (quotation.getWorkerid() != null) {
Users worker = usersService.selectUsersById(quotation.getWorkerid());
if (worker != null) {
quoteMap.put("workerId", worker.getId());
quoteMap.put("workerName", worker.getName());
quoteMap.put("workerAvatar", AppletControllerUtil.buildImageUrl(worker.getAvatar()));
quoteMap.put("workerPhone", worker.getPhone());
quoteMap.put("workerJobNo", worker.getJobNumber());
}
}
resultList.add(quoteMap);
}
// 9. 构建分页信息
int lastPage = (int) Math.ceil((double) total / pageSize);
int from = total > 0 ? (pageNum - 1) * pageSize + 1 : 0;
int to = Math.min(pageNum * pageSize, total);
// 10. 构建返回数据格式
Map<String, Object> responseData = new HashMap<>();
responseData.put("current_page", pageNum);
responseData.put("data", resultList);
responseData.put("from", from);
responseData.put("last_page", lastPage);
responseData.put("per_page", pageSize);
responseData.put("to", to);
responseData.put("total", total);
// 构建分页链接信息
String baseUrl = "https://www.huafurenjia.cn/api/quotation/list";
responseData.put("first_page_url", baseUrl + "?pageNum=1&oid=" + oid);
responseData.put("last_page_url", baseUrl + "?pageNum=" + lastPage + "&oid=" + oid);
responseData.put("next_page_url", pageNum < lastPage ?
baseUrl + "?pageNum=" + (pageNum + 1) + "&oid=" + oid : null);
responseData.put("prev_page_url", pageNum > 1 ?
baseUrl + "?pageNum=" + (pageNum - 1) + "&oid=" + oid : null);
responseData.put("path", baseUrl);
// 构建links数组
List<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageNum > 1 ?
baseUrl + "?pageNum=" + (pageNum - 1) + "&oid=" + oid : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageNum < lastPage ?
baseUrl + "?pageNum=" + (pageNum + 1) + "&oid=" + oid : null);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
links.add(nextLink);
responseData.put("links", links);
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
logger.error("查询报价列表失败:", e);
return AppletControllerUtil.appletError("查询报价列表失败:" + e.getMessage());
}
}
/**
* 获取报价状态文本
* @param status 报价状态
* @return 状态文本
*/
private String getQuotationStatusText(Long status) {
if (status == null) return "未知";
switch (status.intValue()) {
case 1: return "已报价";
case 2: return "已选中";
default: return "未知";
}
}
/**
* 获取师傅好评率
* @param workerId 师傅ID
* @return 好评率0-1之间的小数
*/
private double getWorkerGoodRate(Long workerId) {
try {
OrderComment commentQuery = new OrderComment();
commentQuery.setWorkerId(workerId);
List<OrderComment> workerComments = orderCommentService.selectOrderCommentList(commentQuery);
if (workerComments.isEmpty()) {
return 0.0;
}
int goodNum = 0;
for (OrderComment c : workerComments) {
if (c.getNumType() != null && c.getNumType() == 1) {
goodNum++;
}
}
return (double) goodNum / workerComments.size();
} catch (Exception e) {
logger.warn("计算师傅好评率失败师傅ID: " + workerId + ", 错误: " + e.getMessage());
return 0.0;
}
}
/**
* 获取师傅综合评分
* @param quotation 报价信息
* @return 综合评分
*/
private double getWorkerComprehensiveScore(UserDemandQuotation quotation) {
try {
double score = 0.0;
// 1. 价格评分价格越低分数越高满分30分
BigDecimal price = quotation.getMoney() != null ? quotation.getMoney() : BigDecimal.ZERO;
if (price.compareTo(BigDecimal.ZERO) > 0) {
// 假设价格在100-1000之间价格越低分数越高
double priceScore = Math.max(0, 30 - (price.doubleValue() - 100) / 30);
score += priceScore;
}
// 2. 等级评分等级越高分数越高满分30分
Users worker = usersService.selectUsersById(quotation.getWorkerid());
if (worker != null && worker.getLevel() != null) {
double levelScore = Math.min(30, worker.getLevel() * 10); // 假设等级1-3每级10分
score += levelScore;
}
// 3. 评价评分好评率越高分数越高满分40分
double goodRate = getWorkerGoodRate(quotation.getWorkerid());
double ratingScore = goodRate * 40;
score += ratingScore;
return score;
} catch (Exception e) {
logger.warn("计算师傅综合评分失败报价ID: " + quotation.getId() + ", 错误: " + e.getMessage());
return 0.0;
}
}
/**
* 获取价格区间分组
* @param price 价格
* @return 价格区间分组名称
*/
private String getPriceRangeGroup(BigDecimal price) {
if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
return "价格未知";
}
double priceValue = price.doubleValue();
if (priceValue < 100) {
return "100元以下";
} else if (priceValue < 200) {
return "100-200元";
} else if (priceValue < 300) {
return "200-300元";
} else if (priceValue < 500) {
return "300-500元";
} else if (priceValue < 1000) {
return "500-1000元";
} else {
return "1000元以上";
}
}
/**
* 获取价格区间的最小值
* @param groupKey 分组键
* @return 最小值
*/
private BigDecimal getPriceRangeMin(String groupKey) {
switch (groupKey) {
case "100元以下": return new BigDecimal("0");
case "100-200元": return new BigDecimal("100");
case "200-300元": return new BigDecimal("200");
case "300-500元": return new BigDecimal("300");
case "500-1000元": return new BigDecimal("500");
case "1000元以上": return new BigDecimal("1000");
default: return BigDecimal.ZERO;
}
}
/**
* 获取评价等级分组
* @param goodRate 好评率
* @return 评价等级分组名称
*/
private String getRatingGroup(double goodRate) {
if (goodRate >= 0.9) {
return "优秀评价(90%+)";
} else if (goodRate >= 0.8) {
return "良好评价(80-90%)";
} else if (goodRate >= 0.7) {
return "一般评价(70-80%)";
} else if (goodRate >= 0.6) {
return "较差评价(60-70%)";
} else {
return "差评(60%以下)";
}
}
/**
* 获取评价等级分组的基准评分
* @param groupKey 分组键
* @return 基准评分
*/
private double getRatingGroupRate(String groupKey) {
switch (groupKey) {
case "优秀评价(90%+)": return 0.95;
case "良好评价(80-90%)": return 0.85;
case "一般评价(70-80%)": return 0.75;
case "较差评价(60-70%)": return 0.65;
case "差评(60%以下)": return 0.3;
default: return 0.0;
}
}
/**
* 获取排序方式文本
* @param sortType 排序类型
* @param fieldName 字段名称
* @return 排序方式文本
*/
private String getSortText(Integer sortType, String fieldName) {
if (sortType == null || sortType == 0) return fieldName + "不排序";
switch (sortType) {
case 1: return fieldName + "升序";
case 2: return fieldName + "降序";
default: return fieldName + "不排序";
}
}
/**
* 获取分组方式文本
* @param groupBy 分组方式
* @return 分组方式文本
*/
private String getGroupByText(Integer groupBy) {
if (groupBy == null) return "不分组";
switch (groupBy) {
case 1: return "按师傅等级分组";
case 2: return "按价格区间分组";
case 3: return "按评价等级分组";
default: return "不分组";
}
}
/**
* 构建分组详情
* @param groupedQuotations 分组后的报价数据
* @param groupBy 分组方式
* @return 分组详情
*/
private List<Map<String, Object>> buildGroupDetails(Map<String, List<UserDemandQuotation>> groupedQuotations, Integer groupBy) {
List<Map<String, Object>> groupDetails = new ArrayList<>();
for (Map.Entry<String, List<UserDemandQuotation>> entry : groupedQuotations.entrySet()) {
Map<String, Object> groupDetail = new HashMap<>();
groupDetail.put("groupName", entry.getKey());
groupDetail.put("count", entry.getValue().size());
// 计算该分组的平均价格
BigDecimal totalPrice = BigDecimal.ZERO;
int validPriceCount = 0;
for (UserDemandQuotation quotation : entry.getValue()) {
if (quotation.getMoney() != null) {
totalPrice = totalPrice.add(quotation.getMoney());
validPriceCount++;
}
}
if (validPriceCount > 0) {
BigDecimal avgPrice = totalPrice.divide(BigDecimal.valueOf(validPriceCount), 2, BigDecimal.ROUND_HALF_UP);
groupDetail.put("avgPrice", avgPrice);
} else {
groupDetail.put("avgPrice", BigDecimal.ZERO);
}
// 根据分组类型添加特定信息
if (groupBy == 1) {
// 师傅等级分组
groupDetail.put("groupType", "level");
} else if (groupBy == 2) {
// 价格区间分组
groupDetail.put("groupType", "price");
} else if (groupBy == 3) {
// 评价等级分组
groupDetail.put("groupType", "rating");
}
groupDetails.add(groupDetail);
}
return groupDetails;
}
/**
* 修改预约时间接口
* @param params {"id":"订单id","make_time":"预约时间"}
* @return 操作结果
*/
@PostMapping("/api/service/update/make/time/")
public AjaxResult updateMakeTime(@RequestBody Map<String, Object> params) {
try {
// 1. 校验参数
if (params == null || params.get("id") == null || params.get("make_time") == null) {
return AjaxResult.error("参数id和make_time不能为空");
}
Long id;
try {
id = Long.valueOf(params.get("id").toString());
} catch (Exception e) {
return AjaxResult.error("id格式错误");
}
String makeTime = params.get("make_time").toString();
// 2. 查询订单
Order order = orderService.selectOrderById(id);
if (order == null) {
return AjaxResult.error("订单不存在");
}
// 3. 解析预约时间
// 预约时间格式2025-07-21 8:00-10:00
String[] arr = makeTime.split(" ");
if (arr.length != 2) {
return AjaxResult.error("make_time格式错误需为'yyyy-MM-dd HH:mm-HH:mm'");
}
String dateStr = arr[0];
String hourStr = arr[1];
Long makeTimeStamp = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateStr);
makeTimeStamp = date.getTime() / 1000;
} catch (Exception e) {
return AjaxResult.error("日期格式错误");
}
// 4. 更新订单
order.setMakeTime(makeTimeStamp);
order.setMakeHour(hourStr);
int result = orderService.updateOrder(order);
if (result <= 0) {
return AjaxResult.error("预约时间修改失败");
}
return AjaxResult.success("预约时间修改成功");
} catch (Exception e) {
logger.error("修改预约时间失败:", e);
return AjaxResult.error("修改预约时间失败:" + e.getMessage());
}
}
/**
* 跟单功能接口
* @param params {"oid":订单ID, "content":跟单内容}
* @param request HTTP请求对象
* @return 操作结果
*/
@PostMapping("/api/order/follow")
public AjaxResult followOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验参数
if (params == null || params.get("oid") == null || params.get("content") == null) {
return AppletControllerUtil.appletWarning("参数oid和content不能为空");
}
Long oid;
try {
oid = Long.valueOf(params.get("oid").toString());
} catch (Exception e) {
return AppletControllerUtil.appletWarning("oid格式错误");
}
String content = params.get("content").toString();
// 2. 校验订单是否存在
Order order = orderService.selectOrderById(oid);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 3. 查询最新一条日志获取type
BigDecimal logType = null;
try {
OrderLog latestLog = orderLogService.selectDataTheFirstNew(oid);
if (latestLog != null && latestLog.getType() != null) {
logType = latestLog.getType();
}
} catch (Exception e) {
// 查询异常logType保持null
}
// 4. 构造订单日志对象
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setWorkerId(order.getWorkerId());
orderLog.setWorkerLogId(order.getWorkerId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("师傅跟单");
orderLog.setType(logType); // 跟单type与最新日志一致
// content格式为{"name":内容}
JSONObject json = new JSONObject();
json.put("name", content);
orderLog.setContent(json.toJSONString());
// 5. 插入日志
int result = orderLogService.insertOrderLog(orderLog);
if (result <= 0) {
return AppletControllerUtil.appletWarning("跟单日志插入失败");
}
return AppletControllerUtil.appletSuccess("跟单成功");
} catch (Exception e) {
logger.error("跟单失败:", e);
return AppletControllerUtil.appletError("跟单失败:" + e.getMessage());
}
}
/**
* 区域列表接口
* @param pageNum 页码
* @param pageSize 每页数量
* @return 区域分页列表
*/
@GetMapping("/api/area/list")
public AjaxResult getAreaList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "220") int pageSize) {
try {
List<DiyCity> allList = diyCityService.selectDiyCityList(new DiyCity());
int total = allList.size();
int fromIndex = Math.max(0, (pageNum - 1) * pageSize);
int toIndex = Math.min(fromIndex + pageSize, total);
List<DiyCity> pageList = fromIndex < toIndex ? allList.subList(fromIndex, toIndex) : new ArrayList<>();
// 只返回title和id
List<Map<String, Object>> simpleList = new ArrayList<>();
for (DiyCity city : pageList) {
Map<String, Object> map = new HashMap<>();
map.put("id", city.getId());
map.put("title", city.getTitle());
simpleList.add(map);
}
Map<String, Object> result = new HashMap<>();
result.put("total", total);
result.put("pageNum", pageNum);
result.put("pageSize", pageSize);
result.put("data", simpleList);
return AjaxResult.success(result);
} catch (Exception e) {
logger.error("查询区域列表失败:", e);
return AjaxResult.error("查询区域列表失败:" + e.getMessage());
}
}
/**
* 技能列表接口
* @param pageNum 页码
* @param pageSize 每页数量
* @return 技能分页列表
*/
@GetMapping("/api/skill/list")
public AjaxResult getSkillList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
@RequestParam(value = "pageSize", defaultValue = "200") int pageSize) {
try {
List<SiteSkill> allList = siteSkillService.selectSiteSkillList(new SiteSkill());
int total = allList.size();
int fromIndex = Math.max(0, (pageNum - 1) * pageSize);
int toIndex = Math.min(fromIndex + pageSize, total);
List<SiteSkill> pageList = fromIndex < toIndex ? allList.subList(fromIndex, toIndex) : new ArrayList<>();
// 只返回title和id
List<Map<String, Object>> simpleList = new ArrayList<>();
for (SiteSkill skill : pageList) {
Map<String, Object> map = new HashMap<>();
map.put("id", skill.getId());
map.put("title", skill.getTitle());
simpleList.add(map);
}
Map<String, Object> result = new HashMap<>();
result.put("total", total);
result.put("pageNum", pageNum);
result.put("pageSize", pageSize);
result.put("data", simpleList);
return AjaxResult.success(result);
} catch (Exception e) {
logger.error("查询技能列表失败:", e);
return AjaxResult.error("查询技能列表失败:" + e.getMessage());
}
}
/**
* 评论删除接口
* @param id 评论ID
* @return 操作结果
*/
@PostMapping("/api/goods/order/del/comment/{id}")
public AjaxResult deleteOrderComment(@PathVariable("id") Long id) {
try {
// 1. 查询评论
OrderComment comment = new OrderComment();
comment.setOid(id);
List<OrderComment> comments = orderCommentService.selectOrderCommentList(comment);
if (!comments.isEmpty()){
for (OrderComment c : comments){
c.setStatus(0);
orderCommentService.updateOrderComment(c);
}
return AppletControllerUtil.appletSuccess("评论删除成功");
}
} catch (Exception e) {
logger.error("评论删除失败:", e);
return AppletControllerUtil.appletError("评论删除失败:" + e.getMessage());
}
return AppletControllerUtil.appletSuccess("评论删除成功");
}
/**
* 拼团预约接口
* @param params {id, address_id, make_time}
* @return 操作结果
*/
@PostMapping("/api/group/order/appoint")
public AjaxResult groupOrderAppoint(@RequestBody Map<String, Object> params) {
try {
// 1. 校验参数
if (params == null || params.get("id") == null || params.get("address_id") == null || params.get("make_time") == null) {
return AppletControllerUtil.appletWarning("参数id、address_id、make_time不能为空");
}
Long id = Long.valueOf(params.get("id").toString());
Long addressId = Long.valueOf(params.get("address_id").toString());
String makeTimeStr = params.get("make_time").toString();
String type = params.get("type").toString();;
// 2. 查询订单
Order order = orderService.selectOrderById(id);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 3. 查询地址
UserAddress userAddress = userAddressService.selectUserAddressById(addressId);
if (userAddress == null) {
return AppletControllerUtil.appletWarning("地址不存在");
}
// 4. 解析预约时间
Long makeTime = null;
String makeHour = "";
if (makeTimeStr != null && !makeTimeStr.isEmpty()) {
String[] arr = makeTimeStr.split(" ");
if (arr.length == 2) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(arr[0]);
makeTime = date.getTime() / 1000;
makeHour = arr[1];
} catch (Exception e) {
return AppletControllerUtil.appletWarning("make_time格式错误需为'yyyy-MM-dd HH:mm'");
}
} else {
return AppletControllerUtil.appletWarning("make_time格式错误需为'yyyy-MM-dd HH:mm'");
}
}
// 5. 更新订单信息
order.setAddressId(userAddress.getId());
order.setName(userAddress.getName());
order.setPhone(userAddress.getPhone());
order.setAddress(userAddress.getAddressInfo());
order.setMakeTime(makeTime);
order.setMakeHour(makeHour);
order.setStatus(1L); // 待接单
order.setJsonStatus(0); // 预约状态
int updateResult = orderService.updateOrder(order);
if (updateResult <= 0) {
return AppletControllerUtil.appletWarning("预约失败,订单更新异常");
}
// 6. 添加订单日志
OrderLog orderLog = new OrderLog();
orderLog.setOid(order.getId());
orderLog.setOrderId(order.getOrderId());
orderLog.setTitle("拼团预约");
orderLog.setType(BigDecimal.valueOf(1.0));
JSONObject json = new JSONObject();
json.put("name", "拼团预约成功,待接单");
orderLog.setContent(json.toJSONString());
int updateResult1 = orderLogService.insertOrderLog(orderLog);
//开始派单
if (updateResult1>0){
DispatchUtil.dispatchOrder(order.getId());
}
if (type.equals("2")){
UserGroupBuying userGroupBuying = userGroupBuyingService.selectUserGroupBuyingByptorderid(order.getOrderId());
if (userGroupBuying != null){
userGroupBuyingService.deleteUserGroupBuyingById(userGroupBuying.getId());
}
UsersPayBefor payBefor = usersPayBeforService.selectUsersPayBeforByOrderId(order.getOrderId());
if (payBefor != null){
payBefor.setGrouporderid(order.getOrderId());
usersPayBeforService.updateUsersPayBefor(payBefor);
}
}
return AppletControllerUtil.appletSuccess("拼团预约成功");
} catch (Exception e) {
logger.error("拼团预约失败:", e);
return AppletControllerUtil.appletError("拼团预约失败:" + e.getMessage());
}
}
/**
* 好友支付预览接口
* @param orderid 预支付订单号
* @return 预览信息
*/
@GetMapping("/api/friend/pay/preview")
public AjaxResult friendPayPreview(@RequestParam("orderid") String orderid) {
try {
// 1. 查询预支付信息
UsersPayBefor payBefor = usersPayBeforService.selectUsersPayBeforByOrderId(orderid);
if (payBefor == null) {
return AppletControllerUtil.appletWarning("预支付订单不存在");
}
Users user = usersService.selectUsersById(payBefor.getUid());
Map<String, Object> result = new HashMap<>();
result.put("needPay", payBefor.getAllmoney());
result.put("paystatus", payBefor.getStatus());
result.put("friendname", user.getName());
// 剩余支付时间如有createTime字段保留一分钟倒计时演示
long leftSeconds = 60;
try {
if (payBefor.getCreateTime() != null) {
long now = System.currentTimeMillis();
long create = payBefor.getCreateTime().getTime();
leftSeconds = Math.max(0, 60 - (now - create) / 1000);
}
} catch (Exception e) {
// 没有createTime字段则忽略
}
result.put("leftSeconds", leftSeconds);
List<Map<String, Object>> goodsList = new ArrayList<>();
// 2. 判断服务类型
if (payBefor.getServicetype() != null && payBefor.getServicetype() == 1L) {
// 服务类
Order order = orderService.selectOrderByOrderId(orderid);
// if (order == null) {
// return AppletControllerUtil.appletWarning("服务订单不存在");
// }
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(payBefor.getServiceid());
if (serviceGoods == null) {
return AppletControllerUtil.appletWarning("服务商品不存在");
}
Map<String, Object> item = new HashMap<>();
item.put("shopName", "服务预约");
item.put("title", serviceGoods.getTitle());
item.put("sku",AppletControllerUtil.parseSkuStringToObject(payBefor.getSku()));
item.put("img", AppletControllerUtil.buildImageUrl(serviceGoods.getIcon())); // 假设fileData为图片
item.put("price", payBefor.getAllmoney());
if (order != null){
item.put("num",order.getNum());
}else{
item.put("num",1);
}
goodsList.add(item);
} else if (payBefor.getServicetype() != null && payBefor.getServicetype() == 2L) {
// 商品类
GoodsOrder goodsOrderQuery = new GoodsOrder();
goodsOrderQuery.setMainOrderId(orderid);
List<GoodsOrder> goodsOrders = goodsOrderService.selectGoodsOrderList(goodsOrderQuery);
for (GoodsOrder goodsOrder : goodsOrders) {
Map<String, Object> item = new HashMap<>();
ServiceGoods serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsOrder.getProductId());
if (serviceGoods != null){
// 兼容无getShopName方法
item.put("shopName", "商城订单");
item.put("title", serviceGoods.getTitle());
// 兼容无getProductIcon方法
item.put("img",AppletControllerUtil.buildImageUrl(serviceGoods.getIcon()));
item.put("price", goodsOrder.getPayPrice());
item.put("num", goodsOrder.getNum());
goodsList.add(item);
}
}
} else {
return AppletControllerUtil.appletWarning("未知订单类型");
}
result.put("goodsList", goodsList);
// 3. 代付说明
// result.put("payDesc", "1. 代付前请先与好友确认无误,避免误支付。\n2. 付款成功后,订单将自动进入处理流程。");
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("好友支付预览失败:", e);
return AppletControllerUtil.appletError("好友支付预览失败:" + e.getMessage());
}
}
/**
* 协议类型接口,返回写死的数据
*/
@GetMapping("/api/public/content/type")
public AjaxResult getContentType() {
List<Map<String, Object>> data = new ArrayList<>();
Map<String, Object> item1 = new HashMap<>();
item1.put("id", 1);
item1.put("text", "用户协议");
item1.put("is_single", true);
data.add(item1);
Map<String, Object> item2 = new HashMap<>();
item2.put("id", 2);
item2.put("text", "隐私协议");
item2.put("is_single", true);
data.add(item2);
return AjaxResult.success(data);
}
/**
* 协议类型接口,返回写死的数据
*/
@GetMapping("/api/user/logout")
public AjaxResult getusertest(HttpServletRequest request) {
// 1. 校验用户登录
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
user.setLoginStatus(1);
int count = usersService.updateUsers(user);
if (count > 0) {
return AppletControllerUtil.appletSuccess("用户登出成功");
}else{
return AppletControllerUtil.appletWarning("用户登出失败");
}
}
/**
* 查询内容详情接口
* @param id 内容ID
* @return 内容详情
*/
@GetMapping("/api/public/content/info/{id}")
public AjaxResult getContentInfo(@PathVariable("id") Long id) {
try {
Content content = contentService.selectContentById(id);
if (content == null) {
return AppletControllerUtil.appletWarning("内容不存在");
}
return AjaxResult.success(content);
} catch (Exception e) {
logger.error("查询内容详情失败:", e);
return AppletControllerUtil.appletError("查询内容详情失败:" + e.getMessage());
}
}
// /**
// * 统计bigtype为1、2、3且status!=4的订单数量针对当前用户
// * @return 统计结果
// */
// @GetMapping("/api/order/bigtype/count")
// public AjaxResult getOrderCountByBigtype(HttpServletRequest request) {
// try {
// String token = request.getHeader("token");
// Map<String, Object> 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("用户信息获取失败");
// }
// List<OrderTypeCount> counts = orderService.selectOrderCountByBigtype(user.getId());
// return AjaxResult.success(counts);
// } catch (Exception e) {
// logger.error("统计订单数量失败:", e);
// return AjaxResult.error("统计订单数量失败:" + e.getMessage());
// }
// }
/**
* 查看物料详情接口
* @param id 物料id
* @return 物料详情
*/
@GetMapping("/api/material/detail")
public AjaxResult getMaterialDetail(@RequestParam("id") Long id) {
try {
QuoteMaterial material = quoteMaterialService.selectQuoteMaterialById(id);
if (material == null) {
return AjaxResult.error("物料不存在");
}
Map<String, Object> result = new HashMap<>();
result.put("id", material.getId());
result.put("title", material.getTitle());
result.put("typeId", material.getTypeId());
result.put("typeName", material.getTypeName());
result.put("goodId", material.getGoodId());
result.put("serviceName", material.getServiceName());
result.put("price", material.getPrice());
result.put("unit", material.getUnit());
result.put("image", material.getImage());
// 格式化manyimages为数组
if (material.getManyimages() != null && !material.getManyimages().trim().isEmpty()) {
result.put("manyimages", JSONArray.parseArray(material.getManyimages()));
} else {
result.put("manyimages", new JSONArray());
}
if (StringUtils.isNotBlank(material.getContent())&&StringUtils.isNotBlank(material.getManyimages())){
result.put("showtype", 1);
}else{
result.put("showtype", 2);
}
result.put("content", material.getContent());
result.put("profit", material.getProfit());
result.put("commissions", material.getCommissions());
result.put("iscommissions", material.getIscommissions());
// 可根据需要添加更多字段
return AjaxResult.success(result);
} catch (Exception e) {
logger.error("查询物料详情失败:", e);
return AjaxResult.error("查询物料详情失败:" + e.getMessage());
}
}
@GetMapping("/api/worker/stat")
public AjaxResult getWorkerStat(HttpServletRequest request) {
try {
// 1. 校验用户登录
String token = request.getHeader("token");
Map<String, Object> 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 workerId = user.getId();
// 2. 今日单量
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String todayStr = sdf.format(new Date());
Date todayStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(todayStr + " 00:00:00");
Date todayEnd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(todayStr + " 23:59:59");
Order dayOrder = new Order();
dayOrder.setWorkerId(workerId);
dayOrder.setReceiveTimeStart(todayStart);
dayOrder.setReceiveTimeEnd(todayEnd);
int dayCount = orderService.selectOrderList(dayOrder).size();
// 3. 本月单量
String monthStartStr = todayStr.substring(0, 8) + "01 00:00:00";
Date monthStart = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(monthStartStr);
Order monthOrder = new Order();
monthOrder.setWorkerId(workerId);
monthOrder.setType(1);
monthOrder.setReceiveTimeStart(monthStart);
monthOrder.setReceiveTimeEnd(todayEnd);
int monthCount = orderService.selectOrderList(monthOrder).size();
// 4. 本月收入
BigDecimal monthIncome = workerMoneyLogService.selectWorkerMoneySumPrice(workerId.intValue());
if (monthIncome == null) monthIncome = BigDecimal.ZERO;
// 5. 配置信息
SiteConfig config = new SiteConfig();
config.setName("config_one");
List<SiteConfig> configList = siteConfigService.selectSiteConfigList(config);
Map<String, Object> configValue = new HashMap<>();
if (configList != null && !configList.isEmpty()) {
String value = configList.get(0).getValue();
if (value != null && !value.trim().isEmpty()) {
configValue = com.alibaba.fastjson.JSONObject.parseObject(value, Map.class);
}
}
// 6. 是否需要签到
boolean sign = true;
if (user.getWorkerTime() != null) {
if (sdf.format(user.getWorkerTime()).equals(todayStr)) {
sign = false;
}
}
// 7. 返回数据
Map<String, Object> data = new HashMap<>();
data.put("day_count", dayCount);
data.put("mouth_count", monthCount);
data.put("income", monthIncome);
data.put("user", user);
data.put("sign", sign);
data.put("config", configValue);
return AppletControllerUtil.appletSuccess(data);
} catch (Exception e) {
return AppletControllerUtil.appletError("首页统计异常:" + e.getMessage());
}
}
@PostMapping("/api/workerdata/index")
public AjaxResult workerdataIndex(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 校验用户登录
String token = request.getHeader("token");
Map<String, Object> 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 limit = 10;
if (params.get("limit") != null) {
try { limit = Integer.parseInt(params.get("limit").toString()); } catch (Exception ignore) {}
}
int pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum").toString()) : 1;
int offset = (pageNum - 1) * limit;
// 2. 师傅等级图片
if (user.getLevel() != null) {
WorkerLevel levelInfo = workerLevelService.selectWorkerLevelByLevel(Long.valueOf(user.getLevel()));
if (levelInfo != null) {
user.setLevelInfo(levelInfo);
user.setLevelImg(levelInfo.getImage());
}
}
// 3. 质保金、累计佣金、佣金为0处理
if (user.getMargin() == null) user.setMargin(BigDecimal.ZERO);
if (user.getTotalComm() == null) user.setTotalComm(BigDecimal.ZERO);
if (user.getCommission() == null) user.setCommission(BigDecimal.ZERO);
// 4. 师傅技能
if (user.getSkillIds() != null && !user.getSkillIds().trim().isEmpty()) {
List<String> skillArr = new ArrayList<>();
List<String> skillIds = parseJsonIdList(user.getSkillIds());
for (String sid : skillIds) {
SiteSkill skill = siteSkillService.selectSiteSkillById(Long.valueOf(sid));
if (skill != null) {
Map<String, Object> skillMap = new HashMap<>();
skillMap.put("id", skill.getId());
skillMap.put("title", skill.getTitle());
skillArr.add(skillMap.toString());
}
}
user.setSkillArr(skillArr);
}
// 5. 师傅服务地区
if (user.getServiceCityIds() != null && !user.getServiceCityIds().trim().isEmpty()) {
List<Object> cityArr = new ArrayList<>();
List<String> cityIds = parseJsonIdList(user.getServiceCityIds());
for (String cid : cityIds) {
DiyCity city = diyCityService.selectDiyCityById(Long.valueOf(cid).intValue());
if (city != null) {
Map<String, Object> cityMap = new HashMap<>();
cityMap.put("id", city.getId());
cityMap.put("title", city.getTitle());
cityArr.add(cityMap);
}
}
user.setServiceCityArr(cityArr);
}
// 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);
}
}
// 7. 查询师傅所有服务订单IDLog表worker_id=当前师傅取oid
List<Long> oids = orderLogService.selectOidListByWorkerId(user.getId());
// 8. 查询评价Comment表oid in oids支持type筛选分页
List<Map<String, Object>> dataList = new ArrayList<>();
Map<String, Object> commentStat = new HashMap<>();
double totalNum = 0;
int totalCount = 0;
Long type = params.get("type") != null ? Long.valueOf(params.get("type").toString()) : null;
if (!oids.isEmpty()) {
List<OrderComment> comments = orderCommentService.selectOrderCommentListByOidsAndType(oids, type, offset, limit);
for (OrderComment c : comments) {
Map<String, Object> cMap = new HashMap<>();
Users u = usersService.selectUsersById(c.getUid());
cMap.put("id", c.getId());
cMap.put("uid", c.getUid());
cMap.put("images", c.getImages());
cMap.put("content", c.getContent());
cMap.put("num", c.getNum());
cMap.put("time", c.getCreatedAt());
cMap.put("user", u != null ? Map.of("id", u.getId(), "name", u.getName(), "avatar", u.getAvatar()) : null);
dataList.add(cMap);
totalNum += c.getNum() != null ? c.getNum() : 0;
totalCount++;
}
// 统计好评/中评/差评数量
commentStat.put("one", orderCommentService.countByOidsAndType(oids, 1L));
commentStat.put("two", orderCommentService.countByOidsAndType(oids, 2L));
commentStat.put("three", orderCommentService.countByOidsAndType(oids, 3L));
commentStat.put("total", totalCount > 0 ? Math.round(totalNum / totalCount * 10.0) / 10.0 : 0);
} else {
commentStat.put("one", 0);
commentStat.put("two", 0);
commentStat.put("three", 0);
commentStat.put("total", 0);
}
Map<String, Object> result = new HashMap<>();
result.put("user", user);
result.put("data", dataList);
result.put("comment", commentStat);
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
return AppletControllerUtil.appletError("获取个人中心信息失败:" + e.getMessage());
}
}
// 辅助方法解析JSON数组字符串为List<String>
private List<String> parseJsonIdList(String json) {
try {
return com.alibaba.fastjson.JSONArray.parseArray(json, String.class);
} catch (Exception e) {
return new ArrayList<>();
}
}
/**
* 商品确认收货接口
* @param id 商品订单ID
* @param request HTTP请求对象
* @return 确认收货结果
*/
@GetMapping("/api/goods/order/confirm/receipt")
public AjaxResult confirmGoodsOrderReceipt(@RequestParam("id") Long id, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 获取商品订单ID
Long orderId = id;
if (orderId == null) {
return AppletControllerUtil.appletError("商品订单ID不能为空");
}
// 3. 查询商品订单
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
// // 4. 验证订单所属用户
// if (!goodsOrder.getUid().equals(user.getId())) {
// return AppletControllerUtil.appletError("无权操作此订单");
// }
// 5. 验证订单状态(只有已发货状态才能确认收货)
if (goodsOrder.getStatus() != 3L) {
return AppletControllerUtil.appletError("订单状态不正确,无法确认收货");
}
// 6. 更新订单状态为已收货
goodsOrder.setStatus(4L);
int updateResult = goodsOrderService.updateGoodsOrder(goodsOrder);
if (updateResult > 0) {
// 7. 添加订单日志
com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
jsonObject.put("name", "用户确认收货");
OrderUtil.addgoodsorderlog(goodsOrder.getId(), goodsOrder.getOrderId(), "确认收货", "3", jsonObject, 2L);
Map<String, Object> result = new HashMap<>();
result.put("message", "确认收货成功");
result.put("orderId", goodsOrder.getOrderId());
result.put("status", goodsOrder.getStatus());
//添加购物金消费金
BenefitPointsUtil.processBenefitPoints(goodsOrder.getId(),goodsOrder.getTotalPrice(),"2");
//修改库存及销量
OrderUtil.updateInventoryAndSales(goodsOrder.getOrderId(), 2);
return AppletControllerUtil.appletSuccess(result);
} else {
return AppletControllerUtil.appletError("确认收货失败,请稍后重试");
}
} catch (Exception e) {
logger.error("商品确认收货失败:", e);
return AppletControllerUtil.appletError("确认收货失败:" + e.getMessage());
}
}
/**
* 查询商品订单详情接口
* @param id 订单ID
* @param request HTTP请求对象
* @return 商品订单详情
*/
@GetMapping("/api/goods/order/detail")
public AjaxResult getGoodsOrderDetail(@RequestParam("id") Long id, HttpServletRequest request) {
try {
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 获取订单ID
Long orderId = id;
if (orderId == null) {
return AppletControllerUtil.appletError("订单ID不能为空");
}
// 3. 查询商品订单基本信息
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
// // 4. 验证订单所属用户
// if (!goodsOrder.getUid().equals(user.getId())) {
// return AppletControllerUtil.appletError("无权查看此订单");
// }
// 5. 查询商品基本信息
ServiceGoods serviceGoods = null;
if (goodsOrder.getProductId() != null) {
serviceGoods = serviceGoodsService.selectServiceGoodsById(goodsOrder.getProductId());
}
// // 6. 查询订单日志
// List<OrderLog> orderLogs = orderLogService.selectOrderLogByOrderId(goodsOrder.getOrderId());
// 6. 查询订单日志
OrderLog logQuery = new OrderLog();
logQuery.setOrderId(goodsOrder.getMainOrderId());
logQuery.setOrdertype(2L);
List<OrderLog> logList = orderLogService.selectOrderLogList(logQuery);
List<Map<String, Object>> logArr = new ArrayList<>();
for (OrderLog log : logList) {
Map<String, Object> 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<OrderComment> 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 (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("订单已发货")){
contentObj = JSONObject.parse(log.getContent());
}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", goodsOrder.getStatus());
logMap.put("ordertype", goodsOrder.getType());
logArr.add(logMap);
// if (!log.getTitle().equals("师傅跟单")) {
//
// }
}
// // 7. 构建订单状态时间线
// List<Map<String, Object>> timeline = buildOrderTimeline(goodsOrder, orderLogs);
GoodsOrder goodsOrderDATA = new GoodsOrder();
goodsOrderDATA.setMainOrderId(goodsOrder.getMainOrderId());
List<GoodsOrder> goodsOrderList = goodsOrderService.selectGoodsOrderList(goodsOrderDATA);
List<Map<String, Object>> goodsOrderListDATA = new ArrayList<>();
for (GoodsOrder goodsOrderdata : goodsOrderList) {
ServiceGoods serviceGoods1 = serviceGoodsService.selectServiceGoodsById(goodsOrderdata.getProductId());
if (serviceGoods != null) {
Map<String, Object> productInfo = new HashMap<>();
productInfo.put("id", serviceGoods1.getId());
productInfo.put("title", serviceGoods1.getTitle());
productInfo.put("sub_title", serviceGoods1.getSubTitle());
productInfo.put("icon", AppletControllerUtil.buildImageUrl(serviceGoods1.getIcon()));
productInfo.put("price", goodsOrderdata.getTotalPrice() != null ? goodsOrderdata.getTotalPrice().toString() : "0.00");
productInfo.put("sku",AppletControllerUtil.parseSkuStringToObject(goodsOrderdata.getSku()));
productInfo.put("num", goodsOrderdata.getNum());
goodsOrderListDATA.add(productInfo);
}
}
// 8. 构建商品信息
// Map<String, Object> productInfo = buildProductInfo(goodsOrder, serviceGoods);
// 9. 构建订单信息
Map<String, Object> orderInfo = buildOrderInfo(goodsOrder);
ShopAddress shopAddress = shopAddressService.selectShopAddressById(1L);
// 10. 构建返回结果
Map<String, Object> result = new HashMap<>();
result.put("orderId", goodsOrder.getMainOrderId());
result.put("shopAddress", shopAddress);
result.put("status", goodsOrder.getStatus());
result.put("timeline", logArr);
result.put("product", goodsOrderListDATA);
result.put("orderInfo", orderInfo);
// 11. 添加退货数据(如果有退货信息)
if (goodsOrder.getReturntype() != null || goodsOrder.getReturnreason() != null || goodsOrder.getReturnjson() != null) {
Map<String, Object> returnInfo = new HashMap<>();
returnInfo.put("returntype", goodsOrder.getReturntype());
returnInfo.put("returnreason", goodsOrder.getReturnreason());
if (goodsOrder.getReturnfiledata() != null){
returnInfo.put("returnfiledata",JSONArray.parseArray(goodsOrder.getReturnfiledata()));
}else{
returnInfo.put("returnfiledata", JSONArray.parseArray("[]"));
}
returnInfo.put("returntime", goodsOrder.getReturntime() != null ? dateFormat.format(goodsOrder.getReturntime() ) : null);
if (goodsOrder.getReturnshow() != null){
returnInfo.put("returnshow", com.alibaba.fastjson2.JSONObject.parseObject(goodsOrder.getReturnshow()));
}else{
JSONObject returnJsonObject2 = new JSONObject();
returnJsonObject2.put("title","售后");
returnJsonObject2.put("content","售后处理中,请耐心等待!");
returnInfo.put("returnshow", returnJsonObject2.toJSONString());
}
//returnInfo.put("returnshow", goodsOrder.getReturnshow());
returnInfo.put("returnmoney", goodsOrder.getReturnmoney());
returnInfo.put("returnfinshtime", goodsOrder.getReturnfinshtime()!= null ? dateFormat.format(goodsOrder.getReturnfinshtime() ) : null);
returnInfo.put("returnstatus", goodsOrder.getReturnstatus());
returnInfo.put("returnlogistics", goodsOrder.getReturnlogistics());
returnInfo.put("returnlogisticscode", goodsOrder.getReturnlogisticscode());
// 解析退货流程JSON
if (goodsOrder.getReturnjson() != null && !goodsOrder.getReturnjson().trim().isEmpty()) {
try {
JSONArray returnJsonArray = JSONArray.parseArray(goodsOrder.getReturnjson());
returnInfo.put("returnjson", returnJsonArray);
} catch (Exception e) {
logger.error("解析退货JSON失败", e);
}
} else {
}
result.put("returnInfo", returnInfo);
}
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("查询商品订单详情失败:", e);
return AppletControllerUtil.appletError("查询订单详情失败:" + e.getMessage());
}
}
/**
* 构建商品信息
*/
private Map<String, Object> buildProductInfo(GoodsOrder goodsOrder, ServiceGoods serviceGoods) {
Map<String, Object> productInfo = new HashMap<>();
if (serviceGoods != null) {
productInfo.put("id", serviceGoods.getId());
productInfo.put("title", serviceGoods.getTitle());
productInfo.put("icon",AppletControllerUtil.buildImageUrl(serviceGoods.getIcon()));
productInfo.put("price", serviceGoods.getPrice());
} else {
productInfo.put("id", goodsOrder.getProductId());
productInfo.put("title", goodsOrder.getProductName());
productInfo.put("icon", "");
productInfo.put("price", goodsOrder.getGoodPrice());
}
productInfo.put("num", goodsOrder.getNum());
productInfo.put("sku", AppletControllerUtil.parseSkuStringToObject(goodsOrder.getSku()));
return productInfo;
}
/**
* 构建订单信息
*/
private Map<String, Object> buildOrderInfo(GoodsOrder goodsOrder) {
Map<String, Object> orderInfo = new HashMap<>();
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
UsersPayBefor usersPayBefor = usersPayBeforService.selectUsersPayBeforByOrderId(goodsOrder.getMainOrderId());
// if (usersPayBefor == null){
// usersPayBefor = usersPayBeforService.selectUsersPayBeforByOrderId(goodsOrder.getMainOrderId());
// }
if (usersPayBefor != null){
orderInfo.put("totalPrice", usersPayBefor.getAllmoney());
orderInfo.put("payPrice", usersPayBefor.getAllmoney());
orderInfo.put("deduction", usersPayBefor.getCouponmoney());
orderInfo.put("membermoney", usersPayBefor.getMembermoney());
orderInfo.put("mtmoney", usersPayBefor.getMtmoney());
orderInfo.put("paytype", usersPayBefor.getPaytype());
orderInfo.put("shopmoney", usersPayBefor.getShopmoney());
orderInfo.put("wxmoney", usersPayBefor.getWxmoney());
orderInfo.put("yemoney", usersPayBefor.getYemoney());
}
//orderInfo.put("sku", AppletControllerUtil.parseSkuStringToObject(goodsOrder.getSku()));
orderInfo.put("orderId", goodsOrder.getMainOrderId());
orderInfo.put("postage", goodsOrder.getPostage() != null ? goodsOrder.getPostage() : BigDecimal.ZERO);
// logMap.put("created_at", log.getCreatedAt() != null ? dateFormat.format(log.getCreatedAt()) : null);
orderInfo.put("createdAt", goodsOrder.getCreatedAt() != null ? dateFormat.format(goodsOrder.getCreatedAt()) : null);
orderInfo.put("payTime", goodsOrder.getPayTime() != null ? dateFormat.format( goodsOrder.getPayTime()) : null);
orderInfo.put("transactionId", goodsOrder.getTransactionId());
orderInfo.put("name", goodsOrder.getName());
orderInfo.put("status", goodsOrder.getStatus());
orderInfo.put("phone", goodsOrder.getPhone());
orderInfo.put("address", goodsOrder.getAddress());
orderInfo.put("isself", goodsOrder.getIsself());
orderInfo.put("mark", goodsOrder.getMark());
UserAddress userAddress = userAddressService.selectUserAddressById(goodsOrder.getAddressId());
if (userAddress != null){
orderInfo.put("latitude", userAddress.getLatitude());
orderInfo.put("longitude", userAddress.getLongitude());
}else{
orderInfo.put("latitude", null);
orderInfo.put("longitude", null);
}
// // 计算优惠金额
// BigDecimal totalPrice = goodsOrder.getTotalPrice() != null ? goodsOrder.getTotalPrice() : BigDecimal.ZERO;
// BigDecimal payPrice = goodsOrder.getPayPrice() != null ? goodsOrder.getPayPrice() : BigDecimal.ZERO;
// BigDecimal deduction = goodsOrder.getDeduction() != null ? goodsOrder.getDeduction() : BigDecimal.ZERO;
//
// BigDecimal discountAmount = totalPrice.subtract(payPrice).subtract(deduction);
// orderInfo.put("discountAmount", discountAmount);
return orderInfo;
}
// 辅助方法解析JSON数组字符串为List<String>
/**
* 退货接口
* @param params 请求参数 {"orderId": "订单ID", "refundAmount": "退款金额", "refundType": "退款类别", "refundReason": "退款原因", "voucher": "凭证"}
* @param request HTTP请求对象
* @return 退货处理结果
*/
@PostMapping("/api/goods/order/return")
public AjaxResult returnGoodsOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 获取请求参数
Long orderId = null;
BigDecimal refundAmount = null;
Integer refundType = null;
String refundReason = null;
if (params.get("orderId") != null) {
try {
orderId = Long.valueOf(params.get("orderId").toString());
} catch (NumberFormatException e) {
return AppletControllerUtil.appletError("订单ID格式错误");
}
} else {
return AppletControllerUtil.appletError("订单ID不能为空");
}
if (params.get("refundAmount") != null) {
try {
refundAmount = new BigDecimal(params.get("refundAmount").toString());
} catch (NumberFormatException e) {
return AppletControllerUtil.appletError("退款金额格式错误");
}
} else {
return AppletControllerUtil.appletError("退款金额不能为空");
}
if (params.get("refundType") != null) {
try {
refundType = Integer.valueOf(params.get("refundType").toString());
if (refundType != 1 && refundType != 2) {
return AppletControllerUtil.appletError("退款类别只能是1(仅退款)或2(退货退款)");
}
} catch (NumberFormatException e) {
return AppletControllerUtil.appletError("退款类别格式错误");
}
} else {
return AppletControllerUtil.appletError("退款类别不能为空");
}
refundReason = (String) params.get("refundReason");
if (refundReason == null || refundReason.trim().isEmpty()) {
return AppletControllerUtil.appletError("退款原因不能为空");
}
// 处理附件voucher支持数组格式
Object voucherObj = params.get("voucher");
String voucher = null;
if (voucherObj != null) {
if (voucherObj instanceof String) {
// 如果是字符串,直接使用
voucher = (String) voucherObj;
} else if (voucherObj instanceof List) {
// 如果是List转换为JSON字符串
voucher = JSONArray.toJSONString(voucherObj);
} else {
// 其他情况,转换为字符串
voucher = voucherObj.toString();
}
}
// 3. 查询商品订单
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
// // 4. 验证订单所属用户
// if (!goodsOrder.getUid().equals(user.getId())) {
// return AppletControllerUtil.appletError("无权操作此订单");
// }
// 5. 验证订单状态(只有已收货状态才能申请退货)
// if (goodsOrder.getStatus() != 5L) {
// return AppletControllerUtil.appletError("订单状态不正确,无法申请退货");
// }
// 6. 验证退款金额不能超过支付金额
BigDecimal payPrice = goodsOrder.getPayPrice() != null ? goodsOrder.getPayPrice() : BigDecimal.ZERO;
if (refundAmount.compareTo(payPrice) > 0) {
return AppletControllerUtil.appletError("退款金额不能超过支付金额");
}
// 7. 更新订单退货信息
goodsOrder.setReturntype(Long.valueOf(refundType));
goodsOrder.setReturnreason(refundReason);
goodsOrder.setReturnfiledata(voucher);
goodsOrder.setStatus(20L); // 设置为退货状态
goodsOrder.setReturntime(new Date());
goodsOrder.setReturnstatus(1L);
goodsOrder.setReturnmoney(refundAmount);
// 构建退货日志JSON数组
JSONArray returnJsonArray = new JSONArray();
JSONObject returnJsonObject = new JSONObject();
// returnJsonObject.put("title", refundType == 1 ? "申请仅退款" : "申请退货退款");
returnJsonObject.put("title", "申请退款");
returnJsonObject.put("time",dateFormat.format(new Date()));
returnJsonObject.put("desc", 1);
returnJsonArray.add(returnJsonObject);
JSONObject returnJsonObject2 = new JSONObject();
returnJsonObject2.put("title","退款中");
returnJsonObject2.put("content","平台将在72小时为您处理请耐心等待");
goodsOrder.setReturnshow(returnJsonObject2.toJSONString());
goodsOrder.setReturnjson(returnJsonArray.toJSONString());
// 8. 更新订单
int updateResult = goodsOrderService.updateGoodsOrder(goodsOrder);
if (updateResult > 0) {
// // 9. 添加订单日志
// com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
// jsonObject.put("name", refundType == 1 ? "申请仅退款" : "申请退货退款");
// jsonObject.put("refundAmount", refundAmount);
// jsonObject.put("refundReason", refundReason);
// jsonObject.put("voucher", voucher);
//
// OrderUtil.addgoodsorderlog(goodsOrder.getId(), goodsOrder.getOrderId(),
// refundType == 1 ? "申请仅退款" : "申请退货退款", "6", jsonObject, 2L);
//
// Map<String, Object> result = new HashMap<>();
// result.put("message", "退货申请提交成功");
// result.put("orderId", goodsOrder.getOrderId());
// result.put("status", goodsOrder.getStatus());
// result.put("refundAmount", refundAmount);
// result.put("refundType", refundType);
return AppletControllerUtil.appletSuccess("操作成功");
} else {
return AppletControllerUtil.appletError("退货申请提交失败,请稍后重试");
}
} catch (Exception e) {
logger.error("退货申请失败:", e);
return AppletControllerUtil.appletError("退货申请失败:" + e.getMessage());
}
}
// 辅助方法解析JSON数组字符串为List<String>
/**
* 撤销售后接口
* @param id 订单ID
* @param request HTTP请求对象
* @return 撤销售后结果
*/
@GetMapping("/api/goods/order/cancel/return")
public AjaxResult cancelReturnGoodsOrder(@RequestParam("id") Long id, HttpServletRequest request) {
try {
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 获取订单ID
Long orderId = id;
if (orderId == null) {
return AppletControllerUtil.appletError("订单ID不能为空");
}
// 3. 查询商品订单
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
// 7. 更新订单状态为已完成
goodsOrder.setReturnstatus(7L);
goodsOrder.setStatus(5L);
JSONArray returnfiledataArray = JSON.parseArray(goodsOrder.getReturnjson());
JSONObject returnfiledataObject = new JSONObject();
returnfiledataObject.put("time",dateFormat.format(new Date()));
returnfiledataObject.put("desc",returnfiledataArray.size()+1);
returnfiledataObject.put("title","撤销");
returnfiledataArray.add(returnfiledataObject);
goodsOrder.setReturnjson(returnfiledataArray.toJSONString());
JSONObject returnJsonObject2 = new JSONObject();
returnJsonObject2.put("title","撤销退款");
returnJsonObject2.put("content","撤销退款,平台此条售后记录将不再进行!");
goodsOrder.setReturnshow(returnJsonObject2.toJSONString());
int updateResult = goodsOrderService.updateGoodsOrder(goodsOrder);
if (updateResult > 0) {
return AppletControllerUtil.appletSuccess("操作成功");
} else {
return AppletControllerUtil.appletError("撤销售后失败,请稍后重试");
}
} catch (Exception e) {
logger.error("撤销售后失败:", e);
return AppletControllerUtil.appletError("撤销售后失败:" + e.getMessage());
}
}
// 辅助方法解析JSON数组字符串为List<String>
/**
* 退货添加物流信息接口
* @param params 请求参数 {"id": "订单ID", "logistics": "物流公司", "logisticsCode": "物流单号"}
* @param request HTTP请求对象
* @return 添加物流信息结果
*/
@PostMapping("/api/goods/order/return/logistics")
public AjaxResult addReturnLogistics(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 获取请求参数
Long orderId = null;
String logistics = null;
String logisticsCode = null;
if (params.get("id") != null) {
try {
orderId = Long.valueOf(params.get("id").toString());
} catch (NumberFormatException e) {
return AppletControllerUtil.appletError("订单ID格式错误");
}
} else {
return AppletControllerUtil.appletError("订单ID不能为空");
}
logistics = (String) params.get("logistics");
if (logistics == null || logistics.trim().isEmpty()) {
return AppletControllerUtil.appletError("物流公司不能为空");
}
logisticsCode = (String) params.get("logisticsCode");
if (logisticsCode == null || logisticsCode.trim().isEmpty()) {
return AppletControllerUtil.appletError("物流单号不能为空");
}
// 3. 查询商品订单
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
//
// // 4. 验证订单所属用户
// if (!goodsOrder.getUid().equals(user.getId())) {
// return AppletControllerUtil.appletError("无权操作此订单");
// }
// 5. 验证订单状态(只有退货状态才能添加物流信息)
// if (goodsOrder.getStatus() != 6L) {
// return AppletControllerUtil.appletError("订单状态不正确,无法添加物流信息");
// }
// // 6. 验证是否有退货数据
// if (goodsOrder.getReturntype() == null && goodsOrder.getReturnreason() == null) {
// return AppletControllerUtil.appletError("该订单没有售后申请,无法添加物流信息");
// }
// 7. 更新退货物流信息
goodsOrder.setReturnlogistics(logistics);
goodsOrder.setReturnlogisticscode(logisticsCode);
goodsOrder.setReturnstatus(4L);
JSONArray returnfiledataArray = JSON.parseArray(goodsOrder.getReturnjson());
JSONObject returnfiledataObject = new JSONObject();
returnfiledataObject.put("time",dateFormat.format(new Date()));
returnfiledataObject.put("desc",returnfiledataArray.size()+1);
returnfiledataObject.put("title","待收货");
returnfiledataArray.add(returnfiledataObject);
goodsOrder.setReturnjson(returnfiledataArray.toJSONString());
int updateResult = goodsOrderService.updateGoodsOrder(goodsOrder);
if (updateResult > 0) {
// // 9. 添加订单日志
// com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
// jsonObject.put("name", "添加退货物流信息");
// jsonObject.put("logistics", logistics);
// jsonObject.put("logisticsCode", logisticsCode);
// jsonObject.put("logisticsTime", new Date());
//
// OrderUtil.addgoodsorderlog(goodsOrder.getId(), goodsOrder.getOrderId(), "添加退货物流", "6", jsonObject, 2L);
//
// Map<String, Object> result = new HashMap<>();
// result.put("message", "退货物流信息添加成功");
// result.put("orderId", goodsOrder.getOrderId());
// result.put("logistics", logistics);
// result.put("logisticsCode", logisticsCode);
return AppletControllerUtil.appletSuccess("操作成功");
} else {
return AppletControllerUtil.appletError("退货物流信息添加失败,请稍后重试");
}
} catch (Exception e) {
logger.error("退货物流信息添加失败:", e);
return AppletControllerUtil.appletError("退货物流信息添加失败:" + e.getMessage());
}
}
// 辅助方法解析JSON数组字符串为List<String>
/**
* 评价删除接口
* @param id 订单ID
* @param request HTTP请求对象
* @return 评价删除结果
*/
@GetMapping("/api/goods/order/delete/comment")
public AjaxResult deleteOrderComment(@RequestParam("id") Long id, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 获取订单ID
Long orderId = id;
if (orderId == null) {
return AppletControllerUtil.appletError("订单ID不能为空");
}
// 3. 查询商品订单
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(orderId);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
//
// // 4. 验证订单所属用户
// if (!goodsOrder.getUid().equals(user.getId())) {
// return AppletControllerUtil.appletError("无权操作此订单");
// }
//
// 5. 查询评价数据
OrderComment commentQuery = new OrderComment();
commentQuery.setOid(orderId);
List<OrderComment> commentList = orderCommentService.selectOrderCommentList(commentQuery);
if (commentList == null || commentList.isEmpty()) {
return AppletControllerUtil.appletError("该订单没有评价数据");
}
// 6. 更新评价状态为删除
int updateCount = 0;
for (OrderComment comment : commentList) {
comment.setStatus(0); // 设置为删除状态
int updateResult = orderCommentService.updateOrderComment(comment);
if (updateResult > 0) {
updateCount++;
}
}
if (updateCount > 0) {
// 7. 添加订单日志
com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
jsonObject.put("name", "用户删除评价");
jsonObject.put("deleteTime", new Date());
jsonObject.put("deleteCount", updateCount);
OrderUtil.addgoodsorderlog(goodsOrder.getId(), goodsOrder.getOrderId(), "删除评价", "5", jsonObject, 2L);
Map<String, Object> result = new HashMap<>();
result.put("message", "评价删除成功");
result.put("orderId", goodsOrder.getOrderId());
result.put("deleteCount", updateCount);
return AppletControllerUtil.appletSuccess(result);
} else {
return AppletControllerUtil.appletError("评价删除失败,请稍后重试");
}
} catch (Exception e) {
logger.error("评价删除失败:", e);
return AppletControllerUtil.appletError("评价删除失败:" + e.getMessage());
}
}
// 辅助方法解析JSON数组字符串为List<String>
/**
* 删除商品订单接口
* @param id 订单ID
* @param request HTTP请求对象
* @return 删除结果
*/
@GetMapping("/api/goods/order/delete")
public AjaxResult deleteGoodsOrder(@RequestParam("id") Long id, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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. 验证订单ID
if (id == null) {
return AppletControllerUtil.appletError("订单ID不能为空");
}
// 3. 查询商品订单
GoodsOrder goodsOrder = goodsOrderService.selectGoodsOrderById(id);
if (goodsOrder == null) {
return AppletControllerUtil.appletError("商品订单不存在");
}
// // 4. 验证订单所属用户
// if (!goodsOrder.getUid().equals(user.getId())) {
// return AppletControllerUtil.appletError("无权删除此订单");
// }
// 5. 检查订单状态,防止删除已支付或进行中的订单
if (goodsOrder.getStatus() != null && goodsOrder.getStatus() >= 2) {
return AppletControllerUtil.appletError("已支付或进行中的订单不能删除");
}
// 6. 删除订单
int deleteResult = goodsOrderService.deleteGoodsOrderById(id);
if (deleteResult > 0) {
Map<String, Object> result = new HashMap<>();
result.put("message", "订单删除成功");
result.put("orderId", goodsOrder.getOrderId());
result.put("deleteTime", new Date());
return AppletControllerUtil.appletSuccess(result);
} else {
return AppletControllerUtil.appletError("订单删除失败,请稍后重试");
}
} catch (Exception e) {
logger.error("删除商品订单失败:", e);
return AppletControllerUtil.appletError("删除商品订单失败:" + e.getMessage());
}
}
/**
* 获取弹窗列表
* @return 弹窗列表数据
*/
@GetMapping("/api/popup/list")
public AjaxResult getPopupList() {
try {
// 查询config_shiyi配置
SiteConfig siteConfig = siteConfigService.selectSiteConfigByName("config_shiyi");
if (siteConfig == null || StringUtils.isEmpty(siteConfig.getValue())) {
// 如果没有配置或值为空,返回空的弹窗列表
Map<String, Object> result = new HashMap<>();
result.put("popups", new ArrayList<>());
return AppletControllerUtil.appletSuccess(result);
}
// 解析JSON数据
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> configData = objectMapper.readValue(siteConfig.getValue(), Map.class);
// 获取弹窗列表
List<Map<String, Object>> popups = (List<Map<String, Object>>) configData.get("popups");
if (popups == null) {
popups = new ArrayList<>();
}
// 过滤掉已下线的弹窗
List<Map<String, Object>> activePopups = popups.stream()
.filter(popup -> {
Object status = popup.get("status");
return status != null && Integer.valueOf(status.toString()) == 1;
})
.collect(Collectors.toList());
// 按排序字段排序
activePopups.sort((a, b) -> {
Object sortA = a.get("sort");
Object sortB = b.get("sort");
int sortAValue = sortA != null ? Integer.valueOf(sortA.toString()) : 0;
int sortBValue = sortB != null ? Integer.valueOf(sortB.toString()) : 0;
return Integer.compare(sortAValue, sortBValue);
});
Map<String, Object> result = new HashMap<>();
result.put("popups", activePopups);
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("获取弹窗列表失败:", e);
return AppletControllerUtil.appletError("获取弹窗列表失败:" + e.getMessage());
}
}
/**
* 师傅申请退回
* 将师傅的质保金提现给师傅,并关闭师傅账户
*/
@PostMapping("/api/worker/apply/refund")
public AjaxResult applyWorkerRefund(HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> 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("用户信息获取失败");
}
// // 查询师傅信息
// Users worker = usersService.selectUsersById(userId);
// if (worker == null) {
// return AppletControllerUtil.appletError("师傅信息不存在");
// }
// 检查师傅状态
if (worker.getStatus() == 0) {
return AppletControllerUtil.appletError("师傅账户已被关闭");
}
// // 查询师傅质保金总额
// BigDecimal totalMargin = worker.getMargin();
// if (totalMargin == null || totalMargin.compareTo(BigDecimal.ZERO) <= 0) {
// return AppletControllerUtil.appletError("师傅质保金余额不足");
// }
// // 记录质保金提现日志
// WorkerMarginLog marginLog = new WorkerMarginLog();
// marginLog.setUid(userId);
// marginLog.setPrice(totalMargin.negate()); // 负数表示扣减
// marginLog.setReamk("师傅申请退回,质保金提现");
// marginLog.setCreatedAt(new Date());
// marginLog.setUpdatedAt(new Date());
//
// // 插入质保金变动记录
// workerMarginLogService.insertWorkerMarginLog(marginLog);
//
// // 更新师傅质保金为0
worker.setMargin(BigDecimal.ZERO);
//
// // 关闭师傅账户
// worker.setStatus(0);
worker.setType("1");
// 更新师傅信息
int updateResult = usersService.updateUsers(worker);
if (updateResult <= 0) {
return AppletControllerUtil.appletError("更新师傅信息失败");
}
Map<String, Object> result = new HashMap<>();
result.put("message", "申请退回成功,质保金已提现");
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("师傅申请退回失败", e);
return AppletControllerUtil.appletError("申请退回失败: " + e.getMessage());
}
}
@PostMapping("/api/worker/grab")
public AjaxResult workerGrabOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
// 1. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
Users currentUser = (Users) userValidation.get("user");
if (currentUser == null) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
// 获取订单ID
Long orderId = null;
if (params.get("id") != null) {
if (params.get("id") instanceof Integer) {
orderId = ((Integer) params.get("id")).longValue();
} else if (params.get("id") instanceof Long) {
orderId = (Long) params.get("id");
} else {
orderId = Long.parseLong(params.get("id").toString());
}
}
if (orderId == null) {
return AppletControllerUtil.appletWarning("订单ID不能为空");
}
// 查询订单数据
Order order = orderService.selectOrderById(orderId);
if (order == null) {
return AppletControllerUtil.appletWarning("订单不存在");
}
// 检查订单状态是否为1待接单
if (order.getStatus() == null || order.getStatus() != 1L) {
return AppletControllerUtil.appletWarning("订单状态不正确,无法接单");
}
// // 获取当前登录用户(师傅)
// String token = request.getHeader("token");
// if (StringUtils.isEmpty(token)) {
// return AppletControllerUtil.appletdengluWarning("用户未登录");
// }
//
//// Users currentUser = AppletLoginUtil.getUserByToken(token);
//// if (currentUser == null) {
//// return AppletControllerUtil.appletdengluWarning("用户未登录或token无效");
//// }
// Users currentUser = (Users) userValidation.get("user");
// if (currentUser == null) {
// return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
// }
// // 检查用户是否为师傅
// if (!"2".equals(currentUser.getType()) || currentUser.getIsWork() != 1) {
// return AppletControllerUtil.appletWarning("只有师傅才能接单");
// }
// 检查订单是否已被其他师傅接单
if (order.getWorkerId() != null && order.getWorkerId() > 0) {
return AppletControllerUtil.appletWarning("该订单已被其他师傅接单");
}
// 更新订单状态为2待服务并分配师傅
order.setStatus(2L);
order.setWorkerId(currentUser.getId());
order.setReceiveTime(new Date());
order.setReceiveType(1L); // 1自由抢单
order.setIsAccept(1); // 1已经接单
// 如果是第一次接单设置firstWorkerId
if (order.getFirstWorkerId() == null) {
order.setFirstWorkerId(currentUser.getId());
}
// 更新订单
int updateResult = orderService.updateOrder(order);
if (updateResult <= 0) {
return AppletControllerUtil.appletError("订单状态更新失败");
}
// 添加订单日志
OrderLog orderLog = new OrderLog();
orderLog.setOid(orderId);
orderLog.setOrderId(order.getOrderId());
orderLog.setLogOrderId(order.getOrderId());
orderLog.setTitle("师傅接单");
orderLog.setType(new BigDecimal("2")); // 2接单
JSONObject content = new JSONObject();
content.put("name", "师傅" + currentUser.getName() + "接单成功");
orderLog.setContent(content.toJSONString());
orderLog.setWorkerId(currentUser.getId());
orderLog.setWorkerName(currentUser.getName());
orderLog.setFirstWorkerId(currentUser.getId());
orderLog.setOrdertype(1L);
int logResult = orderLogService.insertOrderLog(orderLog);
if (logResult <= 0) {
logger.warn("订单日志添加失败订单ID{}", orderId);
}
return AppletControllerUtil.appletSuccess("接单成功");
} catch (Exception e) {
logger.error("师傅接单失败:", e);
return AppletControllerUtil.appletError("接单失败:" + e.getMessage());
}
}
@PostMapping("/api/public/get/article/cate")
public AjaxResult getArticleByCate(@RequestBody Map<String, Object> params) {
try {
logger.info("=== 开始获取分类文章 ===");
logger.info("请求参数: {}", params);
// 获取参数
String cate = null;
if (params.get("cate") != null) {
cate = params.get("cate").toString();
}
Boolean strip = false;
if (params.get("strip") != null) {
if (params.get("strip") instanceof Boolean) {
strip = (Boolean) params.get("strip");
} else if (params.get("strip") instanceof String) {
strip = Boolean.parseBoolean((String) params.get("strip"));
} else if (params.get("strip") instanceof Integer) {
strip = ((Integer) params.get("strip")) == 1;
}
}
logger.info("分类参数: {}, 是否去除标签: {}", cate, strip);
// 参数验证
if (cate == null || cate.trim().isEmpty()) {
logger.warn("分类参数为空");
return AppletControllerUtil.appletWarning("分类参数不能为空");
}
// 查询文章内容
Content queryContent = new Content();
queryContent.setId(Long.valueOf(cate));
List<Content> contentList = contentService.selectContentList(queryContent);
if (contentList == null || contentList.isEmpty()) {
logger.warn("未找到分类为 {} 的文章", cate);
return AppletControllerUtil.appletWarning("未找到相关文章");
}
// 按sort排序获取第一条记录
Content content = contentList.stream()
.sorted((c1, c2) -> {
Integer sort1 = Math.toIntExact(c1.getSort() != null ? c1.getSort() : 0);
Integer sort2 = Math.toIntExact(c2.getSort() != null ? c2.getSort() : 0);
return sort1.compareTo(sort2);
})
.findFirst()
.orElse(null);
if (content == null) {
logger.warn("未找到有效的文章内容");
return AppletControllerUtil.appletWarning("未找到相关文章");
}
logger.info("找到文章: ID={}, 标题={}", content.getId(), content.getTitle());
// 构建返回数据
Map<String, Object> result = new HashMap<>();
result.put("id", content.getId());
result.put("title", content.getTitle());
String contentText = content.getContent();
if (contentText != null && !contentText.trim().isEmpty()) {
if (strip) {
// 去除富文本标签并截取前130个字符
String strippedContent = AppletControllerUtil.stripHtmlTags(contentText);
if (strippedContent.length() > 130) {
contentText = strippedContent.substring(0, 130) + " ......";
} else {
contentText = strippedContent;
}
logger.info("已去除HTML标签截取后内容长度: {}", contentText.length());
}
result.put("content", contentText);
} else {
result.put("content", "");
}
logger.info("=== 获取分类文章完成 ===");
return AppletControllerUtil.appletSuccess(result);
} catch (Exception e) {
logger.error("获取分类文章异常", e);
return AppletControllerUtil.appletError("获取文章失败:" + e.getMessage());
}
}
@PostMapping("/api/service/order/rework/lst")
public AjaxResult getReworkList(@RequestBody Map<String, Object> params, HttpServletRequest request) {
try {
logger.info("=== 开始获取售后返修列表 ===");
logger.info("请求参数: {}", params);
// 1. 获取分页参数
int pageNum = 1;
int pageSize = 10;
if (params.get("page") != null) {
try {
pageNum = Integer.parseInt(params.get("page").toString());
if (pageNum <= 0) {
pageNum = 1;
}
} catch (NumberFormatException e) {
logger.warn("page参数格式错误使用默认值1");
pageNum = 1;
}
}
if (params.get("limit") != null) {
try {
pageSize = Integer.parseInt(params.get("limit").toString());
if (pageSize <= 0) {
pageSize = 10;
}
} catch (NumberFormatException e) {
logger.warn("limit参数格式错误使用默认值10");
pageSize = 10;
}
}
// 2. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(pageNum, pageSize);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning((String) pageValidation.get("message"));
}
// 3. 验证用户登录状态
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
Users currentUser = (Users) userValidation.get("user");
if (currentUser == null) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
logger.info("当前用户ID: {}", currentUser.getId());
logger.info("分页参数 - 页码: {}, 每页大小: {}", pageNum, pageSize);
// 4. 构建查询条件
OrderRework queryRework = new OrderRework();
queryRework.setUid(currentUser.getId());
// 状态筛选
if (params.get("status") != null) {
try {
Integer status = Integer.parseInt(params.get("status").toString());
if (status == 0 || status == 1) {
queryRework.setStatus(status);
logger.info("状态筛选: {}", status);
} else {
logger.warn("状态参数无效: {}, 不进行状态筛选", status);
}
} catch (NumberFormatException e) {
logger.warn("status参数格式错误不进行状态筛选");
}
}
// 5. 设置分页参数
PageHelper.startPage(pageNum, pageSize);
// 6. 查询数据
List<OrderRework> reworkList = orderReworkService.selectOrderReworkList(queryRework);
// 7. 构建分页信息
PageInfo<OrderRework> pageInfo = new PageInfo<>(reworkList);
// 8. 构建返回数据格式
Map<String, Object> responseData = new HashMap<>();
responseData.put("current_page", pageInfo.getPageNum());
responseData.put("data", AppletControllerUtil.buildReworkList(reworkList));
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/service/order/rework/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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
nextLink.put("active", false);
links.add(nextLink);
responseData.put("links", links);
logger.info("=== 获取售后返修列表完成 ===");
return AppletControllerUtil.appletSuccess(responseData);
} catch (Exception e) {
logger.error("获取售后返修列表异常", e);
return AppletControllerUtil.appletError("获取售后返修列表失败:" + e.getMessage());
}
}
/**
* 录音上传接口
*
* @param file 录音文件
* @param id 订单ID
* @param request HTTP请求对象
* @return 上传结果
*/
@PostMapping("/api/worker/order/sound")
public AjaxResult uploadOrderSound(@RequestParam("file") MultipartFile file,
@RequestParam("id") Long id,
HttpServletRequest request) {
try {
logger.info("=== 开始录音上传订单ID: {} ===", id);
// 1. 验证文件是否为空
if (file == null || file.isEmpty()) {
logger.warn("录音文件为空");
return AppletControllerUtil.appletWarning("录音文件不能为空");
}
// 2. 验证文件格式(只允许音频格式)
String[] allowedTypes = {
"mp3", "wav", "aac", "m4a", "ogg", "flac", "wma", "amr"
};
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || !isValidAudioFile(originalFilename, allowedTypes)) {
logger.warn("录音文件格式不支持: {}", originalFilename);
return AppletControllerUtil.appletWarning("只允许上传音频文件格式mp3, wav, aac, m4a, ogg, flac, wma, amr");
}
// 3. 验证文件大小50MB
long maxSize = 50 * 1024 * 1024;
if (file.getSize() > maxSize) {
logger.warn("录音文件大小超过限制: {} bytes", file.getSize());
return AppletControllerUtil.appletWarning("录音文件大小不能超过50MB");
}
// 4. 验证订单是否存在
Order order = orderService.selectOrderById(id);
if (order == null) {
logger.warn("订单不存在订单ID: {}", id);
return AppletControllerUtil.appletWarning("订单不存在");
}
// 5. 获取当前用户信息
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
logger.warn("用户未登录");
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
Users currentUser = (Users) userValidation.get("user");
if (currentUser == null) {
logger.warn("用户信息获取失败");
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
// 6. 上传文件到本地
String uploadPath = RuoYiConfig.getUploadPath() + "/sound/" + id;
String fileName = FileUploadUtils.upload(uploadPath, file);
String fileUrl = "/sound/" + id + "/" + fileName;
logger.info("uploadPath录音文件上传成功文件路径: {}", uploadPath);
logger.info("fileUrl录音文件上传成功文件路径: {}", fileUrl);
// // 7. 保存录音记录到数据库
// OrderSoundLog orderSound = new OrderSoundLog();
// orderSound.setOid(id);
// orderSound.setOcode(order.getOrderId());
// orderSound.setFile(fileUrl);
// orderSound.setWorkerUid(currentUser.getId());
// orderSound.setWorkerName(currentUser.getNickname());
// orderSound.setCreatedAt(new Date());
// orderSound.setUpdatedAt(new Date());
// int result = orderSoundService.insertOrderSound(orderSound);
// if (result <= 0) {
// logger.error("保存录音记录失败");
// return AppletControllerUtil.appletError("保存录音记录失败");
// }
OrderSoundLog orderSound = new OrderSoundLog();
orderSound.setOid(id);
orderSound.setFile(fileUrl);
orderSound.setIsMerge(1);
logger.info("录音记录保存成功记录ID: {}", System.currentTimeMillis()/1000);
orderSound.setCreatedAt(System.currentTimeMillis()/1000);
int result= orderSoundLogService.insertOrderSoundLog(orderSound);
logger.info("录音记录保存成功记录ID: {}", orderSound.getId());
// int result = orderSoundService.insertOrderSound(orderSound);
if (result <= 0) {
logger.error("保存录音记录失败");
return AppletControllerUtil.appletError("保存录音记录失败");
}
// 8. 构建返回数据
Map<String, Object> resultData = new HashMap<>();
resultData.put("id", orderSound.getId());
resultData.put("file", fileUrl);
resultData.put("fileName", fileName);
resultData.put("originalFilename", originalFilename);
resultData.put("size", file.getSize());
resultData.put("uploadTime", new Date());
logger.info("=== 录音上传完成 ===");
return AppletControllerUtil.appletSuccess(resultData);
} catch (Exception e) {
logger.error("录音上传异常", e);
return AppletControllerUtil.appletError("录音上传失败:" + e.getMessage());
}
}
/**
* 验证音频文件格式
*
* @param filename 文件名
* @param allowedTypes 允许的文件类型
* @return 是否有效
*/
private boolean isValidAudioFile(String filename, String[] allowedTypes) {
if (filename == null || filename.isEmpty()) {
return false;
}
String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
for (String type : allowedTypes) {
if (type.equalsIgnoreCase(extension)) {
return true;
}
}
return false;
}
/**
* 合并录音MP3文件接口
* 专门处理查询到的录音MP3文件进行合并并插入数据库
*
* @param oid 订单ID
* @param request HTTP请求对象
* @return 合并结果
*/
@PostMapping("/api/worker/order/sound/merge")
public AjaxResult mergeOrderSound(@RequestParam("oid") Long oid, HttpServletRequest request) {
try {
logger.info("=== 开始合并录音MP3文件订单ID: {} ===", oid);
// 1. 验证订单是否存在
Order order = orderService.selectOrderById(oid);
if (order == null) {
logger.warn("订单不存在订单ID: {}", oid);
return AppletControllerUtil.appletWarning("订单不存在");
}
// 2. 获取当前用户信息
String token = request.getHeader("token");
Map<String, Object> userValidation = AppletLoginUtil.validateUserToken(token, usersService);
if (!(Boolean) userValidation.get("valid")) {
logger.warn("用户未登录");
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
Users currentUser = (Users) userValidation.get("user");
if (currentUser == null) {
logger.warn("用户信息获取失败");
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
// 3. 查询需要合并的录音MP3文件
OrderSoundLog queryLog = new OrderSoundLog();
queryLog.setOid(oid);
queryLog.setIsMerge(1); // 1表示未合并
List<OrderSoundLog> soundLogs = orderSoundLogService.selectOrderSoundLogList(queryLog);
if (soundLogs == null || soundLogs.isEmpty()) {
logger.warn("没有需要合并的录音MP3文件订单ID: {}", oid);
return AppletControllerUtil.appletWarning("没有需要合并的录音MP3文件");
}
logger.info("找到 {} 个需要合并的录音MP3文件", soundLogs.size());
// 4. 构建MP3文件路径并验证文件存在性
List<String> validMp3Files = new ArrayList<>();
for (OrderSoundLog soundLog : soundLogs) {
String dbFilePath = soundLog.getFile();
logger.info("数据库中的MP3文件路径: {}", dbFilePath);
// 验证文件格式是否为MP3
if (!dbFilePath.toLowerCase().endsWith(".mp3")) {
logger.warn("跳过非MP3文件: {}", dbFilePath);
continue;
}
// 使用与录音上传接口相同的路径构建逻辑
String fullFilePath = buildFullFilePath(dbFilePath);
if (fullFilePath != null) {
validMp3Files.add(fullFilePath);
logger.info("成功添加MP3文件: {}", fullFilePath);
} else {
logger.warn("无法找到MP3文件: {}", dbFilePath);
}
}
if (validMp3Files.isEmpty()) {
logger.warn("所有MP3文件都不存在订单ID: {}", oid);
return AppletControllerUtil.appletWarning("所有MP3文件都不存在");
}
// 5. 检查FFmpeg是否可用
if (!FFmpegUtilsSimple.isFFmpegAvailable()) {
logger.error("FFmpeg不可用无法进行MP3文件合并");
String errorMsg = "FFmpeg不可用请按以下步骤安装FFmpeg\n" +
"1. 下载FFmpeg: https://ffmpeg.org/download.html\n" +
"2. 解压到 C:\\ffmpeg\\ 目录\n" +
"3. 将 C:\\ffmpeg\\bin\\ 添加到系统PATH环境变量\n" +
"4. 重启应用程序";
return AppletControllerUtil.appletError(errorMsg);
}
// 6. 创建临时目录
String tempDir = RuoYiConfig.getUploadPath() + "/temp_merge_mp3/";
File tempDirFile = new File(tempDir);
if (!tempDirFile.exists()) {
tempDirFile.mkdirs();
}
logger.info("临时目录: {}", tempDir);
// 7. 生成唯一MP3文件名
String fileName = "merged_" + System.currentTimeMillis() + "_" + oid + ".mp3";
String tempOutputPath = tempDir + fileName;
// 8. 创建FFmpeg输入列表文件
String inputListFile =AppletControllerUtil.createInputListFile(validMp3Files);
try {
// 9. 执行FFmpeg合并MP3命令
boolean mergeSuccess =AppletControllerUtil.executeFFmpegMerge(inputListFile, tempOutputPath);
if (!mergeSuccess) {
throw new Exception("MP3文件合并失败");
}
// 10. 验证合并后的MP3文件
File mergedFile = new File(tempOutputPath);
if (!mergedFile.exists()) {
throw new Exception("合并后的MP3文件未生成");
}
// 11. 上传到七牛云
String qiniuPath = "files/merge_mp3/" + DateUtils.getDate() + "/" + fileName;
String fileUrl = AppletControllerUtil.uploadToQiniu(tempOutputPath, qiniuPath);
// 12. 保存到数据库
OrderSound orderSound = new OrderSound();
orderSound.setOid(oid);
orderSound.setOcode(order.getOrderId());
orderSound.setFile(qiniuPath);
orderSound.setWorkerUid(currentUser.getId());
orderSound.setWorkerName(currentUser.getNickname());
orderSound.setCreatedAt(new Date());
orderSound.setUpdatedAt(new Date());
int result = orderSoundService.insertOrderSound(orderSound);
if (result <= 0) {
throw new Exception("保存录音记录失败");
}
// 13. 更新临时文件状态为已合并
for (OrderSoundLog soundLog : soundLogs) {
soundLog.setIsMerge(2); // 2表示已合并
orderSoundLogService.updateOrderSoundLog(soundLog);
}
// 14. 清理临时文件
AppletControllerUtil.cleanupTempFiles(tempOutputPath, inputListFile);
// 15. 构建返回数据
Map<String, Object> resultData = new HashMap<>();
resultData.put("message", "录音MP3文件合并并上传七牛云成功");
resultData.put("file_url", fileUrl);
resultData.put("file_path", qiniuPath);
resultData.put("merged_count", validMp3Files.size());
resultData.put("file_format", "mp3");
resultData.put("order_id", order.getOrderId());
resultData.put("worker_name", currentUser.getNickname());
resultData.put("merge_time", new Date());
logger.info("=== 录音MP3文件合并完成合并了 {} 个文件 ===", validMp3Files.size());
return AppletControllerUtil.appletSuccess(resultData);
} catch (Exception e) {
// 清理临时文件
AppletControllerUtil.cleanupTempFiles(tempOutputPath, inputListFile);
throw e;
}
} catch (Exception e) {
logger.error("合并录音MP3文件异常", e);
return AppletControllerUtil.appletError("合并录音MP3文件失败" + e.getMessage());
}
}
@GetMapping("/api/worker/sound/current/order")
public AjaxResult getCurrentOrder(HttpServletRequest request) {
try {
// 获取token
String token = request.getHeader("token");
if (StringUtils.isEmpty(token)) {
return AjaxResult.error("token不能为空");
}
// 验证用户token
Map<String, Object> userInfo = AppletLoginUtil.validateUserToken(token, usersService);
if (userInfo == null) {
return AjaxResult.error("token验证失败");
}
Users user = (Users) userInfo.get("user");
Long workerId = user.getId();
// 初始化返回信息
Map<String, Object> info = new HashMap<>();
info.put("oid", null);
info.put("order_id", null);
// 查询工人待服务的订单status=2
Order queryOrder = new Order();
queryOrder.setWorkerId(workerId);
queryOrder.setStatus(2L);
List<Order> orderList = orderService.selectOrderList(queryOrder);
// 按ID升序排序
orderList.sort(Comparator.comparing(Order::getId));
// 遍历每个订单
for (Order order : orderList) {
// 查询该订单的日志记录
OrderLog queryLog = new OrderLog();
queryLog.setWorkerId(workerId);
queryLog.setOid(order.getId());
queryLog.setGiveUp(null); // whereNull('give_up')
queryLog.setIsPause(null); // whereNull('is_pause')
List<OrderLog> logList = orderLogService.selectOrderLogList(queryLog);
// 查找符合条件的日志记录type为4或5
OrderLog foundLog = null;
OrderLog stopLog = null;
for (OrderLog log : logList) {
BigDecimal type = log.getType();
if (type != null) {
int typeValue = type.intValue();
// 查找type为4或5的记录
if ((typeValue == 4 || typeValue == 5) && foundLog == null) {
foundLog = log;
}
// 查找停止录音的记录type > 5
if (typeValue > 5 && stopLog == null) {
stopLog = log;
}
}
}
// 如果找到停止录音的记录,跳过该订单
if (stopLog != null) {
continue;
}
// 如果找到符合条件的记录,返回该订单信息
if (foundLog != null) {
info.put("oid", order.getId());
info.put("order_id", order.getOrderId());
break;
}
}
return AjaxResult.success(info);
} catch (Exception e) {
logger.error("获取当前正在进行的单子失败", e);
return AjaxResult.error("获取当前正在进行的单子失败:" + e.getMessage());
}
}
/**
* 根据数据库中的相对路径构建完整的文件路径
*
* @param dbFilePath 数据库中的文件路径(如 /sound/123/filename.mp3
* @return 完整的文件路径
*/
private String buildFullFilePath(String dbFilePath) {
if (dbFilePath == null || dbFilePath.isEmpty()) {
return null;
}
logger.info("构建文件路径,数据库路径: {}", dbFilePath);
// 方法1使用与录音上传接口相同的路径构建逻辑
if (dbFilePath.startsWith("/sound/")) {
// 从 /sound/{id}/{fileName} 提取 id 和 fileName
String[] pathParts = dbFilePath.split("/");
if (pathParts.length >= 4) {
String orderId = pathParts[2];
String fileName = pathParts[3];
String fullPath = RuoYiConfig.getUploadPath() + "/sound/" + orderId + "/" + fileName;
logger.info("方法1构建的完整路径: {}", fullPath);
File file = new File(fullPath);
if (file.exists() && file.isFile()) {
logger.info("方法1成功找到文件: {}", fullPath);
return fullPath;
} else {
logger.warn("方法1文件不存在: {}", fullPath);
}
}
}
// 方法2尝试其他路径组合
List<String> possiblePaths = new ArrayList<>();
// 2.1 使用UploadPath + 数据库路径
String uploadPath = RuoYiConfig.getUploadPath() + dbFilePath;
possiblePaths.add(uploadPath);
// 2.2 使用Profile + 数据库路径
String profilePath = RuoYiConfig.getProfile() + dbFilePath;
possiblePaths.add(profilePath);
// 2.3 直接使用数据库路径(如果是绝对路径)
possiblePaths.add(dbFilePath);
// 2.4 如果数据库路径是相对路径,尝试在当前工作目录下查找
if (dbFilePath.startsWith("/")) {
String currentDirPath = System.getProperty("user.dir") + dbFilePath;
possiblePaths.add(currentDirPath);
}
// 尝试所有可能的路径
for (String path : possiblePaths) {
File file = new File(path);
if (file.exists() && file.isFile()) {
logger.info("方法2成功找到文件: {}", path);
return path;
} else {
logger.debug("方法2文件不存在: {}", path);
}
}
logger.warn("所有方法都无法找到文件: {}", dbFilePath);
return null;
}
/**
* 服务/商品搜索接口
*
* @param params 请求参数包含limit(每页数量)、page(页码)、keywords(搜索关键词)
* @param request HTTP请求对象
* @return 搜索结果列表
* <p>
* 接口说明:
* - 根据关键词搜索服务商品
* - 支持按商品标题进行模糊查询
* - 支持分页查询
* - 无需用户登录验证
* <p>
*/
@PostMapping(value = "/api/service/search")
public AjaxResult searchServices(@RequestBody Map<String, Object> 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 keywords = params.get("keywords") != null ? params.get("keywords").toString().trim() : "";
// 2. 验证分页参数
Map<String, Object> pageValidation = PageUtil.validatePageParams(page, limit);
if (!(Boolean) pageValidation.get("valid")) {
return AppletControllerUtil.appletdengluWarning("用户信息获取失败");
}
// 3. 设置分页参数
PageHelper.startPage(page, limit);
// 4. 构建查询条件
ServiceGoods queryGoods = new ServiceGoods();
// 如果有关键词,设置标题模糊查询
if (!keywords.isEmpty()) {
queryGoods.setTitle(keywords); // 这里依赖mapper中的like查询实现
}
// 5. 查询商品列表
List<ServiceGoods> goodsList = serviceGoodsService.selectServiceGoodsList(queryGoods);
// 6. 构建返回数据
List<Map<String, Object>> resultList = new ArrayList<>();
for (ServiceGoods goods : goodsList) {
Map<String, Object> goodsData = AppletControllerUtil.buildServiceGoodsData(goods);
resultList.add(goodsData);
}
// 7. 构建分页信息
PageInfo<ServiceGoods> pageInfo = new PageInfo<>(goodsList);
// 8. 构建返回数据格式
Map<String, Object> 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/service/search";
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<Map<String, Object>> links = new ArrayList<>();
Map<String, Object> prevLink = new HashMap<>();
prevLink.put("url", pageInfo.isHasPreviousPage() ?
baseUrl + "?page=" + pageInfo.getPrePage() : null);
prevLink.put("label", "&laquo; Previous");
prevLink.put("active", false);
links.add(prevLink);
Map<String, Object> nextLink = new HashMap<>();
nextLink.put("url", pageInfo.isHasNextPage() ?
baseUrl + "?page=" + pageInfo.getNextPage() : null);
nextLink.put("label", "Next &raquo;");
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());
}
}
}