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

import com.amazon.spapi.api.OrdersV0Api;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.orders.*;
import com.amazon.spapi.SellingPartnerAPIAA.*;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.List;

public class AmazonOrderFetcher {

    private final OrdersV0Api ordersApi;
    private final List<String> marketplaceIds;

    public AmazonOrderFetcher(List<String> marketplaceIds) {
        this.marketplaceIds = marketplaceIds;
        this.ordersApi = initializeOrdersApi();
    }

    private OrdersV0Api initializeOrdersApi() {
        LWAAuthorizationCredentials lwaAuthorizationCredentials = LWAAuthorizationCredentials.builder()
                .clientId("YOUR_LWA_CLIENT_ID")
                .clientSecret("YOUR_LWA_CLIENT_SECRET")
                .refreshToken("YOUR_REFRESH_TOKEN")
                .endpoint("https://api.amazon.com/auth/o2/token")
                .build();

        AWSAuthenticationCredentials awsAuthenticationCredentials = AWSAuthenticationCredentials.builder()
                .accessKeyId("YOUR_AWS_ACCESS_KEY")
                .secretKey("YOUR_AWS_SECRET_KEY")
                .region("YOUR_AWS_REGION")
                .build();

        AWSAuthenticationCredentialsProvider awsAuthenticationCredentialsProvider = AWSAuthenticationCredentialsProvider.builder()
                .roleArn("YOUR_ROLE_ARN")
                .roleSessionName("session-name")
                .build();

        return new OrdersV0Api.Builder()
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                .endpoint("https://sellingpartnerapi-na.amazon.com")
                .build();
    }

    public void fetchOrders(String createdAfter, String createdBefore) {
        try {
            GetOrdersResponse ordersResponse = ordersApi.getOrders(
                    marketplaceIds,
                    createdAfter,
                    createdBefore,
                    null, // LastUpdatedAfter
                    null, // LastUpdatedBefore
                    Arrays.asList("UNSHIPPED", "PARTIALLY_SHIPPED", "SHIPPED"), // OrderStatuses
                    null, // FulfillmentChannels
                    null, // PaymentMethods
                    null, // BuyerEmail
                    null, // SellerOrderId
                    null, // MaxResultsPerPage
                    null, // EasyShipShipmentStatuses
                    null, // NextToken
                    null, // AmazonOrderIds
                    null,  // ActualFulfillmentSupplySourceId
                    null,
                    null
            );

            List<Order> orders = ordersResponse.getPayload().getOrders();
            for (Order order : orders) {
                System.out.println("Order ID: " + order.getAmazonOrderId());
                System.out.println("Order Status: " + order.getOrderStatus());
                System.out.println("Purchase Date: " + order.getPurchaseDate());

                // 获取订单项目
                GetOrderItemsResponse itemsResponse = ordersApi.getOrderItems(order.getAmazonOrderId(),null);
                List<OrderItem> orderItems = itemsResponse.getPayload().getOrderItems();

                System.out.println("Number of items: " + orderItems.size());
                for (OrderItem item : orderItems) {
                    System.out.println("  - SKU: " + item.getSellerSKU());
                    System.out.println("    Title: " + item.getTitle());
                    System.out.println("    Quantity: " + item.getQuantityOrdered());
                    System.out.println("    Price: " + item.getItemPrice().getAmount() + " " + item.getItemPrice().getCurrencyCode());
                    //把已经售卖的商品数量在我们自己的商品库存里面减去
                }
                System.out.println("--------------------");
            }

        } catch (ApiException e) {
            System.err.println("Exception when calling OrdersV0Api: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<String> marketplaceIds = Arrays.asList("YOUR_MARKETPLACE_ID");
        AmazonOrderFetcher fetcher = new AmazonOrderFetcher(marketplaceIds);
        // 获取过去7天的订单
        fetcher.fetchOrders(LocalDateTime.now().toString(), LocalDateTime.now().minusDays(7).toString());
    }
}