package cn.edu.hactcm.cotroller;

import cn.edu.hactcm.common.MyThreadLocalForEmployeeId;
import cn.edu.hactcm.common.R;
import cn.edu.hactcm.entity.ShoppingCart;
import cn.edu.hactcm.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //将购物车数据持久化到数据库时肯定是将菜品与用户ID相关联，准备用户ID
        Long userId = MyThreadLocalForEmployeeId.getCurrentId();
        shoppingCart.setUserId(userId);

        //根据用户ID及菜品/套餐ID查看购物车中是否已经有相关数据，如果有，将number属性值加一（update），否则将该信息写入数据库中(save)
        //拼接查询条件并查询是否已有相关数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<ShoppingCart>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        if (shoppingCart.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }else {
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        ShoppingCart shoppingCartInfo = shoppingCartService.getOne(queryWrapper);
        if (shoppingCartInfo != null) {
            //如果已存在,update
            shoppingCartInfo.setNumber(shoppingCartInfo.getNumber()+1);
            shoppingCartService.updateById(shoppingCartInfo);
        }else {
            //如果不存在,save
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
        }

        return R.success(shoppingCart);
    }


    @GetMapping("/list")
    public R<List<ShoppingCart>> CartList(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,MyThreadLocalForEmployeeId.getCurrentId()).orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        return R.success(shoppingCarts);
    }

    @DeleteMapping("/clean")
    public R<String> clean(){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,MyThreadLocalForEmployeeId.getCurrentId());
        boolean flag = shoppingCartService.remove(queryWrapper);
        return R.success("删除成功！");
    }
}
