package com.moka.gdtauto.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.moka.gdtauto.GdtAutoApplication;
import com.moka.gdtauto.client.TencentAdsApiClientFactory;
import com.tencent.ads.model.v3.*;
import com.tencent.ads.v3.TencentAds;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.util.ArrayList;
import java.util.List;

/**
 * 腾讯广告 获取落地页列表 测试
 * https://developers.e.qq.com/v3.0/docs/api/pages/get
 * @author moka
 * @since 2026-02-07
 */
@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
class TencentPagesTest {

    @Autowired
    private TencentAdsApiClientFactory clientFactory;

    private static final Long ORG_ACCOUNT_ID = 33453856L;
    private static final Long TEST_ACCOUNT_ID = 69781948L;
    private static final String TEST_JOB_NUMBER = "12458";

    @Test
    @DisplayName("测试获取落地页列表")
    void testGetPages() {
        System.out.println("\n========================================");
        System.out.println("开始获取落地页列表");
        System.out.println("账户ID: " + TEST_ACCOUNT_ID);
        System.out.println("========================================\n");

        try {
            // 获取TencentAds实例
            TencentAds tencentAds = clientFactory.getTencentAds(TEST_JOB_NUMBER, ORG_ACCOUNT_ID);
            tencentAds.setDebug(true);
            
            // 构建请求参数
            List<FilteringStruct> filtering = buildFiltering();
            AdContext adContext = buildAdContext();
            Long page = 1L;
            Long pageSize = 10L;
            List<String> fields = null; // 返回所有字段
            
            // 输出请求参数
            System.out.println("========== 请求参数 ==========");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println("accountId: " + TEST_ACCOUNT_ID);
            System.out.println("filtering: " + gson.toJson(filtering));
            System.out.println("page: " + page);
            System.out.println("pageSize: " + pageSize);
            System.out.println("adContext: " + gson.toJson(adContext));
            System.out.println("========================================\n");

            // 调用获取落地页列表接口
            System.out.println("正在调用腾讯广告获取落地页列表API...");
            PagesGetResponseData response = tencentAds.pages()
                .pagesGet(TEST_ACCOUNT_ID, filtering, page, pageSize, adContext, fields);

            // 输出响应结果
            System.out.println("\n========== API返回结果 ==========");
            System.out.println(gson.toJson(response));
            System.out.println("========================================\n");

            // 输出摘要信息
            if (response != null && response.getList() != null) {
                System.out.println("✅ 成功获取落地页列表");
                System.out.println("📊 落地页数量: " + response.getList().size());
                
                // 输出每个落地页的详细信息
                for (int i = 0; i < response.getList().size(); i++) {
                    PagesGetListStruct page1 = response.getList().get(i);
                    System.out.println("\n--- 落地页 " + (i + 1) + " ---");
                    System.out.println("落地页ID: " + page1.getPageId());
                    System.out.println("落地页名称: " + page1.getPageName());
                    System.out.println("落地页类型: " + page1.getPageType());
                    System.out.println("落地页状态: " + page1.getPageStatus());
                    System.out.println("落地页禁用码: " + page1.getDisableCode());
                    System.out.println("落地页禁用消息: " + page1.getDisableMessage());
                }
                
                // 输出分页信息
                if (response.getPageInfo() != null) {
                    System.out.println("\n--- 分页信息 ---");
                    System.out.println("当前页: " + response.getPageInfo().getPage());
                    System.out.println("每页条数: " + response.getPageInfo().getPageSize());
                    System.out.println("总页数: " + response.getPageInfo().getTotalPage());
                    System.out.println("总条数: " + response.getPageInfo().getTotalNumber());
                }
            } else {
                System.out.println("⚠️  返回结果为空或无落地页");
            }

        } catch (Exception e) {
            System.err.println("\n❌ API调用失败");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("测试失败", e);
        }
    }

    /**
     * 构建过滤条件
     */
    private List<FilteringStruct> buildFiltering() {
        List<FilteringStruct> filtering = new ArrayList<>();
        FilteringStruct filter = new FilteringStruct();
        filter.setField("page_type");
        filter.setOperator(FilterOperator.EQUALS);
        List<String> values = new ArrayList<>();
        values.add("PAGE_TYPE_OFFICIAL");
        filter.setValues(values);
        filtering.add(filter);
        return filtering;
    }

    /**
     * 构建广告上下文信息
     */
    private AdContext buildAdContext() {
        AdContext adContext = new AdContext();
        
        // 营销目的类型（必填） 用户增长
        adContext.setMarketingGoal(MarketingGoal.USER_GROWTH);
        
        // 二级营销目的类型
        adContext.setMarketingSubGoal(MarketingSubGoal.UNKNOWN);
        
        // 营销载体类型（必填）页面跳转
        adContext.setMarketingCarrierType(MarketingCarrierType.JUMP_PAGE);
        

        // 推广内容类型
        adContext.setPromotedAssetType(PromotedAssetType.SHORT_DRAMA);
        
        // 推广产品： 短剧
        // 产品ID （短剧ID）
        adContext.setMarketingAssetId(421635930L);
        // 推广产品类型（必填）
        adContext.setMarketingTargetType(MarketingTargetType.SHORT_DRAMA);
        
        // 广告版位
        // 投放站点集合（必填）
        List<String> siteSet = new ArrayList<>();
        siteSet.add("SITE_SET_WECHAT");
        siteSet.add("SITE_SET_WECHAT_PLUGIN");
        siteSet.add("SITE_SET_MOBILE_UNION");
        siteSet.add("SITE_SET_KANDIAN");
        siteSet.add("SITE_SET_TENCENT_NEWS");
        siteSet.add("SITE_SET_TENCENT_VIDEO");
        siteSet.add("SITE_SET_MOMENTS");
        adContext.setSiteSet(siteSet);
        
        // 创意形式ID（必填）
        adContext.setCreativeTemplateId(0L);
        
        // 优化目标结构体
        // 转化归因看这个TencentConversionGetTest
        AdContextOptimizationGoalStruct optimizationGoalStruct = new AdContextOptimizationGoalStruct();
        optimizationGoalStruct.setOptimizationGoal(OptimizationGoal.APP_REGISTER);
        adContext.setOptimizationGoalStruct(optimizationGoalStruct);
        
        return adContext;
    }
}
