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/adgroups/add
 * @author moka
 * @since 2026-02-04
 */
@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
class TencentAdsAdgroupCreateTest {

    @Autowired
    private TencentAdsAdgroupService adgroupService;

    @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";
    private static final Long TEST_ADGROUP_ID = 82845099492L;




    @Test
    @DisplayName("测试创建广告-使用提供的测试数据")
    void testCreateAdgroupWithTestData() {
        System.out.println("\n========================================");
        System.out.println("开始创建广告");
        System.out.println("账户ID: " + TEST_ACCOUNT_ID);
        System.out.println("========================================\n");

        try {
            // 构建测试数据（您提供的JSON数据）
            AdgroupsAddRequest request = buildTestRequest(TEST_ACCOUNT_ID);
            
            // 输出请求参数
            System.out.println("========== 请求参数 ==========");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(request));
            System.out.println("========================================\n");

            // 调用创建广告接口
            System.out.println("正在调用腾讯广告创建API...");
            AdgroupsAddResponseData response = adgroupService.createAdgroup(TEST_JOB_NUMBER,TEST_ACCOUNT_ID, request);

            // 输出响应结果
            System.out.println("\n========== API返回结果 ==========");
            Gson gson2 = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson2.toJson(response));
            System.out.println("========================================\n");

            // 输出摘要信息
            if (response != null) {
                System.out.println("✅ 成功创建广告");
                System.out.println("📊 广告ID: " + response.getAdgroupId());
                System.out.println("📊 广告名称: " + request.getAdgroupName());
            } else {
                System.out.println("⚠️  返回结果为空");
            }

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

    /**
     * 构建测试请求对象
     */
    private AdgroupsAddRequest buildTestRequest(Long accountId) {
        AdgroupsAddRequest request = new AdgroupsAddRequest();

        // 基础字段
        request.setAdgroupName("测试MarketingApi线索企微-0204" + System.currentTimeMillis());
        request.setAccountId(accountId);
        //营销目的类型 : 线索留资
        request.setMarketingGoal(MarketingGoal.LEAD_RETENTION);
        //营销载体类型 : 页面跳转
        request.setMarketingCarrierType(MarketingCarrierType.JUMP_PAGE);
        //营销资产外部规格 : 企业微信
        MarketingAssetOuterSpec outerSpec = new MarketingAssetOuterSpec();
        outerSpec.setMarketingTargetType(MarketingTargetType.WECHAT_WORK);
        
        // 产品外部 id 数据 : 企业微信ID 
        outerSpec.setMarketingAssetOuterId("wp7eXwDAAAC2oIBdHTa0-QV8KNGDd3mA");
        request.setMarketingAssetOuterSpec(outerSpec);

        
        // 投放时间
        request.setBeginDate("2026-02-05");
        request.setEndDate("2026-02-06");
        
        // 优化目标
        request.setOptimizationGoal(OptimizationGoal.PAGE_SCAN_CODE);
        
        // 时间序列（全部1表示24小时投放，共7天*48个半小时=336位）
        request.setTimeSeries("111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111");
        
        // 投放站点
        List<String> siteSet = new ArrayList<>();
        siteSet.add("SITE_SET_MOBILE_UNION");
        siteSet.add("SITE_SET_WECHAT");
        siteSet.add("SITE_SET_WECHAT_PLUGIN");
        siteSet.add("SITE_SET_TENCENT_VIDEO");
        siteSet.add("SITE_SET_SEARCH_SCENE");

        request.setSiteSet(siteSet);
        
        // 出价金额（单位：分）
        request.setBidAmount(100L);
        // 出价场景 常规投放-稳定投放
        request.setBidScene(BidScene.NORMAL_AVERAGE);
        
        // 日预算（单位：分）
        request.setDailyBudget(10000L);
    
        // 出价模式
        request.setBidMode(BidMode.OCPM);

        // 转化 id
        request.setConversionId(67676141L);
        
        // 自动衍生创意
        request.setAutoDerivedCreativeEnabled(false);
        
        // 出价场景
        request.setBidScene(BidScene.UNKNOWN);
        
        // 定向设置
        WriteTargetingSetting targeting = buildTargetingSetting();
        request.setTargeting(targeting);

        // 创意增强 MAX 开关
        request.setAutoDerivedCreativeEnabled(true);

        return request;
    }

