package com.moka.gdtauto.service;

import com.moka.gdtauto.GdtAutoApplication;
import com.moka.gdtauto.entity.AdPlan;
import com.moka.gdtauto.entity.AdPlanConf;
import com.moka.gdtauto.entity.AdPlanCreative;
import com.moka.gdtauto.common.AdPlanStatus;
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.List;
import java.util.concurrent.TimeUnit;

/**
 * 广告计划配置异步接口对接测试
 * 测试 asyncTencentInterface 方法
 * 
 * 
 * mvn test -Dtest=AdPlanConfAsyncTest#testAsyncTencentInterface -Dspring.profiles.active=test
 * 
 * @author moka
 * @since 2026-02-25
 */
@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
class AdPlanConfAsyncTest {

    @Autowired
    private AdPlanConfService adPlanConfService;

    @Autowired
    private AdPlanService adPlanService;

    @Autowired
    private AdPlanCreativeService adPlanCreativeService;

    private static final Long TEST_CONF_ID = 4L;

    @Test
    @DisplayName("测试异步对接腾讯接口-从数据库获取confId=4的数据")
    void testAsyncTencentInterface() throws InterruptedException {
        System.out.println("\n========================================");
        System.out.println("开始测试异步对接腾讯接口");
        System.out.println("配置ID: " + TEST_CONF_ID);
        System.out.println("========================================\n");

        // 1. 查询广告计划配置
        AdPlanConf conf = adPlanConfService.getById(TEST_CONF_ID);
        if (conf == null) {
            System.err.println("❌ 未找到配置，confId=" + TEST_CONF_ID);
            return;
        }
        
        System.out.println("📋 广告计划配置信息:");
        System.out.println("  配置ID: " + conf.getId());
        System.out.println("  配置名称: " + conf.getName());
        System.out.println("  工号: " + conf.getJobNumber());
        System.out.println("  账号组ID: " + conf.getAccountGroupId());
        System.out.println("  广告类型: " + (conf.getAdType() == 1 ? "企微" : "ROI"));
        System.out.println("  出价金额: " + conf.getBidAmount() + "分");
        System.out.println("  转化ID: " + conf.getConversionId());
        System.out.println();

        // 2. 查询该配置下的所有 AdPlan
        List<AdPlan> plans = adPlanService.getAdPlans(
            TEST_CONF_ID, null, null, 1, 1, 100
        ).getRecords();
        
        if (plans == null || plans.isEmpty()) {
            System.err.println("❌ 未找到广告计划，confId=" + TEST_CONF_ID);
            return;
        }

        System.out.println("📊 找到 " + plans.size() + " 个广告计划:");
        for (AdPlan plan : plans) {
            if (plan.getId() > 1) {
                continue;
            }
            System.out.println("  - 计划ID: " + plan.getId() + 
                ", 广告名称: " + plan.getAdgroupName() + 
                ", 账户ID: " + plan.getAccountId() +
                ", 状态: " + plan.getStatus());
            
            // 查询该计划的创意
            List<AdPlanCreative> creatives = adPlanCreativeService.getCreativesByPlanId(plan.getId());
            if (creatives != null && !creatives.isEmpty()) {
                System.out.println("    创意数量: " + creatives.size());
                for (AdPlanCreative creative : creatives) {
                    System.out.println("      * " + creative.getCreativeName() + 
                        " (图片ID: " + creative.getImageId() + 
                        ", 落地页: " + creative.getPageIds() + ")");
                }
                // 关联创意到计划对象
                plan.setAdCreatives(creatives);
            }
        }
        System.out.println();

        // 3. 调用异步接口
        System.out.println("🚀 开始调用异步对接腾讯接口...");
        System.out.println("========================================\n");
        
        try {
            adPlanConfService.asyncTencentInterface(conf, plans);
            
            // 等待异步任务完成 (因为是异步方法，需要等待)
            System.out.println("⏳ 等待异步任务执行... (30秒)");
            TimeUnit.SECONDS.sleep(30);
            
            System.out.println("\n========================================");
            System.out.println("📊 异步任务执行完成，查询结果:");
            System.out.println("========================================\n");
            
            // 4. 查询更新后的状态
            AdPlanConf updatedConf = adPlanConfService.getById(TEST_CONF_ID);
            System.out.println("📋 配置状态:");
            System.out.println("  状态: " + getStatusName(updatedConf.getStatus()));
            System.out.println("  失败原因: " + updatedConf.getFailReason());
            System.out.println("  成功时间: " + updatedConf.getSuccessTime());
            System.out.println();
            
            System.out.println("📊 广告计划状态:");
            for (AdPlan plan : plans) {
                AdPlan updatedPlan = adPlanService.getById(plan.getId());
                System.out.println("  - 计划ID: " + updatedPlan.getId());
                System.out.println("    广告组ID: " + updatedPlan.getAdgroupId());
                System.out.println("    状态: " + getStatusName(updatedPlan.getStatus()));
                System.out.println("    失败原因: " + updatedPlan.getFailReason());
                System.out.println("    成功时间: " + updatedPlan.getSuccessTime());
                
                // 查询创意状态
                List<AdPlanCreative> updatedCreatives = adPlanCreativeService.getCreativesByPlanId(updatedPlan.getId());
                if (updatedCreatives != null && !updatedCreatives.isEmpty()) {
                    System.out.println("    创意状态:");
                    for (AdPlanCreative creative : updatedCreatives) {
                        System.out.println("      * " + creative.getCreativeName());
                        System.out.println("        创意ID: " + creative.getCreativeId());
                        System.out.println("        状态: " + getStatusName(creative.getStatus()));
                        System.out.println("        失败原因: " + creative.getFailReason());
                    }
                }
                System.out.println();
            }
            
            System.out.println("✅ 测试完成");
            
        } catch (Exception e) {
            System.err.println("\n❌ 测试失败");
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("测试失败", e);
        }
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        return AdPlanStatus.getStatusDesc(status);
    }

