package org.jeecg.modules.demo.adsaccount.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.modules.demo.adsaccount.entity.AdsAccount;
import org.jeecg.modules.demo.adsaccount.entity.TimezoneID;
import org.jeecg.modules.demo.adsaccount.mapper.AdsAccountMapper;
import org.jeecg.modules.demo.adsaccount.service.IAdsAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Description: 广告账户管理
 * @Author: jeecg-boot
 * @Date:   2024-09-20
 * @Version: V1.0
 */
@Service
public class AdsAccountServiceImpl extends ServiceImpl<AdsAccountMapper, AdsAccount> implements IAdsAccountService {


    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<AdsAccount> getPendingReviewStatusAdsAccounts(String reviewStatus) {
        // 使用 MyBatis-Plus 的查询方式，通过 reviewStatus 字段查找为 pending 的广告账户
        return baseMapper.selectList(new QueryWrapper<AdsAccount>().eq("review_status", reviewStatus));
    }

    @Override
    public String createGoogleAdsCustomer(AdsAccount adsAccount){
        String accountName = adsAccount.getAccountName();
        AdsAccount.AChannel accountChannel = AdsAccount.AChannel.Google;
        String currencyCode = adsAccount.getCurrencyCode();

        String timezoneId =  adsAccount.getAccountId().replaceAll("\\d+", "");
        TimezoneID timezone = TimezoneID.valueOfId(timezoneId);

        String url = "http://127.0.0.1:8090/api/ads_accounts/createAdsAccount?accountName=" + accountName
                + "&accountChannel=" + accountChannel
                + "&currencyCode=" + currencyCode
                + "&timezone=" + timezoneId;

//        RequestConfig requestConfig = RequestConfig.custom()
//					 .setSocketTimeout(5000)  // 设置读取超时时间
//					 .setConnectTimeout(5000) // 设置连接超时时间
//					 .build();
//
//			 HttpClient httpClient = HttpClients.custom()
//					 .setDefaultRequestConfig(requestConfig)
//					 .build();
        // 使用 HttpComponentsClientHttpRequestFactory 包装 HttpClient
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

        RestTemplate restTemplate = new RestTemplate(factory);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, null, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            String accountId = response.getBody();
            adsAccount.setAccountId(accountId);
            return accountId;
        } else {
            return "false";
        }
    }

}