    /**
     * 构建定向设置
     */
    private WriteTargetingSetting buildTargetingSetting() {
        WriteTargetingSetting targeting = new WriteTargetingSetting();

        // 地域定向
        GeoLocations geoLocation = new GeoLocations();
        List<String> locationTypes = new ArrayList<>();
        locationTypes.add("LIVE_IN"); // 居住地
        geoLocation.setLocationTypes(locationTypes);
        List<Long> regions = new ArrayList<>();
        regions.add(1156L); // 地域ID：1156（中国）
        geoLocation.setRegions(regions);
        targeting.setGeoLocation(geoLocation);

        // 性别定向
        List<String> gender = new ArrayList<>();
        gender.add("MALE"); // 男性
        targeting.setGender(gender);

        // 年龄定向
        List<AgeStruct> age = new ArrayList<>();
        AgeStruct ageRange = new AgeStruct();
        ageRange.setMin(35L);
        ageRange.setMax(66L);
        age.add(ageRange);
        targeting.setAge(age);


        //排除已转化用户：同集团（自定义转化行为：指定页面曝光,加企业微信客服）（转化时间区间：1个月）
        // 排除已转化人群行为定向，排除已转化用户定向范围
        ExcludedConvertedAudience excludedConverted = new ExcludedConvertedAudience();
        // 排除已转化人群行为定向 EXCLUDED_DIMENSION_GROUP 集团
        excludedConverted.setExcludedDimension(ExcludedDimension.EXCLUDED_DIMENSION_GROUP);
        
        //转化行为
        List<String> conversionBehaviorList = new ArrayList<>();
        conversionBehaviorList.add("OPTIMIZATIONGOAL_BRAND_CONVERSION"); //品牌转化
        conversionBehaviorList.add("OPTIMIZATIONGOAL_PAGE_SCAN_CODE"); //加企业微信客服
        excludedConverted.setConversionBehaviorList(conversionBehaviorList);
        
        // 转化时间区间：1个月
        //排除天数 EXCLUDED_DAY_ONE_MONTH 1 个月
        excludedConverted.setExcludedDay(ExcludedDay.ONE_MONTH);
        // 排除已转化人群行为定向，排除已转化用户定向范围
        targeting.setExcludedConvertedAudience(excludedConverted);

        // 排除自定义人群
        List<Long> excludedCustomAudience = new ArrayList<>();
        excludedCustomAudience.add(44106830L);
        excludedCustomAudience.add(44107982L);
        excludedCustomAudience.add(43712084L);
        targeting.setExcludedCustomAudience(excludedCustomAudience);

        return targeting;
    }

