package org.wfc.payment.pay.ccpay.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.wfc.payment.pay.ccpay.config.CcpayConfig;
import org.wfc.payment.pay.ccpay.mapper.UCreditCardOrderMapper;
import org.wfc.payment.pay.ccpay.model.PaymentRequest;
import org.wfc.payment.pay.ccpay.model.PaymentResponse;
import org.wfc.payment.pay.ccpay.model.RefundRequest;
import org.wfc.payment.pay.ccpay.model.RefundResponse;
import org.wfc.payment.pay.ccpay.model.UCreditCardOrder;
import org.wfc.payment.pay.ccpay.service.IUCreditCardOrderService;


import java.util.HashMap;
import java.util.Map;

@Service
public class UCreditCardOrderServiceImpl implements IUCreditCardOrderService {

    private final UCreditCardOrderMapper paymentMapper;
    private final CcpayConfig ccpayConfig;

    private static final String CONTENT_TYPE_HEADER = "Content-Type";
    private static final String APPLICATION_JSON = "application/json";

    @Autowired
    public UCreditCardOrderServiceImpl(UCreditCardOrderMapper paymentMapper, CcpayConfig ccpayConfig) {
        this.paymentMapper = paymentMapper;
        this.ccpayConfig = ccpayConfig;
    }

    @Override
    public void saveOrder(UCreditCardOrder order) {
        paymentMapper.insertOrder(order);
    }

    @Override
    public UCreditCardOrder getOrderById(Long id) {
        return paymentMapper.selectOrderById(id);
    }

    @Override
    public String getPaymentToken(PaymentRequest paymentRequest) {
        RestTemplate restTemplate = new RestTemplate();
        String authUrl = ccpayConfig.getTokenUrl();

        HttpHeaders headers = new HttpHeaders();

        headers.set(CONTENT_TYPE_HEADER, "application/x-www-form-urlencoded");

        // 设置请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("grant_type", "client_credentials");
        requestBody.put("client_id", ccpayConfig.getClientId());
        requestBody.put("client_secret", ccpayConfig.getClientSecret());

       // 调用第三方支付网关的 API 获取 token
        ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
                authUrl, HttpMethod.POST, new HttpEntity<>(requestBody, headers),
                new ParameterizedTypeReference<Map<String, Object>>() {});

        // 从响应中提取 token
        Map<String, Object> responseBody = response.getBody();
        if (responseBody != null && responseBody.containsKey("access_token")) {
            return (String) responseBody.get("access_token");
        } else {    
            throw new IllegalStateException("Failed to obtain access token from third-party gateway");
        }        
    }

    @Override
    public PaymentResponse processPayment(PaymentRequest paymentRequest) {
        RestTemplate restTemplate = new RestTemplate();
        PaymentResponse paymentResponse = new PaymentResponse();

        try {
            HttpHeaders headers = new HttpHeaders();            
            headers.set(CONTENT_TYPE_HEADER, APPLICATION_JSON);
  
            // 设置请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("merchantId", ccpayConfig.getMerchantId());
            requestBody.put("currency", ccpayConfig.getCurrency());
            requestBody.put("amount", paymentRequest.getAmount());
            requestBody.put("cardNumber", paymentRequest.getCardNumber());
            requestBody.put("cardHolderName", paymentRequest.getCardHolderName());
            requestBody.put("expirationDate", paymentRequest.getExpirationDate());
            requestBody.put("cvv", paymentRequest.getCvv());
            requestBody.put("callbackUrl", ccpayConfig.getCallbackUrl());

            // 调用第三方支付网关的 API 进行支付处理
            PaymentResponse response = restTemplate.postForObject(ccpayConfig.getPaymentUrl(), requestBody,
                    PaymentResponse.class);

            if (response != null && response.isSuccess()) {
                paymentResponse.setSuccess(true);
                paymentResponse.setMessage("Payment successful");
                paymentResponse.setTransactionId(response.getTransactionId());
            } else {
                paymentResponse.setSuccess(false);
                paymentResponse.setMessage("Payment failed");
            }
        } catch (Exception e) {
            paymentResponse.setSuccess(false);
            paymentResponse.setMessage("Error occurred while processing payment: " + e.getMessage());
        }

        return paymentResponse;
    }

    @Override
    public PaymentResponse queryOrder(Long orderId) {
        // 实现查询订单逻辑
        // 例如，调用第三方支付网关的查询订单接口
        RestTemplate restTemplate = new RestTemplate();
        String queryUrl = ccpayConfig.getQueryUrl() + "/" + orderId;

        ResponseEntity<PaymentResponse> response = restTemplate.getForEntity(queryUrl, PaymentResponse.class);
        return response.getBody();
    }

    @Override
    public RefundResponse refundOrder(RefundRequest refundRequest) {
        // 实现退款逻辑
        // 例如，调用第三方支付网关的退款接口
        RestTemplate restTemplate = new RestTemplate();
        String refundUrl = ccpayConfig.getRefundUrl();
        HttpHeaders headers = new HttpHeaders();
        headers.set(CONTENT_TYPE_HEADER, APPLICATION_JSON);

        HttpEntity<RefundRequest> requestEntity = new HttpEntity<>(refundRequest, headers);
        ResponseEntity<RefundResponse> response = restTemplate.postForEntity(refundUrl, requestEntity,
                RefundResponse.class);
        return response.getBody();
    }    
}