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.ExpansionOrder;
import com.fdkankan.platform.order.request.RequestPlaceOrder;
import com.fdkankan.platform.order.service.IExpansionOrderService;
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 PaypalExpansion implements Expansion {

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private IExpansionOrderService expansionOrderService;
    @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 {
        ExpansionOrder expansion = expansionOrderService.getById(order.getOrderId());
        if (expansion == null) {
            throw new BusinessException(ErrorCode.FAILURE_CODE_8001);
        }
        String date = "1年";
        if(expansion.getMonth() < 12){
            date = expansion.getMonth() + "个月";
        }
        String subject = Constant.EXPANSION_SUBJECT + "：" + expansion.getUnitSize() + expansion.getUnit() + "/" + date;
        String orderSn = expansion.getOrderSn();
        orderSn += "_expansion";
        String body = subject;
        if(order.getSpaceId() != null){
            orderSn += "_" + order.getSpaceId();
        }
        return payOrderService.payPalPay(orderSn, subject, body, expansion.getAmount(), expansion.getAmount(),
                successUrl,
                cancelUrl);
    }

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