    @Test
    @DisplayName("测试创建动态创意")
    void testCreateDynamicCreative() {
        System.out.println("\n========================================");
        System.out.println("开始创建动态创意");
        System.out.println("账户ID: " + TEST_ACCOUNT_ID);
        System.out.println("广告ID: " + TEST_ADGROUP_ID);
        System.out.println("========================================\n");

        try {
            // 获取TencentAds实例
            TencentAds tencentAds = clientFactory.getTencentAds(TEST_JOB_NUMBER, ORG_ACCOUNT_ID);
            tencentAds.setDebug(true);
            
            // 构建动态创意请求
            DynamicCreativesAddRequest request = buildDynamicCreativeRequest();
            
            // 输出请求参数
            System.out.println("========== 请求参数 ==========");
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            System.out.println(gson.toJson(request));
            System.out.println("========================================\n");

            // 调用创建动态创意接口
            System.out.println("正在调用腾讯广告创建动态创意API...");
            DynamicCreativesAddResponseData response = tencentAds.dynamicCreatives()
                .dynamicCreativesAdd(request);

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

            // 输出摘要信息
            if (response != null) {
                System.out.println("✅ 成功创建动态创意");
                System.out.println("📊 动态创意ID: " + response.getDynamicCreativeId());
                System.out.println("📊 动态创意名称: " + request.getDynamicCreativeName());
            } else {
                System.out.println("⚠️  返回结果为空");
            }

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

    /**
     * 构建动态创意请求对象
     */
    private DynamicCreativesAddRequest buildDynamicCreativeRequest() {
        DynamicCreativesAddRequest request = new DynamicCreativesAddRequest();
        
        // 必填字段
        request.setAccountId(TEST_ACCOUNT_ID);
        request.setAdgroupId(TEST_ADGROUP_ID);
        request.setDynamicCreativeName("测试动态创意-" + System.currentTimeMillis());
        
        // 创意组件
        request.setDeliveryMode(DeliveryMode.COMPONENT);
        request.setDynamicCreativeType(DynamicCreativeType.PROGRAM);
        CreativeComponents components = buildCreativeComponents();
        request.setCreativeComponents(components);
        
        return request;
    }

    /**
     * 构建创意组件
     */
    private CreativeComponents buildCreativeComponents() {
        CreativeComponents components = new CreativeComponents();
        
        // 标题组件
        List<TitleComponent> titles = new ArrayList<>();
        TitleComponent title1 = new TitleComponent();
        TitleStruct titleValue1 = new TitleStruct();
        titleValue1.setContent("优质产品推荐");
        title1.setValue(titleValue1);
        titles.add(title1);
        
        TitleComponent title2 = new TitleComponent();
        TitleStruct titleValue2 = new TitleStruct();
        titleValue2.setContent("限时优惠活动");
        title2.setValue(titleValue2);
        titles.add(title2);
        
        components.setTitle(titles);
        
        // 文案
        List<DescriptionComponent> descriptions = new ArrayList<>();
        DescriptionComponent desc1 = new DescriptionComponent();
        DescriptionStruct descValue1 = new DescriptionStruct();
        descValue1.setContent("高品质产品，值得信赖");
        desc1.setValue(descValue1);
        descriptions.add(desc1);
        
        DescriptionComponent desc2 = new DescriptionComponent();
        DescriptionStruct descValue2 = new DescriptionStruct();
        descValue2.setContent("限时特惠，机会难得");
        desc2.setValue(descValue2);
        descriptions.add(desc2);
        
        components.setDescription(descriptions);
        
        // 图片组件（需要先上传图片获取image_id）
        List<ImageComponent> images = new ArrayList<>();
        ImageComponent image1 = new ImageComponent();
        ImageStruct imageValue1 = new ImageStruct();
        imageValue1.setImageId("32253396893"); // 需要替换为实际上传的图片ID
        image1.setValue(imageValue1);
        images.add(image1);
        
        components.setImage(images);

        //品牌形象
        List<BrandComponent> brands = new ArrayList<>();
        BrandComponent brand = new BrandComponent();
        BrandStruct brandValue = new BrandStruct();
        brandValue.setBrandName("情感美女");
        brandValue.setBrandImageId("24319699712");
        brand.setValue(brandValue);
        brand.setComponentId(44579024220L);
        brands.add(brand);
        components.setBrand(brands);


        // 落地页
        // 落地页ID: 1653380852
        // 落地页ID: 1603275376
        // 落地页ID: 1612635779
        // main_jump_info
        List<JumpinfoComponent> mainJumpInfo = new ArrayList<>();

        JumpinfoComponent jumpinfo = new JumpinfoComponent();
        JumpinfoStruct jumpinfoValue = new JumpinfoStruct();
        PageSpec pageSpec = new PageSpec();
        XjPageSpec xjPageSpec = new XjPageSpec();
        xjPageSpec.setPageId(1653380852L);
        pageSpec.setOfficialSpec(xjPageSpec);
        jumpinfoValue.setPageSpec(pageSpec);
        jumpinfoValue.setPageType(PageType.OFFICIAL);
        jumpinfo.setValue(jumpinfoValue);
        mainJumpInfo.add(jumpinfo);

        //再创建一个pageId = 1603275376
        JumpinfoComponent jumpinfo2 = new JumpinfoComponent();
        JumpinfoStruct jumpinfoValue2 = new JumpinfoStruct();
        PageSpec pageSpec2 = new PageSpec();
        XjPageSpec xjPageSpec2 = new XjPageSpec();
        xjPageSpec2.setPageId(1603275376L);
        pageSpec2.setOfficialSpec(xjPageSpec2);
        jumpinfoValue2.setPageSpec(pageSpec2);
        jumpinfoValue2.setPageType(PageType.OFFICIAL);
        jumpinfo2.setValue(jumpinfoValue2);
        mainJumpInfo.add(jumpinfo2);

        //再创建一个pageId = 1612635779
        JumpinfoComponent jumpinfo3 = new JumpinfoComponent();
        JumpinfoStruct jumpinfoValue3 = new JumpinfoStruct();
        PageSpec pageSpec3 = new PageSpec();
        XjPageSpec xjPageSpec3 = new XjPageSpec();
        xjPageSpec3.setPageId(1612635779L);
        pageSpec3.setOfficialSpec(xjPageSpec3);
        jumpinfoValue3.setPageSpec(pageSpec3);
        jumpinfoValue3.setPageType(PageType.OFFICIAL);
        jumpinfo3.setValue(jumpinfoValue3);
        mainJumpInfo.add(jumpinfo3);

        components.setMainJumpInfo(mainJumpInfo);

        //action_button
        List<ActionButtonComponent> actionButtons = new ArrayList<>();
        ActionButtonComponent actionButton = new ActionButtonComponent();
        ActionButtonStruct actionButtonValue = new ActionButtonStruct();
        actionButtonValue.setButtonText("了解更多");
        actionButton.setValue(actionButtonValue);
        actionButtons.add(actionButton);
        // 查看详情
        ActionButtonComponent actionButton2 = new ActionButtonComponent();
        ActionButtonStruct actionButtonValue2 = new ActionButtonStruct();
        actionButtonValue2.setButtonText("查看详情");
        actionButton2.setValue(actionButtonValue2);
        actionButtons.add(actionButton2);
        components.setActionButton(actionButtons);
    
                
        return components;
    }
}
