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

import com.amazon.spapi.api.FeedsApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.feeds.*;
import com.amazon.spapi.SellingPartnerAPIAA.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AmazonInventorySynchronizer {

    private final FeedsApi feedsApi;
    private final String sellerId;
    private final List<String> marketplaceIds;

    public AmazonInventorySynchronizer(String sellerId, List<String> marketplaceIds) {
        this.sellerId = sellerId;
        this.marketplaceIds = marketplaceIds;
        this.feedsApi = initializeFeedsApi();
    }

    private FeedsApi initializeFeedsApi() {
        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 FeedsApi.Builder()
                .lwaAuthorizationCredentials(lwaAuthorizationCredentials)
                .awsAuthenticationCredentials(awsAuthenticationCredentials)
                .awsAuthenticationCredentialsProvider(awsAuthenticationCredentialsProvider)
                .endpoint("https://sellingpartnerapi-na.amazon.com")
                .build();
    }

    public void syncInventory(Map<String, Integer> localInventory) {
        try {
            // 创建 XML 格式的库存更新 feed
            String feedContent = createInventoryFeedContent(localInventory);

            // 创建 feed 文档
            CreateFeedDocumentSpecification feedDocSpec = new CreateFeedDocumentSpecification()
                    .contentType("text/xml; charset=UTF-8");
            CreateFeedDocumentResponse feedDocResponse = feedsApi.createFeedDocument(feedDocSpec);

            // 上传 feed 内容
            uploadFeedDocument(feedDocResponse.getUrl(), feedContent);

            // 创建 feed
            CreateFeedSpecification feedSpec = new CreateFeedSpecification()
                    .feedType("POST_INVENTORY_AVAILABILITY_DATA")
                    .marketplaceIds(marketplaceIds)
                    .inputFeedDocumentId(feedDocResponse.getFeedDocumentId());

            CreateFeedResponse feedResponse = feedsApi.createFeed(feedSpec);

            System.out.println("Inventory feed submitted. Feed ID: " + feedResponse.getFeedId());

        } catch (ApiException | IOException e) {
            System.err.println("Error synchronizing inventory: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void uploadFeedDocument(String url, String content) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");

        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = content.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
    }

    private String createInventoryFeedContent(Map<String, Integer> localInventory) {
        StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xmlBuilder.append("<AmazonEnvelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"amzn-envelope.xsd\">\n");
        xmlBuilder.append("  <Header>\n");
        xmlBuilder.append("    <DocumentVersion>1.01</DocumentVersion>\n");
        xmlBuilder.append("    <MerchantIdentifier>").append(sellerId).append("</MerchantIdentifier>\n");
        xmlBuilder.append("  </Header>\n");
        xmlBuilder.append("  <MessageType>Inventory</MessageType>\n");

        int messageId = 1;
        for (Map.Entry<String, Integer> entry : localInventory.entrySet()) {
            xmlBuilder.append("  <Message>\n");
            xmlBuilder.append("    <MessageID>").append(messageId++).append("</MessageID>\n");
            xmlBuilder.append("    <OperationType>Update</OperationType>\n");
            xmlBuilder.append("    <Inventory>\n");
            xmlBuilder.append("      <SKU>").append(entry.getKey()).append("</SKU>\n");
            xmlBuilder.append("      <Quantity>").append(entry.getValue()).append("</Quantity>\n");
            xmlBuilder.append("    </Inventory>\n");
            xmlBuilder.append("  </Message>\n");
        }

        xmlBuilder.append("</AmazonEnvelope>");
        return xmlBuilder.toString();
    }

    // 示例使用方法
    public static void main(String[] args) {
        String sellerId = "YOUR_SELLER_ID";
        List<String> marketplaceIds = Arrays.asList("YOUR_MARKETPLACE_ID");
        AmazonInventorySynchronizer synchronizer = new AmazonInventorySynchronizer(sellerId, marketplaceIds);

        Map<String, Integer> localInventory = new HashMap<>();
        localInventory.put("SKU001", 100);
        localInventory.put("SKU002", 50);
        localInventory.put("SKU003", 75);

        synchronizer.syncInventory(localInventory);
    }
}