package com.cyksj.service.oceanengine.impl;

import cn.hutool.json.JSONObject;
import com.cyksj.common.util.IoKit;
import com.cyksj.common.util.J11HttpC;
import com.cyksj.common.util.Jsons;
import com.cyksj.common.util.StringUtil;
import com.cyksj.redis.RedisService;
import com.cyksj.service.oceanengine.OceanengineService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.http.HttpResponse;
import java.util.Set;

/**
 * @author chan
 * @date 2023/10/18 14:14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OceanengineServiceImpl implements OceanengineService {

    private final RedisService redisService;

    @Override
    public void monitorAddCorpPost() {
        Set<Object> callbackSet = redisService.sGet(RedisService.key.OCEANENGINE_MONITOR_CALLBCAK.getName());
        if (callbackSet.size() > 0) {
            String callback = StringUtil.getString(callbackSet.stream().findFirst().get());
            JSONObject params = new JSONObject();
            params.putOpt("event_type", "active_pay");
            JSONObject context = new JSONObject();
            JSONObject ad = new JSONObject();
            ad.putOpt("callback", StringUtil.getString(callback));
            context.putOpt("ad", ad);
            params.putOpt("context", context);
            params.putOpt("timestamp", System.currentTimeMillis());

            try {
                HttpResponse<String> res =
                        J11HttpC.custom()
                                .ofPost()
                                .url("https://analytics.oceanengine.com/api/v2/conversion")
                                .headers(J11HttpC.ReqType.raw_json)
                                .body(java.net.http.HttpRequest.BodyPublishers.ofString(params.toString(), IoKit.Charsets.UTF_8.getCharset()))
                                .send(HttpResponse.BodyHandlers.ofString());
                log.info("巨量回传 res:{}",res.body());
                redisService.setRemove(RedisService.key.OCEANENGINE_MONITOR_CALLBCAK.getName(), callback);
            } catch (Exception e) {
                log.error("巨量回传 error:{}",StringUtil.getErrorMsg(e));
            }
        }
    }
}