package com.ruoyi.order.controller;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.account.api.feignClient.UserAddressClient;
import com.ruoyi.account.api.model.UserAddress;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.order.enums.OrderStatus;
import com.ruoyi.order.mapper.OrderMapper;
import com.ruoyi.order.model.Order;
import com.ruoyi.order.model.RefundPass;
import com.ruoyi.order.service.CommissionService;
import com.ruoyi.order.service.OrderService;
import com.ruoyi.order.service.RefundPassService;
import com.ruoyi.order.util.payment.model.RefundCallbackResult;
import com.ruoyi.order.util.vo.MapTrackKD100Vo;
import com.ruoyi.order.vo.*;
import com.ruoyi.other.api.domain.BaseSetting;
import com.ruoyi.other.api.feignClient.BaseSettingClient;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysUserClient;
import com.ruoyi.system.api.model.LoginUser;
import io.swagger.annotations.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
/**
*
* 前端控制器
*
*
* @author luodangjia
* @since 2024-11-21
*/
@Api(tags = "订单")
@RestController
@RequestMapping("/order")
public class OrderController extends BaseController {
@Resource
private OrderService orderService;
@Resource
private TokenService tokenService;
@Resource
private UserAddressClient addressClient;
@Resource
private CommissionService commissionService;
@Resource
private BaseSettingClient baseSettingClient;
@Resource
private OrderMapper orderMapper;
@Resource
private SysUserClient sysUserClient;
@Resource
private RefundPassService refundPassService;
/**
* 我的订单列表
*/
@ApiOperation(value = "我的订单列表", tags = {"小程序-个人中心-我的订单"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单状态", name = "status", required = true, dataType = "int"),
})
@GetMapping("/getMyOrderList")
public TableDataInfo getMyOrderList(@ApiParam("订单状态") Integer status){
startPage();
LoginUser loginUserApplet = tokenService.getLoginUserApplet();
return getDataTable(orderService.selectOrderListByUserId(status, loginUserApplet.getUserid()));
}
/**
* 通过订单ids获取订单列表
*/
@PostMapping("/getOrderListByIds")
public R> getOrderListByIds(@RequestBody List ids){
return R.ok(orderService.listByIds(ids));
}
/**
* 订单详情
*/
@ApiOperation(value = "订单详情", tags = {"小程序-个人中心-我的订单-订单详情"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单id", name = "orderId", required = true, dataType = "int"),
})
@GetMapping("/detail/{orderId}")
public R detail(@PathVariable("orderId") Long orderId){
return R.ok(orderService.getOrderDetail(orderId));
}
/**
* 扫码校验
*/
@ApiOperation(value = "扫码校验", tags = {"小程序-个人中心-门店管理"})
@ApiImplicitParams({
@ApiImplicitParam(value = "分享id", name = "shareId", required = true, dataType = "int", paramType="query"),
})
@GetMapping("/check/{orderNumber}/{shopId}")
public R check(@PathVariable("orderNumber") String orderNumber, @PathVariable("shopId") Integer shopId){
LoginUser loginUserApplet = tokenService.getLoginUserApplet();
Order order = orderService.getOne(new LambdaQueryWrapper()
.eq(Order::getOrderNumber, orderNumber));
return R.ok(orderService.check(order, shopId, loginUserApplet.getUserid()));
}
/**
* 订单核销
*/
@ApiOperation(value = "订单核销", tags = {"小程序-个人中心-门店管理"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单id", name = "id", required = true, dataType = "String"),
})
@GetMapping("/writeOff")
public R writeOff(String code, Integer shopId, String technicianId){
orderService.writeOff(code, shopId, technicianId);
return R.ok();
}
/**
* 取消订单
*/
@ApiOperation(value = "取消订单", tags = {"小程序-个人中心-我的订单"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单id", name = "orderId", required = true, dataType = "int"),
})
@GetMapping("/cancel/{orderId}")
public R cancel(@PathVariable("orderId") Long orderId){
return orderService.cancel(orderId);
}
/**
* 确认收货
*/
@ApiOperation(value = "确认收货", tags = {"小程序-个人中心-我的订单"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单id", name = "orderId", required = true, dataType = "int"),
})
@GetMapping("/confirm/{orderId}")
public R confirm(@PathVariable("orderId") Long orderId){
R baseSettingR = baseSettingClient.getBaseSetting(5);
if (R.isError(baseSettingR)) {
return R.fail("售后设置获取失败");
}
BaseSetting baseSetting = baseSettingR.getData();
if (baseSetting == null) {
return R.fail("售后设置获取失败");
}
String content = baseSetting.getContent();
JSONObject jsonObject = JSONObject.parseObject(content);
Long days = jsonObject.getLong("days");
Order order = orderService.getById(orderId);
order.setAfterSaleTime(LocalDateTime.now().plusDays(days));
order.setIsCommission(0);
order.setOrderStatus(OrderStatus.COMPLETED.getCode());
orderService.updateById(order);
return R.ok();
}
/**
* 更换收货地址
*/
@ApiOperation(value = "更换收货地址", tags = {"小程序-个人中心-我的订单"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单id", name = "orderId", required = true, dataType = "int"),
})
@GetMapping("/changeAddress")
public R changeAddress(@RequestParam("orderId") Long orderId, @RequestParam("addressId") Long addressId){
R userAddressR = addressClient.getUserAddressById(addressId);
if(R.isError(userAddressR)){
return R.fail("收货地址不存在");
}
UserAddress userAddress = userAddressR.getData();
String addressJson = JSONObject.toJSONString(userAddress);
orderService.update(new LambdaUpdateWrapper()
.eq(Order::getId, orderId)
.set(Order::getAddressJson, addressJson));
return R.ok();
}
/**
* 更新订单状态
*/
@ApiOperation(value = "更新订单状态", tags = {"后台-订单管理"})
@ApiImplicitParams({
@ApiImplicitParam(value = "订单对象", name = "order", required = true, dataType = "Order"),
})
@PostMapping("/updateOrderStatus")
public R updateOrderStatus(@RequestBody Order order){
Order order1 = orderService.getById(order.getId());
order1.setOrderStatus(order.getOrderStatus());
order1.setOldOrderStatus(order.getOldOrderStatus());
orderService.updateById(order1);
return R.ok();
}
/**
* 预约技师
*/
@PostMapping("/subscribe")
public R subscribe(@RequestParam(value = "id", required = false) Long id ,@RequestParam(value = "technicianId", required = false) Integer technicianId){
Order order = orderService.getById(id);
order.setTechnicianId(technicianId);
orderService.updateById(order);
return R.ok();
}
@PostMapping("/getLastOrder")
public R getLastOrder(@RequestParam("appUserId") Long appUserId){
Order one = orderService.lambdaQuery().eq(Order::getAppUserId, appUserId).orderByDesc(Order::getCreateTime).last("limit 1").one();
return R.ok(one);
}
@PostMapping("/byUserId")
public R> byUserId(@RequestParam("appUserId") Long appUserId){
return R.ok(orderService.lambdaQuery().eq(Order::getAppUserId, appUserId).list());
}
@PostMapping("/byShopId")
public R> byShopId(@RequestParam("shopId") Integer shopId){
return R.ok(orderService.lambdaQuery().isNotNull(Order::getEndTime).eq(Order::getShopId, shopId).list());
}
@PostMapping("/confirmDelivery")
@ApiOperation(value = "已发货操作", tags = {"管理后台-订单管理"})
public R confirmDelivery(@RequestBody ConfirmDelivery confirmDelivery){
return orderService.confirmDelivery(confirmDelivery);
}
@PutMapping("/cancelOrder/{orderId}")
@ApiOperation(value = "取消订单操作", tags = {"管理后台-订单管理"})
public R cancelOrder(@PathVariable("orderId") Long orderId){
return orderService.cancelOrder(orderId);
}
@PutMapping("/receivingOperation/{orderId}")
@ApiOperation(value = "收货操作", tags = {"管理后台-订单管理"})
public R receivingOperation(@PathVariable("orderId") Long orderId){
return orderService.receivingOperation(orderId);
}
@GetMapping("/getOrderInfo/{orderId}")
@ApiOperation(value = "查询订单详情", tags = {"管理后台-订单管理"})
public R getOrderInfo(@PathVariable("orderId") Long orderId){
OrderInfoVo orderInfo = orderService.getOrderInfo(orderId);
RefundPass refundPass = refundPassService.lambdaQuery().eq(RefundPass::getOrderId, orderId).one();
if (refundPass!=null){
orderInfo.setRefundPassId(refundPass.getId().toString());
}
return R.ok(orderInfo);
}
@GetMapping("/getOrderPageList")
// @ApiOperation(value = "获取订单列表", tags = {"管理后台-订单管理", "门店后台-订单管理"})
public R> getOrderPageList(OrderPageList orderPageList){
return R.ok(orderService.getOrderPageList(orderPageList));
}
/**
* 订单统计
*/
@GetMapping("/getOrderStatistics")
@ApiOperation(value = "订单统计", tags = {"管理后台-首页统计"})
public R getOrderStatistics(@RequestParam("startTime") String startTime,
@RequestParam("endTime") String endTime){
Long userid = tokenService.getLoginUser().getUserid();
SysUser sysUser = sysUserClient.getSysUser(userid).getData();
List orderList = orderService.list(new LambdaQueryWrapper()
.eq(sysUser.getRoleType() == 2, Order::getShopId, sysUser.getObjectId())
.between(Order::getCreateTime, LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
.orderByAsc(Order::getCreateTime));
Map> map = orderList.stream()
.collect(Collectors.groupingBy(
item -> item.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
TreeMap::new, // 使用 TreeMap 按键排序
Collectors.toList()
));
List orderStatisticsDetails = new ArrayList<>();
map.forEach((key, value) -> {
int serviceTotal = 0;
int singleTotal = 0;
int total = 0;
BigDecimal totalMoney = BigDecimal.ZERO;
BigDecimal serviceTotalMoney = BigDecimal.ZERO;
BigDecimal singleTotalMoney = BigDecimal.ZERO;
OrderStatisticsDetail orderStatisticsDetail = new OrderStatisticsDetail();
for (Order order : value) {
if (order.getOrderType().equals(1)) {
serviceTotal++;
serviceTotalMoney = serviceTotalMoney.add(order.getPaymentAmount());
total++;
totalMoney = totalMoney.add(order.getPaymentAmount());
}else if (order.getOrderType().equals(2) && 1 == order.getDistributionMode()){
singleTotal++;
singleTotalMoney = singleTotalMoney.add(order.getPaymentAmount());
total++;
totalMoney = totalMoney.add(order.getPaymentAmount());
}
}
orderStatisticsDetail.setDate(key);
orderStatisticsDetail.setServiceTotal(serviceTotal);
orderStatisticsDetail.setSingleTotal(singleTotal);
orderStatisticsDetail.setTotal(total);
orderStatisticsDetail.setServiceTotalMoney(serviceTotalMoney);
orderStatisticsDetail.setSingleTotalMoney(singleTotalMoney);
orderStatisticsDetail.setTotalMoney(totalMoney);
orderStatisticsDetails.add(orderStatisticsDetail);
});
Integer shopId = null;
if(sysUser.getRoleType() == 2){
shopId = sysUser.getObjectId();
}
OrderStatistics orderStatistics = orderMapper.getOrderStatistics(startTime, endTime, shopId);
if(null != orderStatistics){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
List sortedDetails = orderStatisticsDetails.stream()
.sorted(Comparator.comparing((OrderStatisticsDetail detail) -> {
try {
return dateFormat.parse(detail.getDate());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}).reversed())
.collect(Collectors.toList());
orderStatistics.setOrderStatisticsDetailList(sortedDetails);
}
return R.ok(orderStatistics);
}
/**
* 订单取消支付回退
* @param refundCallbackResult
* @param response
* @return
*/
@ResponseBody
@GetMapping("/refundPayMoneyCallback")
public void refundPayMoneyCallback(RefundCallbackResult refundCallbackResult, HttpServletResponse response){
R callback = orderService.refundPayMoneyCallback(refundCallbackResult);
if(callback.getCode() == 200){
response.setStatus(200);
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e) {
throw new RuntimeException(e);
}
out.println("success");
out.flush();
out.close();
}
}
/**
* 取消订单快递费回退
* @param refundCallbackResult
* @param response
*/
@ResponseBody
@GetMapping("/refundExpressPayMoneyCallback")
public void refundExpressPayMoneyCallback(RefundCallbackResult refundCallbackResult, HttpServletResponse response){
R callback = orderService.refundExpressPayMoneyCallback(refundCallbackResult);
if(callback.getCode() == 200){
response.setStatus(200);
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e) {
throw new RuntimeException(e);
}
out.println("success");
out.flush();
out.close();
}
}
/**
* 获取商品销售数量
* @param goodsId
* @return
*/
@PostMapping("/getGoodsSaleNum")
public R getGoodsSaleNum(@RequestParam("goodsId") Integer goodsId, @RequestParam("type") Integer type){
Integer goodsSaleNum = orderService.getGoodsSaleNum(goodsId, type);
return R.ok(goodsSaleNum);
}
/**
* 获取门店销售订单数量
* @param shopId 门店id
* @param type 1:服务订单,2:单品订单
* @return
*/
@PostMapping("/getShopSaleNum")
public R getShopSaleNum(@RequestParam("shopId") Integer shopId, @RequestParam("type") Integer type){
Integer shopSaleNum = orderService.getShopSaleNum(shopId, type);
return R.ok(shopSaleNum);
}
/**
* 获取所有在指定门店消费的用户id
* @param shopId
* @return
*/
@PostMapping("/getAppUserByShoppingShop")
public R> getAppUserByShoppingShop(@RequestParam("shopId") Integer shopId){
List list = orderService.list(new LambdaQueryWrapper().eq(Order::getShopId, shopId).eq(Order::getDelFlag, 0)
.eq(Order::getPayStatus, 2).in(Order::getOrderStatus, Arrays.asList(1, 2, 3, 4, 7, 8)));
Set collect = list.stream().map(Order::getAppUserId).collect(Collectors.toSet());
return R.ok(collect);
}
/**
* 获取订单快递明细
* @param id
* @return
*/
@GetMapping("/getOrderExpress/{id}")
@ApiOperation(value = "获取订单快递明细", tags = {"小程序-订单管理"})
public R getOrderExpress(@PathVariable("id") Long id){
Order order = orderService.getById(id);
String expressResult = order.getExpressResult();
if(StringUtils.isNotEmpty(expressResult)){
MapTrackKD100Vo mapTrackKD100Vo = JSON.parseObject(expressResult, MapTrackKD100Vo.class);
return R.ok(mapTrackKD100Vo);
}
return R.ok();
}
/**
* 根据id获取订单详情
* @param id
* @return
*/
@PostMapping("/getOrderById")
public R getOrderById(@RequestParam("id") Long id){
Order order = orderService.getById(id);
return R.ok(order);
}
/**
* 修改订单
* @param order
* @return
*/
@PostMapping("/editOrder")
public R editOrder(@RequestBody Order order){
orderService.updateById(order);
return R.ok();
}
}