package com.fdkankan.platform.user.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.pay.paypal.PayPalDefaultConfig;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.IOrderService;
import com.fdkankan.platform.order.service.PayOrderService;
import com.fdkankan.platform.user.factory.Entity;
import com.fdkankan.platform.user.vo.ResponseOrder;
import com.fdkankan.platform.user.vo.ResponseOrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PaypalEntity implements Entity {

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private PayPalDefaultConfig payPalDefaultConfig;

    @Value("${main.url}")
    private String mainUrl;

    @Override
    public JSONObject scanPay(RequestPlaceOrder order) throws Exception {
        return getResult(order, mainUrl + payPalDefaultConfig.getPaySuccessUrl(), mainUrl + payPalDefaultConfig.getCancelUrl());
    }

    @Override
    public JSONObject h5Pay(RequestPlaceOrder order, String ip) throws Exception {
        return getResult(order, mainUrl + payPalDefaultConfig.getH5PaySuccessUrl(), mainUrl + payPalDefaultConfig.getH5CancelUrl());
    }

    @Override
    public String getType() {
        return "paypal_0";
    }

    private JSONObject getResult(RequestPlaceOrder order, String successUrl, String cancelUrl) throws Exception {
        ResponseOrder responseOrder = orderService.getOrderDetail(order.getOrderId());
        if (responseOrder.getId() == null)
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);

        List<ResponseOrderItem> items = responseOrder.getOrderItems();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < items.size(); i++) {
            sb.append(items.get(i).getGoodsCount()).append("*").append(items.get(i).getGoodsName());
            if (i != items.size() - 1) {
                sb.append("，");
            }
        }
        String orderSn = responseOrder.getOrderSn();
        orderSn += "_entity";
        return payOrderService.payPalPay(orderSn, sb.toString(), sb.toString(),
                responseOrder.getTotalAmount(), responseOrder.getGoodsAmount(),
                successUrl,
                cancelUrl);
    }
}
