package com.cyksj.service.order.post.impl;

import cn.hutool.http.HttpUtil;
import com.cyksj.common.util.IoKit;
import com.cyksj.common.util.J11HttpC;
import com.cyksj.common.util.Jsons;
import com.cyksj.model.request.OeCallbackInfo;
import com.cyksj.service.order.post.AbstractPostDataService;
import com.cyksj.service.order.post.PostDataFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author zwhui
 * @date 2022/10/18 11:32
 */
@Slf4j
@Service("OePostDataService")
@RequiredArgsConstructor
public class OEPostDataService extends AbstractPostDataService {


    @Override
    public void postData(Long orderId, String callback, String evenType) throws Exception {

        log.info("巨量api数据回传：{}", orderId);

        String url = "https://analytics.oceanengine.com/api/v2/conversion";
        if (callback.contains("clickid=")) {
            Map<String, String> paramMap = HttpUtil.decodeParamMap(callback, StandardCharsets.UTF_8);
            callback = paramMap.get("clickid");
        }
        OeCallbackInfo oeCallbackInfo = new OeCallbackInfo().setEvent_type(evenType).setContext(new OeCallbackInfo.Context().setAd(new OeCallbackInfo.Context.Ad().setCallback(callback))).setTimestamp(System.currentTimeMillis());

        // 带参GET请求
        HttpResponse<byte[]> res =
                J11HttpC.custom()
                        .ofPost()
                        .url(url)
                        .headers(J11HttpC.ReqType.raw_json)
                        .body(HttpRequest.BodyPublishers.ofString(Jsons.toJson(oeCallbackInfo), IoKit.Charsets.UTF_8.getCharset()))
                        .send(HttpResponse.BodyHandlers.ofByteArray());

        Map<String, Object> map = Jsons.parseObject(res.body(), Map.class);
        log.info("巨量api数据回传:{}", map);

        if ("0".equals(String.valueOf(map.get("code"))) ) {
            log.info("回传成功！orderId:{}", orderId);
            orderPostMapper.updateStatus(orderId);

            //回传即删除 用户获客助手广告平台 clickId
            TASK_EXECUTOR.execute(()->{
                delCorpCustomerAcquistionClickIdByOrderId(orderId);
            });
        }

    }

    @PostConstruct
    public void init() {
        PostDataFactory.add(this, this.getClass().getSimpleName());

    }
}
