package com.example.demo.service;

import com.example.demo.model.Payment;
import com.example.demo.model.PaymentMethod;
import com.example.demo.model.PaymentStatus;
import com.example.demo.repository.PaymentRepository;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class PayPalService {
    
    private static final Logger logger = LoggerFactory.getLogger(PayPalService.class);
    
    private final PaymentRepository paymentRepository;
    
    @Value("${paypal.client-id}")
    private String clientId;
    
    @Value("${paypal.client-secret}")
    private String clientSecret;
    
    @Value("${paypal.mode}")
    private String mode;
    
    @Value("${paypal.return-url}")
    private String returnUrl;
    
    @Value("${paypal.cancel-url}")
    private String cancelUrl;
    
    public PayPalService(PaymentRepository paymentRepository) {
        this.paymentRepository = paymentRepository;
    }
    
    /**
     * 创建PayPal支付订单
     */
    public String createPayment(Payment payment) {
        try {
            // 设置支付状态
            payment.setStatus(PaymentStatus.PENDING);
            payment.setPaymentMethod(PaymentMethod.PAYPAL);
            payment.setOrderId(generateOrderId());
            payment.setReturnUrl(returnUrl);
            
            // 保存支付记录
            paymentRepository.save(payment);
            
            // 创建API上下文
            APIContext apiContext = new APIContext(clientId, clientSecret, mode);
            
            // 创建支付金额
            Amount amount = new Amount();
            amount.setCurrency(payment.getCurrency());
            amount.setTotal(payment.getAmount().toString());
            
            // 创建交易
            Transaction transaction = new Transaction();
            transaction.setAmount(amount);
            transaction.setDescription(payment.getDescription() != null ? payment.getDescription() : "商品支付");
            
            // 创建交易列表
            List<Transaction> transactions = new ArrayList<>();
            transactions.add(transaction);
            
            // 创建支付者
            Payer payer = new Payer();
            payer.setPaymentMethod("paypal");
            
            // 创建支付
            com.paypal.api.payments.Payment paypalPayment = new com.paypal.api.payments.Payment();
            paypalPayment.setIntent("sale");
            paypalPayment.setPayer(payer);
            paypalPayment.setTransactions(transactions);
            
            // 设置重定向URL
            RedirectUrls redirectUrls = new RedirectUrls();
            redirectUrls.setReturnUrl(returnUrl + "?paymentId={PAY_ID}&PayerID={PAYER_ID}");
            redirectUrls.setCancelUrl(cancelUrl);
            paypalPayment.setRedirectUrls(redirectUrls);
            
            // 创建支付
            com.paypal.api.payments.Payment createdPayment = paypalPayment.create(apiContext);
            
            // 更新支付记录
            payment.setExternalTransactionId(createdPayment.getId());
            paymentRepository.save(payment);
            
            logger.info("PayPal支付订单创建成功，订单号：{}，PayPal ID：{}", 
                payment.getOrderId(), createdPayment.getId());
            
            // 获取批准URL
            for (Links link : createdPayment.getLinks()) {
                if ("approval_url".equals(link.getRel())) {
                    return link.getHref();
                }
            }
            
            throw new RuntimeException("未找到PayPal批准URL");
            
        } catch (PayPalRESTException e) {
            logger.error("PayPal API调用异常：", e);
            payment.setStatus(PaymentStatus.FAILED);
            paymentRepository.save(payment);
            throw new RuntimeException("PayPal支付服务异常：" + e.getMessage());
        }
    }
    
    /**
     * 执行PayPal支付
     */
    public boolean executePayment(String paymentId, String payerId) {
        try {
            // 创建API上下文
            APIContext apiContext = new APIContext(clientId, clientSecret, mode);
            
            // 创建支付执行
            PaymentExecution paymentExecution = new PaymentExecution();
            paymentExecution.setPayerId(payerId);
            
            // 获取支付信息
            com.paypal.api.payments.Payment payment = com.paypal.api.payments.Payment.get(apiContext, paymentId);
            
            // 执行支付
            com.paypal.api.payments.Payment executedPayment = payment.execute(apiContext, paymentExecution);
            
            // 查找支付记录
            Payment paymentRecord = paymentRepository.findByExternalTransactionId(paymentId)
                .orElseThrow(() -> new RuntimeException("支付记录不存在：" + paymentId));
            
            // 更新支付状态
            if ("approved".equals(executedPayment.getState())) {
                paymentRecord.setStatus(PaymentStatus.SUCCESS);
                paymentRecord.setPaidAt(LocalDateTime.now());
                logger.info("PayPal支付成功，订单号：{}", paymentRecord.getOrderId());
            } else {
                paymentRecord.setStatus(PaymentStatus.FAILED);
                logger.warn("PayPal支付失败，订单号：{}，状态：{}", 
                    paymentRecord.getOrderId(), executedPayment.getState());
            }
            
            paymentRepository.save(paymentRecord);
            return true;
            
        } catch (PayPalRESTException e) {
            logger.error("PayPal支付执行异常：", e);
            return false;
        }
    }
    
    /**
     * 处理PayPal Webhook通知
     */
    public boolean handleWebhook(Map<String, String> params) {
        try {
            String eventType = params.get("event_type");
            String resourceType = params.get("resource_type");
            
            logger.info("收到PayPal Webhook通知，事件类型：{}，资源类型：{}", eventType, resourceType);
            
            if ("PAYMENT.SALE.COMPLETED".equals(eventType) && "sale".equals(resourceType)) {
                String paymentId = params.get("resource.id");
                
                // 查找支付记录
                Payment payment = paymentRepository.findByExternalTransactionId(paymentId)
                    .orElseThrow(() -> new RuntimeException("支付记录不存在：" + paymentId));
                
                // 更新支付状态
                payment.setStatus(PaymentStatus.SUCCESS);
                payment.setPaidAt(LocalDateTime.now());
                paymentRepository.save(payment);
                
                logger.info("PayPal Webhook处理成功，订单号：{}", payment.getOrderId());
                return true;
            }
            
            return false;
            
        } catch (Exception e) {
            logger.error("处理PayPal Webhook异常：", e);
            return false;
        }
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderId() {
        return "PP" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
    }
}

