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

import com.alibaba.fastjson.JSONObject;
import com.fdkankan.common.constant.Constant;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.pay.paypal.PayPalDefaultConfig;
import com.fdkankan.platform.order.entity.IncrementOrder;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.IIncrementOrderService;
import com.fdkankan.platform.order.service.PayOrderService;
import com.fdkankan.platform.user.factory.Expansion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PaypalIncrement implements Expansion {

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private IIncrementOrderService incrementOrderService;
    @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());
    }

    private JSONObject getResult(RequestPlaceOrder order, String successUrl, String cancelUrl) throws Exception {
        IncrementOrder incrementOrderEntity = incrementOrderService.getById(order.getOrderId());
        if (incrementOrderEntity == null) {
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        String subject = Constant.INCREMENT_SUBJECT + "：" + incrementOrderEntity.getCount() + "个/年";
        String orderSn = incrementOrderEntity.getOrderSn();
        orderSn += "_increment";
        String body = subject;
        return payOrderService.payPalPay(orderSn, subject, body, incrementOrderEntity.getAmount(), incrementOrderEntity.getAmount(),
                successUrl,
                cancelUrl);
    }

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