package com.ai.da.controller;

import com.ai.da.common.response.Response;
import com.ai.da.model.dto.ProductPurchaseDTO;
import com.ai.da.service.PayPalCheckoutService;
import com.paypal.http.HttpResponse;
import com.paypal.http.exceptions.SerializeException;
import com.paypal.orders.Order;
import com.paypal.payments.Refund;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;

@RestController
@Api(tags = "PayPalCheckout接口")
@RequestMapping("/api/paypal")
public class PayPalCheckoutController {

    @Resource
    private PayPalCheckoutService payPalCheckoutService;

    @ApiOperation(value = "创建订单")
    @PostMapping(value = "/trade")
    public Response<HashMap<String, String>> createOrder(@Valid @RequestBody ProductPurchaseDTO productPurchaseDTO, HttpServletRequest request) throws SerializeException {
        HashMap<String, String> approvalUrl = payPalCheckoutService.createOrder(productPurchaseDTO, request);
        return Response.success(approvalUrl);
    }

    @ApiOperation(value = "ipn异步回调")
    @PostMapping(value = "/ipn/back")
    public Response<String> callback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Boolean result = payPalCheckoutService.doPost(request, response);
        if (result){
            return Response.success(200,"success");
        }else {
            return Response.fail(500,"failure");
        }
    }

    @ApiOperation(value = "查询指定订单")
    @PostMapping(value = "/trade/query/{orderNo}")
    public Response<Order> queryOrder(@PathVariable String orderNo) throws SerializeException {
        Order s = payPalCheckoutService.queryOrder(orderNo);
        return Response.success(s);
    }

    /** 不提供退款接口 */
    @ApiOperation("申请退款")
    @PostMapping("/trade/refund/{orderNo}/{reason}")
    public Response<HttpResponse<Refund>> refund(@PathVariable String orderNo, @PathVariable String reason) throws IOException {
        Boolean response = payPalCheckoutService.refundOrder(orderNo,reason);
        if (response){
            return Response.success();
        }else {
            return Response.fail("Request for refund failed.");
        }
    }

    @ApiOperation("执行扣款")
    @PostMapping("/trade/capture/{orderNo}")
    public Response<com.paypal.orders.Order> captureOrder(@PathVariable String orderNo) throws IOException {
        Order response = payPalCheckoutService.captureOrder(orderNo);
        return Response.success(response);
    }
}

