package com.moka.gdtauto.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moka.gdtauto.client.TencentAdsApiClientFactory;
import com.moka.gdtauto.entity.TencentConversion;
import com.moka.gdtauto.mapper.TencentConversionMapper;
import com.moka.gdtauto.service.TencentConversionService;
import com.tencent.ads.model.v3.*;
import com.tencent.ads.v3.TencentAds;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 腾讯广告转化归因服务实现类
 * 
 * @author moka
 * @since 2026-02-06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TencentConversionServiceImpl extends ServiceImpl<TencentConversionMapper, TencentConversion> implements TencentConversionService {

    private final TencentAdsApiClientFactory clientFactory;
    private final TencentConversionMapper tencentConversionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncConversions(String jobNumber, Long orgAccountId, Long accountId) {
        log.info("开始同步转化归因数据，jobNumber={}, orgAccountId={}, accountId={}", jobNumber, orgAccountId, accountId);
        
        try {
            TencentAds tencentAds = clientFactory.getTencentAdsWithoutUserToken(jobNumber, orgAccountId);
            tencentAds.setDebug(true);
            
            // 构建过滤条件：短剧用户增长注册变现
            List<FilteringStruct> filtering = buildFiltering();
            
            int syncCount = 0;
            Long page = 1L;
            Long pageSize = 100L;
            boolean hasMore = true;
            
            while (hasMore) {
                log.info("获取转化归因数据，page={}, pageSize={}", page, pageSize);
                
                try {
                    // 调用API查询转化归因
                    ConversionsGetResponseData response = tencentAds.conversions()
                        .conversionsGet(
                            accountId,
                            filtering,
                            page,
                            pageSize,
                            List.of("conversion_id", "conversion_name")  // 只获取需要的字段
                        );
                    
                    if (response != null && response.getList() != null && !response.getList().isEmpty()) {
                        log.info("获取到{}条转化归因数据", response.getList().size());
                        
                        // 批量保存到数据库
                        List<TencentConversion> conversions = new ArrayList<>();
                        for (ConversionsGetListStruct item : response.getList()) {
                            TencentConversion conversion = new TencentConversion();
                            conversion.setConversionId(item.getConversionId());
                            conversion.setConversionName(item.getConversionName());
                            conversions.add(conversion);
                        }
                        
                        // 使用 saveOrUpdateBatch 批量保存或更新
                        tencentConversionMapper.batchInsertOrUpdate(conversions);
                        syncCount += conversions.size();
                        
                        // 判断是否还有下一页
                        if (response.getPageInfo() != null) {
                            Long totalNumber = response.getPageInfo().getTotalNumber();
                            Long totalPage = response.getPageInfo().getTotalPage();
                            log.info("当前页={}, 总页数={}, 总记录数={}", page, totalPage, totalNumber);
                            
                            if (page < totalPage) {
                                page++;
                            } else {
                                hasMore = false;
                                log.info("已到最后一页，停止翻页");
                            }
                        } else {
                            hasMore = false;
                            log.warn("响应中没有page_info，停止翻页");
                        }
                    } else {
                        hasMore = false;
                        log.info("本次请求未获取到数据，停止翻页");
                    }
                    
                } catch (Exception e) {
                    log.error("调用API获取转化归因失败，accountId={}, page={}", accountId, page, e);
                    throw new RuntimeException("调用API获取转化归因失败: " + e.getMessage(), e);
                }
            }
            
            log.info("同步转化归因数据完成，orgAccountId={}, accountId={}, 同步数量={}", orgAccountId, accountId, syncCount);
            return syncCount;
            
        } catch (Exception e) {
            log.error("同步转化归因数据失败，orgAccountId={}, accountId={}", orgAccountId, accountId, e);
            throw new RuntimeException("同步转化归因数据失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 构建过滤条件：短剧用户增长注册变现
     */
    private List<FilteringStruct> buildFiltering() {
        List<FilteringStruct> filtering = new ArrayList<>();
        
        // 过滤条件1：优化目标 = OPTIMIZATIONGOAL_APP_REGISTER
        FilteringStruct filter1 = new FilteringStruct();
        filter1.setField("optimization_goal");
        filter1.setOperator(FilterOperator.EQUALS);
        filter1.setValues(List.of("OPTIMIZATIONGOAL_APP_REGISTER"));
        filtering.add(filter1);
        
        // 过滤条件2：营销目标 = MARKETING_GOAL_USER_GROWTH
        FilteringStruct filter2 = new FilteringStruct();
        filter2.setField("marketing_goal");
        filter2.setOperator(FilterOperator.EQUALS);
        filter2.setValues(List.of("MARKETING_GOAL_USER_GROWTH"));
        filtering.add(filter2);
        
        // 过滤条件3：营销资产类型 = MARKETING_TARGET_TYPE_SHORT_DRAMA
        FilteringStruct filter3 = new FilteringStruct();
        filter3.setField("marketing_target_type");
        filter3.setOperator(FilterOperator.EQUALS);
        filter3.setValues(List.of("MARKETING_TARGET_TYPE_SHORT_DRAMA"));
        filtering.add(filter3);
        
        return filtering;
    }
}
