package com.hys.app.service.otherService.amazon;

// 导入必要的库和类
import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazon.spapi.SellingPartnerAPIAA.AWSAuthenticationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.LWAAuthorizationCredentials;
import com.amazon.spapi.SellingPartnerAPIAA.LWAClientScopes;
import com.amazon.spapi.api.OrdersV0Api;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.orders.*;
import org.apache.http.client.utils.URIBuilder;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class AmazonSellerApp {
    // 定义常量，这些应该从安全的配置源获取，而不是硬编码
    private static final String LWA_CLIENT_ID = "YOUR_LWA_CLIENT_ID";
    private static final String LWA_CLIENT_SECRET = "YOUR_LWA_CLIENT_SECRET";
    private static final String AWS_ACCESS_KEY = "YOUR_AWS_ACCESS_KEY";
    private static final String AWS_SECRET_KEY = "YOUR_AWS_SECRET_KEY";
    private static final String AWS_REGION = "us-east-1"; // AWS 区域，这里是美国东部1区
    private static final String REDIRECT_URI = "YOUR_REDIRECT_URI";

    // 用于存储卖家的刷新令牌的线程安全Map
    private static final Map<String, String> sellerRefreshTokens = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        // 生成授权URL并打印
        String authUrl = getAuthorizationUrl();
        System.out.println("Authorization URL: " + authUrl);

        // 模拟处理授权回调
        String authCode = "EXAMPLE_AUTH_CODE"; // 实际应用中，这应该是从重定向URL获取的
        String sellerId = "EXAMPLE_SELLER_ID"; // 实际应用中，这应该是与授权关联的卖家ID
        handleAuthorizationCallback(authCode, sellerId);

        // 拉取订单示例
        fetchOrders(sellerId);
    }

    // 生成授权URL的方法
    public static String getAuthorizationUrl() {
        try {
            URIBuilder builder = new URIBuilder("https://sellercentral.amazon.com/apps/authorize/consent");
            builder.addParameter("application_id", LWA_CLIENT_ID);
            builder.addParameter("redirect_uri", REDIRECT_URI);
            builder.addParameter("state", "YOUR_STATE"); // 应使用唯一的状态值以防止CSRF攻击
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 处理授权回调的方法
    public static void handleAuthorizationCallback(String authCode, String sellerId) {
        try {

            // 使用授权码交换刷新令牌
            String refreshToken = AuthorizationCodeExchange.exchangeAuthorizationCodeForRefreshToken(
                    LWA_CLIENT_ID,
                    LWA_CLIENT_SECRET,
                    authCode,
                    REDIRECT_URI
            );

            // 安全地存储刷新令牌
            sellerRefreshTokens.put(sellerId, refreshToken);
            System.out.println("Refresh token stored for seller: " + sellerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 拉取订单的方法
    public static void fetchOrders(String sellerId) {
        // 获取卖家的刷新令牌
        String refreshToken = sellerRefreshTokens.get(sellerId);
        if (refreshToken == null) {
            System.out.println("No refresh token found for seller: " + sellerId);
            return;
        }

        try {
            // 构建LWA授权凭证
            LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                    .clientId(LWA_CLIENT_ID)
                    .clientSecret(LWA_CLIENT_SECRET)
                    .refreshToken(refreshToken)
                    .endpoint("https://api.amazon.com/auth/o2/token")
                    .scopes(new LWAClientScopes(new HashSet<>())) // 设置空的作用域集合
                    .build();

            // 构建AWS认证凭证
            AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                    .accessKeyId(AWS_ACCESS_KEY)
                    .secretKey(AWS_SECRET_KEY)
                    .region(AWS_REGION)
                    .build();

            // 创建OrdersV0Api实例
            OrdersV0Api ordersApi = new OrdersV0Api.Builder()
                    .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                    .awsAuthenticationCredentials(awsAuthenticationCredentials)
                    .endpoint("https://sellingpartnerapi-na.amazon.com")
                    .build();

            // 设置市场ID（这里是美国市场）
            List<String> marketplaceIds = ListUtil.toList("ATVPDKIKX0DER");
            String createdAfter = "2023-01-01T00:00:00Z"; // 设置订单创建时间的起始点

            // 调用API获取订单
            GetOrdersResponse response = ordersApi.getOrders(null, null, null, null, null, null, null, null, null,
                    null, null, null, null, null, null, null, null);

            // 处理返回的订单数据
            List<Order> orders = response.getPayload().getOrders();
            for (Order order : orders) {
                System.out.println("Order ID: " + order.getAmazonOrderId());
                System.out.println("Purchase Date: " + order.getPurchaseDate());
                System.out.println("Order Status: " + order.getOrderStatus());
                System.out.println("------------------------");
            }

        } catch (ApiException e) {
            System.err.println("Exception when calling OrdersV0Api#getOrders");
            e.printStackTrace();
        }
    }
}