package com.fshark.overseas.advert.sink;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fshark.overseas.advert.modle.AppsFlyerEvent;
import com.fshark.overseas.advert.modle.EventTypeEnum;
import com.fshark.overseas.advert.modle.TiktokModle;
import com.google.gson.Gson;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

public class TiktokSink extends RichSinkFunction<AppsFlyerEvent> {

    private Gson gson;

    private static String ACCESS_TOKEN = "0e76c1138387d6ee7805eca2334bba89ad855557";
    private static Long TIKTOK_APPID = 7174239434366320641L;

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        gson = new Gson();
    }

    public void sendReport(TiktokModle tiktokModle) throws JsonProcessingException {
        String body = gson.toJson(tiktokModle);
        String result = HttpRequest.post("https://business-api.tiktok.com/open_api/v1.2/app/track/")
                .header(Header.CONTENT_TYPE, "application/json")
                .header("Access-Token", ACCESS_TOKEN)
                .body(body)
                .timeout(20000) //超时，毫秒
                .execute().body();
//        System.out.println(body);
//        System.out.println(result);
    }

    @Override
    public void invoke(AppsFlyerEvent value, Context context) throws Exception {
        if (!value.getGame_id().equals("com.chaosportal.shark") || !"pangle".equals(value.getMedia_source())) {
            return;
        }

        if (EventTypeEnum.installEvent(value) || EventTypeEnum.orderEvent(value)) {
            String event_name = "";
            if (EventTypeEnum.installEvent(value)) {
                event_name = "InstallApp";
            }
            TiktokModle tiktokModle = new TiktokModle();
            tiktokModle.setTiktokAppId(TIKTOK_APPID);
            tiktokModle.setEvent(event_name);
            tiktokModle.setTimestamp(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'hh:mm:ss'Z'").format(value.getEvent_time().atOffset(ZoneOffset.UTC)));
            TiktokModle.ContextDTO contextDTO = new TiktokModle.ContextDTO();
            contextDTO.setIp(value.getIp());
            contextDTO.setUserAgent(value.getUser_agent());
            contextDTO.setOriginUrl(value.getOriginal_url());
            TiktokModle.ContextDTO.AppDTO appDTO = new TiktokModle.ContextDTO.AppDTO();
            appDTO.setId(value.getApp_id());
            contextDTO.setApp(appDTO);
            TiktokModle.ContextDTO.DeviceDTO deviceDTO = new TiktokModle.ContextDTO.DeviceDTO();
            deviceDTO.setPlatform(value.getPlatform());
            deviceDTO.setIdfa(value.getIdfa());
            deviceDTO.setIdfv(value.getIdfv());
            contextDTO.setDevice(deviceDTO);
            TiktokModle.ContextDTO.AdDTO adDTO = new TiktokModle.ContextDTO.AdDTO();
            adDTO.setPlacement("Pangle");
            if (!"id_matching".equals(value.getMatch_type())) {
                adDTO.setMatchType("probabilistic");
            } else {
                adDTO.setMatchType(value.getMatch_type());
            }
            adDTO.setCampaignId(Long.valueOf(value.getCampaign_id()));
            adDTO.setAdId(Long.valueOf(value.getAd_set_id()));
            adDTO.setCreativeId(Long.valueOf(value.getAd_id()));
            adDTO.setRetargeting(value.getIs_retargeting());
            adDTO.setAttributed(true);
            adDTO.setAttributionType(value.getAttributed_touch_type() + "_through");
            adDTO.setAttributionProvider("mmp");
            contextDTO.setAd(adDTO);
            tiktokModle.setContext(contextDTO);
            if (EventTypeEnum.orderEvent(value)) {
                JSONObject json = JSON.parseObject(value.getEvent_value());
                String currency = json.getString("af_currency");
                Integer revenue = Integer.valueOf(json.getString("af_revenue"));
                TiktokModle.PropertiesDTO propertiesDTO = new TiktokModle.PropertiesDTO();
                propertiesDTO.setCurrency(currency);
                propertiesDTO.setValue(revenue);
                ArrayList<TiktokModle.PropertiesDTO.ContentsDTO> contentsDTOS = new ArrayList<>();
                TiktokModle.PropertiesDTO.ContentsDTO contentsDTOS1 = new TiktokModle.PropertiesDTO.ContentsDTO();
                contentsDTOS1.setPrice(revenue);
                contentsDTOS1.setQuantity(1);
                contentsDTOS.add(contentsDTOS1);
                propertiesDTO.setContents(contentsDTOS);
                tiktokModle.setProperties(propertiesDTO);
            }

            sendReport(tiktokModle);
        }
    }

}
