package com.gxwebsoft.shop.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.service.*;
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 会员特权购买记录表控制器
 *
 * @author 科技小王子
 * @since 2023-06-20 18:07:50
 */
@Api(tags = "微信支付结果通知")
@RestController
@RequestMapping("/api/shop/wx-pay/notify/nbg")
public class WxPayNotifyNbgController extends BaseController {
  @Resource
  private OrderService orderService;
  @Resource
  private OrderInfoService orderInfoService;
  @Resource
  private OrderGoodsService orderGoodsService;
  @Resource
  private GoodsService goodsService;
  @Resource
  private UsersService usersService;
  @Resource
  private CartService cartService;

  @Resource
  private RedisUtil redisUtil;

  @ApiModelProperty("微信支付通知")
  @PostMapping()
  public String demo(@RequestBody Transaction transaction){

    System.out.println("支付通知 >>>>> ");
    System.out.println("transaction = " + transaction);

    // TODO 1.查询订单信息
    final Order order = orderService.getByOutTradeNo(transaction.getOutTradeNo());
    // TODO 2.更新订单支付状态
    order.setPayStatus(1);
    order.setTransactionId(transaction.getTransactionId());
    order.setPayPrice(new BigDecimal(NumberUtil.decimalFormat("0.00", transaction.getAmount().getTotal() * 0.01)));
    order.setPayTime(DateUtil.date());
    order.setExpirationTime(DateUtil.offset(DateUtil.date(), DateField.YEAR, 10));
    orderService.updateById(order);
    // TODO 3.更新订单商品的支付状态
    if (order.getType().equals(0)) {
      final boolean update = orderGoodsService.update(new LambdaUpdateWrapper<OrderGoods>().eq(OrderGoods::getOrderId, order.getOrderId()).set(OrderGoods::getPayStatus, 1));
      System.out.println("update1 = " + update);
      // TODO 3.1 更新商品销量、库存数量
      final List<OrderGoods> orderGoods = orderGoodsService.list(new LambdaQueryWrapper<OrderGoods>().eq(OrderGoods::getOrderId, order.getOrderId()));
      final Set<Integer> goodsIds = orderGoods.stream().map(OrderGoods::getGoodsId).collect(Collectors.toSet());
      final Map<Integer, List<OrderGoods>> collectGoods = orderGoods.stream().collect(Collectors.groupingBy(OrderGoods::getGoodsId));
      final List<Goods> goods = goodsService.list(new LambdaQueryWrapper<Goods>().in(Goods::getGoodsId, goodsIds));
      for (Goods g : goods) {
        final List<OrderGoods> goods1 = collectGoods.get(g.getGoodsId());
        final OrderGoods goods2 = goods1.get(0);
        g.setSales(g.getSales() + goods2.getTotalNum());
        if (g.getStock().compareTo(0) >= 0) {
          g.setStock(g.getStock() - goods2.getTotalNum());
        }

      }
      final boolean batchById = goodsService.updateBatchById(goods);
      System.out.println("batchById = " + batchById);
    }
    if (order.getType().equals(1)) {
      final boolean update = orderInfoService.update(new LambdaUpdateWrapper<OrderInfo>().eq(OrderInfo::getOrderId, order.getOrderId()).set(OrderInfo::getPayStatus, 1));
      System.out.println("update2 = " + update);
      // TODO 3.2 更新订单类型为预定的关联订单信息
    }

    // TODO 4. 清除购物车
    final boolean remove = cartService.remove(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, order.getUserId()).eq(Cart::getIsNew, true));
    System.out.println("remove = " + remove);


    // TODO 5.累计会员积分

    return "订单已支付";
  }

}
