package com.gxwebsoft.shop.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.entity.UserBalanceLog;
import com.gxwebsoft.common.system.service.UserBalanceLogService;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.service.ShopOrderGoodsService;
import com.gxwebsoft.shop.service.ShopOrderService;
import com.gxwebsoft.shop.entity.ShopOrder;
import com.gxwebsoft.shop.param.ShopOrderParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

import static com.gxwebsoft.common.core.constants.BalanceConstants.BALANCE_USE;

/**
 * 订单控制器
 *
 * @author 科技小王子
 * @since 2024-09-10 21:05:07
 */
@Api(tags = "订单管理")
@RestController
@RequestMapping("/api/shop/shop-order")
public class ShopOrderController extends BaseController {
    @Resource
    private ShopOrderService shopOrderService;
    @Resource
    private UserService userService;
    @Resource
    private UserBalanceLogService userBalanceLogService;
    @Resource
    private ShopOrderGoodsService shopOrderGoodsService;
    @Resource
    private RedisUtil redisUtil;

    @PreAuthorize("hasAuthority('shop:shopOrder:list')")
    @ApiOperation("分页查询订单")
    @GetMapping("/page")
    public ApiResult<PageResult<ShopOrder>> page(ShopOrderParam param) {
        // 使用关联查询
        return success(shopOrderService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:list')")
    @ApiOperation("查询全部订单")
    @GetMapping()
    public ApiResult<List<ShopOrder>> list(ShopOrderParam param) {
        // 使用关联查询
        return success(shopOrderService.listRel(param));
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:list')")
    @ApiOperation("根据id查询订单")
    @GetMapping("/{id}")
    public ApiResult<ShopOrder> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(shopOrderService.getByIdRel(id));
    }

    @ApiOperation("添加订单")
    @PostMapping()
    public ApiResult<?> save(@RequestBody ShopOrder shopOrder) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
          shopOrder.setUserId(loginUser.getUserId());
        }
        if (shopOrderService.save(shopOrder)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:update')")
    @ApiOperation("修改订单")
    @PutMapping()
    public ApiResult<?> update(@RequestBody ShopOrder shopOrder) {
        if (shopOrderService.updateById(shopOrder)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:remove')")
    @ApiOperation("删除订单")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (shopOrderService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:save')")
    @ApiOperation("批量添加订单")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<ShopOrder> list) {
        if (shopOrderService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:update')")
    @ApiOperation("批量修改订单")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<ShopOrder> batchParam) {
        if (batchParam.update(shopOrderService, "order_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('shop:shopOrder:remove')")
    @ApiOperation("批量删除订单")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (shopOrderService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

  @ApiOperation("统一下单")
  @PostMapping("/createOrder")
  public ApiResult<?> createOrder(@RequestBody ShopOrder shopOrder) {
    // 记录当前登录用户id
    User loginUser = getLoginUser();
    if (loginUser != null) {
      // 封装订单数据
      shopOrder.setUserId(loginUser.getUserId());
      shopOrder.setOrderNo(Long.toString(IdUtil.getSnowflakeNextId()));
      shopOrder.setPhone(loginUser.getPhone());
      shopOrder.setOpenid(loginUser.getOpenid());
      shopOrder.setTenantId(loginUser.getTenantId());
      shopOrder.setLoginUser(loginUser);
      shopOrder.setRealName(loginUser.getRealName());
      shopOrder.setPayTime(DateUtil.date());

      // 判断支付方式
      if(shopOrder.getPayType() == null){
        return fail("支付方式不能为空");
      }
      // 商品描述(必填)
      if (StrUtil.isBlank(shopOrder.getComments())) {
        return fail("商品描述(必填)");
      }
      // 微信支付
      if(shopOrder.getPayType().equals(1) || shopOrder.getPayType().equals(102)){
        // 微信openid(必填)
        if (StrUtil.isBlank(loginUser.getOpenid())) {
          return fail("微信openid(必填)");
        }
        // 微信支付(商品金额不能为0)
        if (shopOrder.getPayType().equals(1) && shopOrder.getPayType().equals(102)) {
          if (shopOrder.getTotalPrice().compareTo(BigDecimal.ZERO) == 0) {
            return fail("商品金额不能为0");
          }
        }
      }
      if (shopOrderService.save(shopOrder)) {
        // 保存订单商品
        if(shopOrder.getOrderProduct() != null){
          shopOrder.getOrderProduct().forEach(item -> {
            item.setOrderId(shopOrder.getOrderId());
            item.setTenantId(shopOrder.getTenantId());
            item.setOrderCode("product");
            item.setMerchantId(shopOrder.getMerchantId());
            item.setUserId(shopOrder.getUserId());
          });
          final boolean saveBatch = shopOrderGoodsService.saveBatch(shopOrder.getOrderProduct());
          System.out.println("saveBatch = " + saveBatch);
        }
        // 调起支付
        return onPay(shopOrder);
      }
    }
    return fail("下单失败");
  }

  private ApiResult<?> onPay(ShopOrder order) {
    // TODO 余额支付
    if (order.getPayType().equals(0)) {
      final User loginUser = order.getLoginUser();
      if (order.getLoginUser().getBalance().compareTo(order.getTotalPrice()) < 0) {
        throw new BusinessException("余额不足");
      }
      // 扣除余额
      final BigDecimal subtract = loginUser.getBalance().subtract(order.getTotalPrice());
      loginUser.setBalance(subtract);
      final boolean updateUser = userService.updateById(loginUser);
      System.out.println("updateUser = " + updateUser);

      // 记录余额明细
      UserBalanceLog userBalanceLog = new UserBalanceLog();
      userBalanceLog.setUserId(loginUser.getUserId());
      userBalanceLog.setTenantId(loginUser.getTenantId());
      userBalanceLog.setScene(BALANCE_USE);
      userBalanceLog.setMoney(order.getPayPrice());
      BigDecimal balance = loginUser.getBalance().add(order.getPayPrice());
      userBalanceLog.setBalance(balance);
      userBalanceLog.setComments(order.getMerchantName());
      userBalanceLog.setTransactionId(UUID.randomUUID().toString());
      userBalanceLog.setOrderNo(order.getOrderNo());
      final boolean save = userBalanceLogService.save(userBalanceLog);
      System.out.println("记录余额明细 = " + save);

      // 支付成功后的事务处理
      shopOrderService.onPaySuccess(order);
      return success("支付成功",order);
    }

    // TODO 微信统一下单接口
//    if (order.getPayType().equals(1)) {
//      // 清空购物车
//      final Set<Integer> cartIds = order.getGoodsList().stream().map(OrderGoods::getGoodsId).collect(Collectors.toSet());
//      cartService.remove(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId,order.getUserId()).in(Cart::getGoodsId,cartIds));
//      // 外卖订单
//      if(!order.getMerchantId().equals(0)){
//        cartService.remove(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId,order.getUserId()).eq(Cart::getType,1));
//      }
//      return success("下单成功", orderService.createWxOrder(order));
//    }

//      // TODO 微信Native支付
//      if(order.getPayType().equals(102)){
//        order.setAccessToken(access_token);
//        order.setLoginUser(loginUser);
//        return success("下单成功", orderService.payByWxNative(order));
//      }

    // TODO 会员卡支付
//    if(order.getPayType().equals(2)){
//      order.setAccessToken(order.getAccessToken());
//      System.out.println("getAccessToken = " + order.getAccessToken());
//      return success("下单成功", orderService.payByUserCard(order));
//    }
    return fail("支付失败");
  }

}
