package com.gxwebsoft.open.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.core.utils.CacheClient;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.entity.Goods;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.entity.OrderGoods;
import com.gxwebsoft.shop.param.CartParam;
import com.gxwebsoft.shop.service.GoodsService;
import com.gxwebsoft.shop.service.OrderGoodsService;
import com.gxwebsoft.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车记录表控制器
 *
 * @author 科技小王子
 * @since 2022-11-25 19:04:43
 */
@Api(tags = "购物车记录表管理")
@RestController
@RequestMapping("/api/open/cart")
public class OpenCartController extends BaseController {
    @Resource
    private GoodsService goodsService;
    @Resource
    private CacheClient cacheClient;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderGoodsService orderGoodsService;

    @ApiOperation("添加购物车")
    @PostMapping("/addCart")
    public ApiResult<?> addCart(@RequestBody OrderGoods param) {
      // 准备数据
      Goods goods = goodsService.getById(param.getGoodsId());
      param.setGoodsName(goods.getGoodsName());
      param.setCategoryId(goods.getCategoryId());
      param.setImageUrl(goods.getImage());
      param.setGoodsNo(goods.getGoodsCode());
      param.setGoodsPrice(param.getGoodsPrice());
      param.setLinePrice(goods.getLinePriceMin());
      param.setGoodsWeight(goods.getGoodsWeight());
      param.setComments(goods.getSellingPoint());
      param.setGear(goods.getGear());
      param.setSortNumber(goods.getSortNumber());
      // 保存到redis
      String key = getKey();
      cacheClient.hPut(key,param.getGoodsId().toString(), JSONUtil.toJSONString(param));
      return success("添加成功",getCart());
    }

    @ApiOperation("查看购物车")
    @GetMapping("/showCart")
    public ApiResult<?> showCart() {
      return success("获取成功",getCart());
    }

    @ApiOperation("从购物车创建订单")
    @PostMapping("/createOrder")
    @Transactional(rollbackFor = {Exception.class})
    public ApiResult<?> createOrder(@RequestBody CartParam param) {
      Integer userId = 0;
      if(param.getAgentUserId() != null){
        userId = param.getAgentUserId();
      }else{
        userId = getLoginUserId();
      }
      // 1.从缓存读取用户的购物车数据
      List<OrderGoods> orderGoods = getCart();
      if(orderGoods == null){
        throw new BusinessException("订单不存在");
      }
      // 2.创建订单
      Order order = new Order();
      order.setOrderNo(IdUtil.getSnowflakeNextId());
      order.setTotalPrice(param.getTotalPrice());
      order.setOrderPrice(param.getTotalPrice());
      order.setPayPrice(param.getTotalPrice());
      order.setDeliveryTime(Date.valueOf(param.getDeliveryTime()));
      order.setExpirationTime(DateUtil.nextMonth());
      order.setUserId(userId);
      orderService.save(order);
      orderGoods.forEach(d -> {
        // 附加orderId
        d.setOrderId(order.getOrderId());
      });
      // 3.批量添加订单商品
      orderGoodsService.saveBatch(orderGoods);
      // 4.清空购物车
      cacheClient.delete(getKey());
      return success("创建成功",order);
    }

    @ApiOperation("清空购物车")
    @GetMapping("/clearCart")
    public ApiResult<?> clearCart() {
      cacheClient.delete(getKey());
      return success("清空成功");
    }

    /**
     * 获取key
     * @return cache10048:cart651
     */
    private String getKey(){
        // 验证签名
        isCheckSign();
        return "cart".concat(getLoginUserId().toString());
    }

    /**
     * 获取购物车数据
     * @return
     */
    private List<OrderGoods> getCart(){
      String key = getKey();
      // 获取购物车数据
      List<Object> values = cacheClient.hValues(key);
      return values.stream().map(item -> JSONUtil.parseObject(JSONUtil.toJSONString(item), OrderGoods.class)).collect(Collectors.toList());
    }

}
