package com.remy.order.controller;

import com.remy.order.entity.Order;
import com.remy.order.service.OrderService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("orders")
public class OrderController {

    @Autowired
    OrderService orderService;

    @RequestMapping()
    public List<Order> findAll() {
        return orderService.findAll();
    }

    @RequestMapping("{orderNo}")
    public Order findBySerialNo(@PathVariable("orderNo") String orderNo) {
        return orderService.findByOrderNo(orderNo);
    }

    @RequestMapping("query")
    public List<Order> findAllByCondition(@RequestParam Map<String, String> params) {
        return orderService.findByCondition(
                Order.builder()
                        .goodsSerialNo(params.get("goodsSerialNo"))
                        .userID(params.get("userID") == null ? null : Long.parseLong(params.get("userID")))
                        .build());
    }

    @PostMapping()
    public Order save(@RequestBody Order order) {
        order.setOrderNo(RandomStringUtils.randomAlphanumeric(10));
        return orderService.save(order);
    }
}
