package com.moka.gdtauto.service;

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

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 com.alibaba.fastjson2.JSON;
import com.moka.gdtauto.GdtAutoApplication;
import com.moka.gdtauto.common.AutoPlanRule;
import com.moka.gdtauto.entity.AdAutoConf;
import com.moka.gdtauto.entity.AdPlan;
import com.moka.gdtauto.entity.AdPlanCreative;
import com.moka.gdtauto.util.RobotUtil;

@SpringBootTest(classes = GdtAutoApplication.class)
@ActiveProfiles("test")
public class AdAutoTest {
    
    @Autowired
    private AdPlanService adPlanService;
    @Autowired
    private AdAutoConfService adAutoConfService;
    @Autowired
    private AdPlanAutoExecutor adPlanAutoExecutor;
    @Autowired
    private RobotUtil robotUtil;
    @Autowired
    private AdPlanCreativeService adPlanCreativeService;

    @Test
    public void testCheckRule() {
        AdAutoConf conf = adAutoConfService.getById(11);
        adPlanAutoExecutor.checkRule(55L, conf, JSON.parseArray(conf.getRules(), AutoPlanRule.class));
    }

    @Test
    public void testCompareTO() {
        AdPlan plan = adPlanService.lambdaQuery()
            .eq(AdPlan::getAdgroupId, 87878621549L).one();
        AdAutoConf conf = adAutoConfService.getById(7L);
        List<AutoPlanRule> rules = JSON.parseArray(conf.getRules(), AutoPlanRule.class);
        for (AutoPlanRule rule : rules) {
            if (adPlanAutoExecutor.matchRule(plan, rule, 3)) {
                System.out.println("匹配成功: " + JSON.toJSON(rule));
            }
        }
    }

    @Test
    public void testRobotUtil() {
        List<AdPlanCreative> creatives = adPlanCreativeService.lambdaQuery()
            .in(AdPlanCreative::getId, List.of(45,46,47,48)).list();
            creatives.forEach(c -> c.setFailReason("不考虑消耗 ROI:0.1 < 阈值:0.2"));
            List<String> msgs = new ArrayList<>(creatives.size());
                String msgFormat =  "测试组" + "账户组下%d账户的%d创意 %s 已经被自动暂停链接如下: [点击](%s)";
                String urlFormat = "https://ad.qq.com/atlas/%d/admanage/index?tab=dynamic_creative&query={'operation_status':[],'created_time':'2-89','fuzzy_name':'%d'}";
                for (AdPlanCreative creative : creatives) {
                    String targetUrl = String.format(urlFormat, creative.getAccountId(), creative.getCreativeId());
                    String msg = String.format(msgFormat, creative.getAccountId(), creative.getCreativeId(), creative.getFailReason(), targetUrl);
                    msgs.add(msg);
                }
                robotUtil.pushMsg(msgs);
    }



}
