package com.moka.gdtauto.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moka.gdtauto.client.TencentAdsApiClientFactory;
import com.moka.gdtauto.entity.TencentAccount;
import com.moka.gdtauto.mapper.TencentAccountMapper;
import com.moka.gdtauto.service.TencentAccountService;
import com.tencent.ads.model.v3.OrganizationAccountRelationGetResponseData;
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 org.springframework.util.CollectionUtils;

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

/**
 * 腾讯广告账户服务实现类
 * 
 * @author moka
 * @since 2026-02-06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TencentAccountServiceImpl extends ServiceImpl<TencentAccountMapper, TencentAccount> implements TencentAccountService {

    private final TencentAccountMapper tencentAccountMapper;
    private final TencentAdsApiClientFactory clientFactory;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncAccountsByOrgAccountId(Long orgAccountId, String jobNumber) {
        log.info("开始同步组织账户下的广告账户信息，orgAccountId={}, jobNumber={}", orgAccountId, jobNumber);
        
        try {
            // 获取TencentAds实例
            TencentAds tencentAds = clientFactory.getTencentAdsWithoutUserToken(jobNumber, orgAccountId);
            tencentAds.setDebug(true);
            // 调用API获取组织账户下的广告账户列表
            List<TencentAccount> accounts = new ArrayList<>();
            Long pageSize = 100L;
            Long cursor = null;  // 游标，第一次请求时为null
            boolean hasMore = true;
            
            while (hasMore) {
                log.info("获取数据，pageSize={}, cursor={}", pageSize, cursor);
                
                // 调用SDK的organizationAccountRelation().organizationAccountRelationGet()方法
                try {
                    OrganizationAccountRelationGetResponseData response = tencentAds.organizationAccountRelation()
                        .organizationAccountRelationGet(
                            "PAGINATION_MODE_CURSOR",  // paginationMode 使用游标翻页模式
                            null,  // accountId
                            null,  // advertiserType
                            null,  // businessUnitId
                            cursor,  // cursor 游标值
                            null,  // page 游标模式下不需要page参数
                            pageSize,
                            null   // fields
                        );
                    
                    if (response != null && response.getList() != null && !response.getList().isEmpty()) {
                        log.info("获取到{}条账户数据", response.getList().size());
                        
                        // 转换为TencentAccount实体
                        for (var item : response.getList()) {
                            // 将item转换为JSON并再解析，以处理字段名问题
                            String itemJson = JSON.toJSONString(item);
                            com.alibaba.fastjson2.JSONObject itemObj = JSON.parseObject(itemJson);
                            
                            TencentAccount account = new TencentAccount();
                            account.setOrgAccountId(orgAccountId);
                            account.setJobNumber(jobNumber);
                            account.setAccountId(itemObj.getLong("account_id"));
                            account.setCorporationName(itemObj.getString("corporation_name"));
                            account.setIsBid(itemObj.getBoolean("is_bid"));
                            account.setIsMp(itemObj.getBoolean("is_mp"));
                            account.setIsAdx(itemObj.getBoolean("is_adx"));
                            
                            // 处理comment_list
                            if (item.getCommentList() != null && !item.getCommentList().isEmpty()) {
                                // 将comment_list转换为JSON字符串存储
                                account.setCommentList(JSON.toJSONString(item.getCommentList()));
                                
                                // 取第一个元素的user_id和comment
                                var firstComment = item.getCommentList().get(0);
                                if (firstComment != null) {
                                    account.setCommentUserId(firstComment.getUserId());
                                    account.setComment(firstComment.getComment());
                                }
                            }
                            
                            accounts.add(account);
                        }
                        
                        // 每次响应后立即批量插入或更新
                        if (!accounts.isEmpty()) {
                            int batchCount = batchInsertOrUpdate(accounts);
                            log.info("本次响应插入或更新{}条账户数据", batchCount);
                            accounts.clear(); // 清空列表，准备下一批
                        }
                        
                        // 判断是否还有下一页（使用游标翻页信息）
                        if (response.getCursorPageInfo() != null) {
                            // 将CursorPageInfo转为JSON并解析，以处理字段名问题
                            String cursorPageInfoJson = JSON.toJSONString(response.getCursorPageInfo());
                            com.alibaba.fastjson2.JSONObject cursorPageInfoObj = JSON.parseObject(cursorPageInfoJson);
                            
                            Boolean hasMoreData = cursorPageInfoObj.getBoolean("has_more");
                            hasMore = hasMoreData != null && hasMoreData;
                            if (hasMore) {
                                cursor = cursorPageInfoObj.getLong("cursor");
                                log.info("还有更多数据，下次游标={}", cursor);
                            } else {
                                log.info("没有更多数据了，总共获取{}条", accounts.size());
                            }
                        } else {
                            hasMore = false;
                            log.warn("响应中没有cursor_page_info，停止翻页");
                        }
                    } else {
                        hasMore = false;
                        log.info("本次请求未获取到数据，停止翻页");
                    }
                    
                } catch (Exception e) {
                    log.error("调用API获取组织账户关系失败，orgAccountId={}, cursor={}", orgAccountId, cursor, e);
                    throw new RuntimeException("调用API获取组织账户关系失败: " + e.getMessage(), e);
                }
            }
            
            // 最后返回总数
            log.info("同步组织账户下的广告账户信息完成，orgAccountId={}", orgAccountId);
            // 查询最终同步的总数
            LambdaQueryWrapper<TencentAccount> countWrapper = new LambdaQueryWrapper<>();
            countWrapper.eq(TencentAccount::getOrgAccountId, orgAccountId)
                       .eq(TencentAccount::getDeleted, 0);
            long totalCount = this.count(countWrapper);
            log.info("最终同步总数={}", totalCount);
            return (int) totalCount;
            
        } catch (Exception e) {
            log.error("同步组织账户下的广告账户信息失败，orgAccountId={}", orgAccountId, e);
            throw new RuntimeException("同步组织账户下的广告账户信息失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchInsertOrUpdate(List<TencentAccount> accounts) {
        if (CollectionUtils.isEmpty(accounts)) {
            log.warn("账户列表为空，无需批量插入或更新");
            return 0;
        }
        
        log.info("开始批量插入或更新账户信息，数量={}", accounts.size());
        int count = tencentAccountMapper.batchInsertOrUpdate(accounts);
        log.info("批量插入或更新账户信息完成，影响行数={}", count);
        
        return count;
    }
}
