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

import com.amazon.spapi.api.SellersApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.sellers.*;
import com.amazon.spapi.SellingPartnerAPIAA.*;

import java.sql.*;
import java.util.Arrays;
import java.util.List;

public class AmazonStoreManager {

    private final SellersApi sellersApi;
    private final List<String> marketplaceIds;
    private final Connection dbConnection;

    public AmazonStoreManager(List<String> marketplaceIds, String dbUrl, String dbUser, String dbPassword) throws SQLException {
        this.marketplaceIds = marketplaceIds;
        this.sellersApi = initializeSellersApi();
        this.dbConnection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
    }

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

    public void fetchAndSaveStoreInfo() {
        try {
            GetMarketplaceParticipationsResponse response = sellersApi.getMarketplaceParticipations();
            List<MarketplaceParticipation> participations = response.getPayload();

            for (MarketplaceParticipation participation : participations) {
                Marketplace marketplace = participation.getMarketplace();
                Participation participationData = participation.getParticipation();

                // 保存到数据库
                String sql = "INSERT INTO amazon_stores (marketplace_id, name, country_code, default_currency_code, default_language_code, domain_name, is_participating) " +
                        "VALUES (?, ?, ?, ?, ?, ?, ?) " +
                        "ON DUPLICATE KEY UPDATE name = ?, country_code = ?, default_currency_code = ?, default_language_code = ?, domain_name = ?, is_participating = ?";

                try (PreparedStatement pstmt = dbConnection.prepareStatement(sql)) {
                    pstmt.setString(1, marketplace.getId());
                    pstmt.setString(2, marketplace.getName());
                    pstmt.setString(3, marketplace.getCountryCode());
                    pstmt.setString(4, marketplace.getDefaultCurrencyCode());
                    pstmt.setString(5, marketplace.getDefaultLanguageCode());
                    pstmt.setString(6, marketplace.getDomainName());
                    pstmt.setBoolean(7, participationData.isIsParticipating());

                    // 更新部分
                    pstmt.setString(8, marketplace.getName());
                    pstmt.setString(9, marketplace.getCountryCode());
                    pstmt.setString(10, marketplace.getDefaultCurrencyCode());
                    pstmt.setString(11, marketplace.getDefaultLanguageCode());
                    pstmt.setString(12, marketplace.getDomainName());
                    pstmt.setBoolean(13, participationData.isIsParticipating());

                    pstmt.executeUpdate();
                }
            }
        } catch (ApiException | SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateLocalStoreInfo(String marketplaceId, boolean isParticipating) {
        String sql = "UPDATE amazon_stores SET is_participating = ? WHERE marketplace_id = ?";
        try (PreparedStatement pstmt = dbConnection.prepareStatement(sql)) {
            pstmt.setBoolean(1, isParticipating);
            pstmt.setString(2, marketplaceId);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void syncStoreInfoToAmazon() {
        String sql = "SELECT marketplace_id, is_participating FROM amazon_stores";
        try (Statement stmt = dbConnection.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                String marketplaceId = rs.getString("marketplace_id");
                boolean isParticipating = rs.getBoolean("is_participating");

                // 这里应该调用亚马逊的API来更新店铺信息
                // 注意：亚马逊可能不允许直接修改某些店铺信息，这里仅作为示例
                System.out.println("Syncing store info for marketplace " + marketplaceId + ": isParticipating = " + isParticipating);
                // 实际的API调用应该放在这里
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            if (dbConnection != null && !dbConnection.isClosed()) {
                dbConnection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<String> marketplaceIds = Arrays.asList("YOUR_MARKETPLACE_ID");
        try {
            AmazonStoreManager manager = new AmazonStoreManager(marketplaceIds, "jdbc:mysql://localhost:3306/your_database", "your_username", "your_password");

            // 从亚马逊拉取店铺信息并保存到本地
            manager.fetchAndSaveStoreInfo();

            // 在本地更新店铺信息
            manager.updateLocalStoreInfo("YOUR_MARKETPLACE_ID", false);

            // 将本地更改同步回亚马逊
            manager.syncStoreInfoToAmazon();

            manager.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}