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.vo.NewOrderVO;
import cn.edu.ecnu.stu.bookstore.service.impl.BuyerService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

@RestController
@RequestMapping("/buyer")
public class BuyerController {

    @Autowired
    private BuyerService buyerService;

    @PostMapping("/new_order")
    public Result newOrder(@RequestBody NewOrderVO newOrderVO) {
        buyerService.newOrder(newOrderVO);
        return Result.success();
    }

    @PostMapping("/payment")
    public Result payment(@RequestBody JSONObject object) {
        Integer userId = object.getInteger("userId");
        String orderId = object.getString("orderId");
        String password = object.getString("password");
        buyerService.payment(userId, orderId, password);
        return Result.success();
    }

    @PostMapping("/add_funds")
    public Result addFunds(@RequestBody JSONObject object) {
        String username = object.getString("username");
        String password = object.getString("password");
        BigDecimal addValue = object.getBigDecimal("addValue");
        buyerService.addFunds(username, password, addValue);
        return Result.success();
    }

    @GetMapping("/order")
    public Result order() {
        return Result.success(buyerService.getOrderList());
    }

    @PostMapping("/take_delivery")
    public Result takeDelivery(@RequestBody Map<String, String> body) {
        String orderId = body.get("orderId");
        if(!StringUtils.hasText(orderId))
            throw new AppException(Constants.CLIENT_ERROR, Constants.PARAMETER_ERROR_MESSAGE);
        buyerService.takeDelivery(orderId);
        return Result.success();
    }


}
