package cn.edu.ecnu.stu.bookstore.service.impl;

import cn.edu.ecnu.stu.bookstore.component.AppException;
import cn.edu.ecnu.stu.bookstore.component.Constants;
import cn.edu.ecnu.stu.bookstore.mapper.OrderMapper;
import cn.edu.ecnu.stu.bookstore.pojo.Order;
import cn.edu.ecnu.stu.bookstore.pojo.OrderStatus;
import cn.edu.ecnu.stu.bookstore.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    public List<Order> getOrderList(Integer status) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return orderMapper.select(user.getId(), status == null ? null : OrderStatus.getByValue(status));
    }

    public void cancelOrder(String orderId) {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(orderMapper.checkOrder(orderId, user.getId()) != 1)
            throw new AppException(Constants.CLIENT_ERROR, Constants.AUTHORITY_ERROR);
        orderMapper.updateOrderStatus(orderId, OrderStatus.CANCEL);
    }

    public void add(Order order) {
        orderMapper.insert(order);
    }
}
