package com.fs.newAdv.integration.client.advertiser;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.fs.newAdv.domain.PromotionAccount;
import com.fs.newAdv.domain.SiteStatistics;
import com.fs.newAdv.enums.AdvertiserTypeEnum;
import com.fs.newAdv.integration.client.AbstractApiClient;
import com.fs.common.constant.SystemConstant;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.util.crypto.SHA1;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 腾讯广点通API客户端
 * 用于调用巨量引擎的API接口（转化回传等）
 *
 * @author zhangqin
 * @date 2025-11-03
 * @see <a href="https://adsfs.heytapimage.com/res/v2/default/market/doc/H5%E6%95%B0%E6%8D%AE%E5%9B%9E%E4%BC%A0%E8%BD%AC%E5%8C%96Api%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A33_0_3.pdf">巨量引擎API文档</a>
 */
@Slf4j
@Component
public class OPPOApiClient extends AbstractApiClient {

    /**
     * 巨量引擎转化回传API地址
     */
    private static final String CONVERSION_API_URL = "https://sapi.ads.oppomobile.com/v1/clue/sendData";
    private static final String SALT = "e0u6fnlag06lc3pl";

    /**
     * 回传转化数据
     *
     * @param conversionData 转化数据
     * @return 是否成功
     */
    @Override
    public boolean reportConversion(Map<String, Object> conversionData) {
        return  executeWithLog(AdvertiserTypeEnum.OPPO, CONVERSION_API_URL, conversionData, () -> {
            // 构建请求参数
            Map<String, Object> requestBody = buildConversionParams(conversionData);
            Long timestamp = (Long) conversionData.get("timestamp");
            String ownerId = (String) conversionData.get("adAccountId");
            String appId = (String) conversionData.get("appId");
            String appKey = (String) conversionData.get("appSecret");
            String sign = Hashing.sha1().hashString(appId + appKey + timestamp, Charset.defaultCharset()).toString();
            String token = BaseEncoding.base64().encode((ownerId + "," + appId + "," + timestamp + "," + sign).getBytes());
            // 发送HTTP请求
            return HttpRequest.post(CONVERSION_API_URL)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + token)
                    .body(JSONUtil.toJsonStr(requestBody))
                    .timeout(SystemConstant.API_TIMEOUT)
                    .execute();
        });
    }

    /**
     * 构建转化回传参数
     *
     * @param conversionData 转化数据
     * @return 请求参数
     */
    protected Map<String, Object> buildConversionParams(Map<String, Object> conversionData) {
        Map<String, Object> params = new HashMap<>();

        // 落地页Id:投放广告到投放
        params.put("pageId", conversionData.get("pageId"));
        // 广告主id：对应广告主自提供
        params.put("ownerId", conversionData.get("adAccountId"));
        // 用户IP：广告主收集
        params.put("ip", "127.0.0.1");
        // traceId：播放时追加在url上
        params.put("tid", conversionData.get("traceId"));
        // 流量号：播放时追加在URL上
        params.put("lbid ", conversionData.get("lbid"));
        // 事件
        params.put("transformType", conversionData.get("eventType"));
        return params;
    }


    @Override
    public AdvertiserTypeEnum getAdvertiserType() {
        return AdvertiserTypeEnum.OPPO;
    }

    @Override
    public SiteStatistics getDataReport(PromotionAccount account,String ideaId,String startDate,String endDate) {
        return null;
    }
}

