package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.entity.OrderItem;
import com.example.demo.entity.User;
import com.example.demo.service.OrderItemService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orderItem")
public class OrderItemController {

    @Autowired
    private OrderItemService orderItemService;

    // 增加物品项
    @RequestMapping("/add")
    public String add(@RequestBody OrderItem orderItem){
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        if(null!=user){
            System.out.println(orderItem);
            orderItem.setUserId(user.getUserId());
            orderItemService.save(orderItem);
            return orderItem.getOrderItemId().toString();
        }else {
            return "fail";
        }
    }

    // 根据订单列出订单项
    @RequestMapping("/listByOrder")
    public String listByOrder(@RequestBody Map<String, Object> map){
        Integer orderId= (Integer) map.get("orderId");
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        if(null!=user){
            System.out.println(orderId);
            QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",orderId);
            List<OrderItem> orderItemList=orderItemService.list(wrapper);
            return JSON.toJSONString(orderItemList);
        }else {
            return "fail";
        }
    }

    // 根据用户列出订单项
    @RequestMapping("/listByUser")
    public List<OrderItem> listByUser(){
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        if(null!=user){
            QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",user.getUserId());
            List<OrderItem> orderItemList=orderItemService.list(wrapper);
            return orderItemList;
        }else {
            return null;
        }
    }
}
