package com.gxwebsoft.shop.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.Cart;
import com.gxwebsoft.shop.entity.Merchant;
import com.gxwebsoft.shop.param.CartParam;
import com.gxwebsoft.shop.service.CartService;
import com.gxwebsoft.shop.service.MerchantService;
import com.gxwebsoft.shop.vo.CartVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 购物车控制器
 *
 * @author 科技小王子
 * @since 2024-07-29 21:02:39
 */
@Api(tags = "购物车管理")
@RestController
@RequestMapping("/api/shop/cart")
public class CartController extends BaseController {
  @Resource
  private CartService cartService;
  @Resource
  private MerchantService merchantService;

  @ApiOperation("分页查询购物车")
  @GetMapping("/page")
  public ApiResult<PageResult<Cart>> page(CartParam param) {
    // 使用关联查询
    return success(cartService.pageRel(param));
  }

  @ApiOperation("查询全部购物车")
  @GetMapping()
  public ApiResult<CartVo> list(CartParam param) {
    if (ObjectUtil.isEmpty(getLoginUser())) {
      return success("请先登录",new CartVo());
    }
    // 附加用户ID
    param.setUserId(getLoginUserId());
    return success(cartService.listRel(param));
  }

  @PreAuthorize("hasAuthority('shop:cart:list')")
  @ApiOperation("根据id查询购物车")
  @GetMapping("/{id}")
  public ApiResult<Cart> get(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(cartService.getByIdRel(id));
  }

  @ApiOperation("添加购物车")
  @PostMapping()
  public ApiResult<?> save(@RequestBody Cart cart) {
    if (ObjectUtil.isEmpty(getLoginUser())) {
      return success("请先登录",null);
    }

    // 修正用户ID
    cart.setUserId(getLoginUserId());
    // 修正购买数量
    if (ObjectUtil.isEmpty(cart.getCartNum())) {
      cart.setCartNum(1);
    }
    // 超出最大限制
    if (cartService.count(new LambdaUpdateWrapper<Cart>().eq(Cart::getUserId,cart.getUserId())) > 50) {
      return fail("购物车宝贝数量已满，建议您先去结算或清理~");
    }
    // 叠加
    final Cart one = cartService.getOne(new LambdaQueryWrapper<Cart>().eq(Cart::getGoodsId, cart.getGoodsId()).eq(Cart::getSpec, cart.getSpec()).eq(Cart::getUserId, cart.getUserId()).eq(Cart::getType, cart.getType()).last("limit 1"));
    if (ObjectUtil.isNotEmpty(one)) {
        one.setCartNum(one.getCartNum() + cart.getCartNum());
        cartService.updateById(one);
        return success("添加成功",one.getId());
    }
    if (cartService.save(cart)) {
      return success("添加成功",cart.getId());
    }

    return fail("添加失败");
  }

  @ApiOperation("修改购物车")
  @PutMapping()
  public ApiResult<?> update(@RequestBody Cart cart) {
    if (cartService.updateById(cart)) {
      final CartParam param = new CartParam();
      param.setType(cart.getType());
      return success("修改成功");
    }
    return fail("修改失败");
  }

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

