package cn.edu.ecnu.stu.bookstore.controller;

import cn.edu.ecnu.stu.bookstore.component.AppException;
import cn.edu.ecnu.stu.bookstore.component.Constants;
import cn.edu.ecnu.stu.bookstore.component.Result;
import cn.edu.ecnu.stu.bookstore.pojo.Order;
import cn.edu.ecnu.stu.bookstore.service.impl.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/")
    public Result getOrderList(@RequestParam(value = "status", required = false) Integer status) {
        return Result.success(orderService.getOrderList(status));
    }

    @PostMapping("/cancel_order")
    public Result cancelOrder(@RequestBody Map<String, Object> map) {
        Object orderIdObj = map.get("orderId");
        if(orderIdObj == null)
            throw new AppException(Constants.CLIENT_ERROR, Constants.PARAMETER_ERROR_MESSAGE);
        String orderId = (String) orderIdObj;
        if(!StringUtils.hasText(orderId))
            throw new AppException(Constants.CLIENT_ERROR, Constants.PARAMETER_ERROR_MESSAGE);
        orderService.cancelOrder(orderId);
        return Result.success();
    }

    @PostMapping("/add")
    public Result add(@RequestBody Order order) {
        orderService.add(order);
        return Result.success();
    }
}