    @Test
    @DisplayName("测试仅查询配置和计划数据")
    void testQueryOnly() {
        System.out.println("\n========================================");
        System.out.println("查询广告计划配置和计划数据");
        System.out.println("配置ID: " + TEST_CONF_ID);
        System.out.println("========================================\n");

        // 查询配置
        AdPlanConf conf = adPlanConfService.getById(TEST_CONF_ID);
        if (conf == null) {
            System.err.println("❌ 未找到配置");
            return;
        }

        System.out.println("📋 配置信息:");
        System.out.println("  ID: " + conf.getId());
        System.out.println("  名称: " + conf.getName());
        System.out.println("  工号: " + conf.getJobNumber());
        System.out.println("  账号组ID: " + conf.getAccountGroupId());
        System.out.println("  广告类型: " + conf.getAdType() + " (" + (conf.getAdType() == 1 ? "企微" : "ROI") + ")");
        System.out.println("  出价金额: " + conf.getBidAmount() + "分");
        System.out.println("  转化ID: " + conf.getConversionId());
        System.out.println("  企微主体ID: " + conf.getWxCorpid());
        System.out.println("  短剧ID: " + conf.getDramaId());
        System.out.println("  图片IDs: " + conf.getImageIds());
        System.out.println("  落地页IDs: " + conf.getPageIds());
        System.out.println("  站点配置: " + conf.getSites());
        System.out.println("  定向配置: " + conf.getTargets());
        System.out.println("  状态: " + getStatusName(conf.getStatus()));
        System.out.println();

        // 查询计划
        List<AdPlan> plans = adPlanService.getAdPlans(
            TEST_CONF_ID, null, null,1, 1, 100
        ).getRecords();

        System.out.println("📊 找到 " + plans.size() + " 个广告计划:");
        for (AdPlan plan : plans) {
            System.out.println("\n  计划 #" + plan.getId() + ":");
            System.out.println("    广告名称: " + plan.getAdgroupName());
            System.out.println("    账户ID: " + plan.getAccountId());
            System.out.println("    广告组ID: " + plan.getAdgroupId());
            System.out.println("    广告类型: " + plan.getAdType() + " (" + (plan.getAdType() == 1 ? "企微" : "ROI") + ")");
            System.out.println("    出价金额: " + plan.getBidAmount() + "分");
            System.out.println("    转化ID: " + plan.getConversionId());
            System.out.println("    企微主体ID: " + plan.getWxCorpid());
            System.out.println("    短剧ID: " + plan.getDramaId());
            System.out.println("    站点配置: " + plan.getSite());
            System.out.println("    定向配置: " + plan.getTarget());
            System.out.println("    状态: " + getStatusName(plan.getStatus()));
            System.out.println("    失败原因: " + plan.getFailReason());

            // 查询创意
            List<AdPlanCreative> creatives = adPlanCreativeService.getCreativesByPlanId(plan.getId());
            if (creatives != null && !creatives.isEmpty()) {
                System.out.println("    创意列表 (" + creatives.size() + "个):");
                for (AdPlanCreative creative : creatives) {
                    System.out.println("      - " + creative.getCreativeName());
                    System.out.println("        创意ID: " + creative.getCreativeId());
                    System.out.println("        图片ID: " + creative.getImageId());
                    System.out.println("        落地页IDs: " + creative.getPageIds());
                    System.out.println("        状态: " + getStatusName(creative.getStatus()));
                }
            }
        }

        System.out.println("\n✅ 查询完成");
    }
}