  @PreAuthorize("hasAuthority('shop:cart:save')")
  @ApiOperation("批量添加购物车")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<Cart> list) {
    if (cartService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('shop:cart:update')")
  @ApiOperation("批量修改购物车")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<Cart> batchParam) {
    if (batchParam.update(cartService, "id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

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

  @ApiOperation("全选操作")
  @PutMapping("/onSelectAll/{yes}")
  public ApiResult<?> onSelectAll(@PathVariable("yes") Boolean yes) {
    if (ObjectUtil.isEmpty(getLoginUser())) {
      return success("请先登录",null);
    }
    final List<Cart> carts = cartService.list(new LambdaUpdateWrapper<Cart>()
      .eq(Cart::getSelected,!yes)
      .eq(Cart::getUserId, getLoginUserId()));
    carts.forEach(d -> {
      d.setSelected(yes);
    });
    return success("修改成功", cartService.updateBatchById(carts));
  }


//  @ApiOperation("我的购物车")
//  @GetMapping("/myCart")
//  public ApiResult<?> myCart(CartParam param) {
//    // 记录当前登录用户id
//    User loginUser = getLoginUser();
//    if (loginUser == null) {
//      return success("请先登录", null);
//    }
//
////    if (param.getIsNew() == null) {
////      param.setIsNew(false);
////    }
//
//    HashMap<String, Object> map = computeCart(param);
//    System.out.println("map = " + map);
//
//    // 查询购物车
//    param.setUserId(loginUser.getUserId());
//    final List<Cart> carts = cartService.listRelMpj(param);
//    System.out.println("carts3 = " + carts);
//
//    // 收集店铺ID
//    final Set<Integer> merchantIds = carts.stream().map(Cart::getMerchantId).collect(Collectors.toSet());
//    if (CollectionUtils.isEmpty(merchantIds)) {
//      map.put("selectAll", false);
//      return success(map);
//    }
//
//    // 查询店铺列
//    final List<Merchant> merchants = merchantService.list(new LambdaQueryWrapper<Merchant>()
//      .select(Merchant::getMerchantId, Merchant::getMerchantName, Merchant::getImage, Merchant::getShopType, Merchant::getAddress)
//      .in(Merchant::getMerchantId, merchantIds));
//
//    // 返回空列表
//    if (CollectionUtils.isEmpty(merchants)) {
//      map.put("merchants", merchants);
//      return success(map);
//    }
//
//    final Map<Integer, List<Cart>> collect = carts.stream().collect(Collectors.groupingBy(Cart::getMerchantId));
//
//    // 封装数据
//    merchants.forEach(d -> {
//      d.setCarts(collect.get(d.getMerchantId()));
//    });
//
//    // 计算购物车金额
//    map.put("merchants", merchants);
//
//    return success(map);
//  }


//  @ApiOperation("计算购物车金额")
//  @GetMapping("/count")
//  public HashMap<String, Object> computeCart(CartParam param) {
//    final LambdaQueryWrapper<Cart> queryWrapper = new LambdaQueryWrapper<>();
//
//    queryWrapper.select(Cart::getId, Cart::getPrice, Cart::getCartNum)
//      .eq(Cart::getUserId, getLoginUserId())
//      .eq(Cart::getType, param.getType())
//      .eq(Cart::getSelected, param.getSelected())
//      .eq(Cart::getIsPay, param.getIsPay())
//      .eq(Cart::getIsNew,param.getIsNew())
//      .eq(Cart::getId,param.getId());
//
////    if (param.getId() != null) {
////      queryWrapper.eq(Cart::getId,param.getId());
////    }
////    if(param.getIsNew() != null){
////      queryWrapper.eq(Cart::getIsNew,param.getIsNew());
////    }
//
//    // 查询购物车数据
//    final List<Cart> carts = cartService.list(queryWrapper);
//    System.out.println("carts2 = " + carts);
//
//    // 计算单品合计价格
//    carts.forEach(d -> {
//      d.setTotalPrice(d.getPrice().multiply(BigDecimal.valueOf(d.getCartNum())));
//    });
//
//    // 保存到数据库
//    cartService.updateBatchById(carts);
//
//    // 计算购物车金额
//    final Integer reduce = carts.stream().map(Cart::getCartNum).reduce(Integer::sum).orElse(0);
//    final BigDecimal reduced = carts.stream().map(Cart::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//    // 是否全选
//    Boolean selectAll = cartService.count(new LambdaQueryWrapper<Cart>()
//      .eq(Cart::getUserId, getLoginUserId())
//      .eq(Cart::getSelected, 0)
//      .eq(Cart::getIsPay, 0)
//    ) == 0;
//
//
//    // 返回给前端
//    final HashMap<String, Object> map = new HashMap<>();
//    map.put("totalCartNum", reduce);
//    map.put("totalPrice", reduced);
//    map.put("selectAll", selectAll);
//
//    return map;
//  }


}
