package com.gh.common.util;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.gh.gamecenter.BuildConfig;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.entity.CommunityEntity;
import com.gh.gamecenter.common.entity.ExposureEntity;
import com.gh.gamecenter.common.exposure.ExposureSource;
import com.gh.gamecenter.common.exposure.meta.Meta;
import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.gh.gamecenter.common.loghub.LoghubUtils;
import com.gh.gamecenter.common.loghub.SimpleLogContainerEntity;
import com.gh.gamecenter.common.utils.DeviceUtils;
import com.gh.gamecenter.core.utils.GsonUtils;
import com.gh.gamecenter.entity.SpecialColumn;
import com.gh.gamecenter.entity.StartupAdEntity;
import com.gh.gamecenter.feature.entity.DetectionObjectEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.PackageDialogEntity;
import com.gh.gamecenter.feature.entity.Questions;
import com.gh.gamecenter.feature.exposure.ExposureEvent;
import com.gh.gamecenter.login.user.UserManager;
import com.halo.assistant.HaloApp;
import com.lightgame.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by khy on 2/01/18.
 */
public class LogUtils {

    private static final String KEY_EVENT = "event";
    private static final String KEY_META = "meta";
    private static final String KEY_TIMESTAMP = "timestamp";
    private static final String KEY_ENTRANCE = "entrance";
    private static final String KEY_PAY_LOAD = "payload";
    private static final String KEY_GAME_NAME = "game_name";
    private static final String KEY_GAME_ID = "game_id";
    private static final String LOG_STORE_EVENT = "event";

    public static void logVideoStreamingUpload(String action, String entrance, String entranceDetail, String videoId) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();

        try {
            object.put(KEY_EVENT, "UPLOAD_VIDEO_STEAMING");
            object.put("action", action);
            payloadObject.put(KEY_ENTRANCE, entrance);
            payloadObject.put("entrance_detail", entranceDetail);
            payloadObject.put("video_id", videoId);
            object.put(KEY_PAY_LOAD, payloadObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        uploadVideoStreaming(object);
    }

    public static void uploadCommunityArticle(String tracers, String articleId, String articleTitle, int readTime, CommunityEntity community, SpecialColumn specialColumn) {
        JSONObject object = new JSONObject();
        try {
            object.put("subject", "community_article");
            object.put("community_id", community.getId());
            object.put("community_name", community.getName());
            object.put("article_id", articleId);
            object.put("article_name", articleTitle);
            object.put("tracers", tracers);
            object.put("read", readTime);
            JSONObject columnObject = new JSONObject();
            if (specialColumn != null) {
                columnObject.put("type", specialColumn.getType());
                columnObject.put("name", specialColumn.getName());
                columnObject.put("tab", specialColumn.getTab());
            } else {
                columnObject.put("type", "");
                columnObject.put("name", "");
                columnObject.put("tab", "");
            }
            object.put("special_column", columnObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToCommunity(object);
    }

    public static void uploadDevice(LunchType launchType) {
        JSONObject object = new JSONObject();
        Application application = HaloApp.getInstance().getApplication();
        try {
            object.put("subject", "halo_device");
            object.put("launch_time", Utils.getTime(application));
            object.put("launch_type", launchType.name());
            object.put("manufacture", Build.MANUFACTURER);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToCommunity(object, true);
    }

    public static void uploadAnswerReadTime(String tracers, int readTime, String answerId, Questions questions, String communityId, String CommunityName, SpecialColumn specialColumn) {
        JSONObject object = new JSONObject();
        try {
            object.put("subject", "answer");
            object.put("community_id", communityId);
            object.put("community_name", CommunityName);
            object.put("question_id", questions.getId());
            object.put("question_name", questions.getTitle());
            object.put("tracers", tracers);
            object.put("answer_id", answerId);
            object.put("read", readTime);
            JSONObject columnObject = new JSONObject();
            if (specialColumn != null) {
                columnObject.put("type", specialColumn.getType());
                columnObject.put("name", specialColumn.getName());
                columnObject.put("tab", specialColumn.getTab());
            } else {
                columnObject.put("type", "");
                columnObject.put("name", "");
                columnObject.put("tab", "");
            }
            object.put("special_column", columnObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToCommunity(object);
    }

    public static void uploadQuestionReadTime(String tracers, int readTime, Questions questions, String communityId, String communityName, SpecialColumn specialColumn) {
        JSONObject object = new JSONObject();
        try {
            object.put("subject", "question");
            object.put("community_id", communityId);
            object.put("community_name", communityName);
            object.put("question_id", questions.getId());
            object.put("question_name", questions.getTitle());
            object.put("tracers", tracers);
            object.put("read", readTime);
            JSONObject columnObject = new JSONObject();
            if (specialColumn != null) {
                columnObject.put("type", specialColumn.getType());
                columnObject.put("name", specialColumn.getName());
                columnObject.put("tab", specialColumn.getTab());
            } else {
                columnObject.put("type", "");
                columnObject.put("name", "");
                columnObject.put("tab", "");
            }
            object.put("special_column", columnObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToCommunity(object);
    }

    public static void login(String loginStep, String loginType, String entrance) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_ENTRANCE, entrance);
            object.put("subject", "login");
            object.put("step", loginStep);
            object.put("login_type", loginType);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToCommunity(object, true);
    }

    public static void qaAccess(String access, CommunityEntity communityEntity) {
        JSONObject object = new JSONObject();
        try {
            object.put("subject", "qa_access");
            object.put("access", access);
            object.put("community_id", communityEntity.getId());
            object.put("community_name", communityEntity.getName());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToCommunity(object);
    }

    public static void logReservation(GameEntity gameEntity, @Nullable ExposureEvent event) {
        JSONObject object = new JSONObject();
        List<ExposureSource> exposureSourceList;

        if (event == null) {
            exposureSourceList = new ArrayList<>();
            exposureSourceList.add(new ExposureSource("其它", ""));
        } else {
            exposureSourceList = event.getSource();
        }

        try {
            object.put("source", GsonUtils.toJson(exposureSourceList));
            object.put(KEY_GAME_NAME, gameEntity.getName());
            object.put(KEY_GAME_ID, gameEntity.getId());
            object.put("game_platform", gameEntity.getPlatform());
            if (event != null) {
                object.put("sequence", event.getPayload().getSequence());
                object.put("outer_sequence", event.getPayload().getOuterSequence());
            }
            object.put("download_open", gameEntity.getDownloadOffStatus() == null ? "true" : "false");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadToReservation(object);
    }

    private static void uploadToCommunity(JSONObject object) {
        uploadToCommunity(object, false);
    }

    private static void uploadToCommunity(JSONObject object, boolean forcedUpload) {
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }

        Context context = HaloApp.getInstance().getApplication();
        try {
            object.put("version", PackageUtils.getGhVersionName());
            object.put("channel", HaloApp.getInstance().getChannel());
            object.put("dia", MetaUtil.getBase64EncodedAndroidId());
            object.put("time", Utils.getTime(context));
            object.put("network", DeviceUtils.getNetwork(context));
            object.put("user_id", UserManager.getInstance().getUserId());
            object.put("device_system", android.os.Build.VERSION.RELEASE);
            object.put("device_model", android.os.Build.MODEL);
            object.put("jnfj", MetaUtil.getBase64EncodedIMEI());
            object.put("G_ID", UserManager.getInstance().getDeviceId());
            object.put("oaid", HaloApp.getInstance().getOAID());
            object.put("rom", MetaUtil.getMeta().getRom());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 暂时除了曝光外的数据都是扔到 community 这个库的，要是不是这个这个库的话这里要改一下
        LoghubUtils.log(object, "community", forcedUpload);
    }

    /**
     * 上传数据到“预约”的 logStore
     */
    private static void uploadToReservation(JSONObject object) {
        Context context = HaloApp.getInstance().getApplication();
        try {
            object.put(KEY_EVENT, "appointment");
            object.put("version", PackageUtils.getGhVersionName());
            object.put("channel", HaloApp.getInstance().getChannel());
            object.put("dia", MetaUtil.getBase64EncodedAndroidId());
            object.put("oaid", MetaUtil.INSTANCE.getMeta().getOaid());
            object.put("rom", MetaUtil.getMeta().getRom());
            object.put("time", Utils.getTime(context));
            object.put("network", DeviceUtils.getNetwork(context));
            object.put("user_id", UserManager.getInstance().getUserId());
            object.put("device_system", android.os.Build.VERSION.RELEASE);
            object.put("device_model", android.os.Build.MODEL);
            object.put("jnfj", MetaUtil.getBase64EncodedIMEI());
            object.put("G_ID", UserManager.getInstance().getDeviceId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        LoghubUtils.log(object, "appointment", false);
    }

    private static void uploadVideoStreaming(JSONObject object) {
        Meta meta = MetaUtil.INSTANCE.getMeta();
        JSONObject metaObject = new JSONObject();
        try {
            metaObject.put("dia", MetaUtil.getBase64EncodedAndroidId());
            metaObject.put("android_sdk", meta.getAndroid_sdk());
            metaObject.put("android_version", meta.getAndroid_version());
            metaObject.put("appVersion", meta.getAppVersion());
            metaObject.put("channel", meta.getChannel());
            metaObject.put("gid", meta.getGid());
            metaObject.put("oaid", meta.getOaid());
            metaObject.put("rom", MetaUtil.getMeta().getRom());
            metaObject.put("jnfj", MetaUtil.getBase64EncodedIMEI());
            metaObject.put("mac", meta.getMac());
            metaObject.put("manufacturer", meta.getManufacturer());
            metaObject.put("model", meta.getModel());
            metaObject.put("network", meta.getNetwork());
            metaObject.put("os", meta.getOs());
            metaObject.put("userId", meta.getUserId());

            object.put(KEY_META, metaObject);
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }

        LoghubUtils.log(object, "video_streaming", false);
    }

    public static void uploadVideoStreamingEnter(String entrance, String entranceDetail, String videoId, String streamingId) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();

        try {
            object.put(KEY_EVENT, "ENTERING_VIDEO_STEAMING");
            payloadObject.put(KEY_ENTRANCE, entrance);
            if (!TextUtils.isEmpty(entranceDetail)) {
                payloadObject.put("entrance_detail", entranceDetail);
            }
            payloadObject.put("video_id", videoId);
            payloadObject.put("streaming_id", streamingId);
            object.put(KEY_PAY_LOAD, payloadObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        uploadVideoStreaming(object);
    }

    public static void uploadVideoStreamingPlaying(String action, String msg, String entrance, String entranceDetail, String videoId, String streamingId, double videoSize, int videoTotalTime, int progress, String videoPlayStatus) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();

        try {
            object.put(KEY_EVENT, "VIDEO_PLAYING");
            object.put("action", action);
            if (!TextUtils.isEmpty(msg)) {
                object.put("msg", msg);
            }

            payloadObject.put(KEY_ENTRANCE, entrance);
            if (!TextUtils.isEmpty(entranceDetail)) {
                payloadObject.put("entrance_detail", entranceDetail);
            }
            payloadObject.put("video_id", videoId);
            payloadObject.put("streaming_id", streamingId);
            if (videoSize > 0) {
                payloadObject.put("video_size", videoSize);
            }
            if (videoTotalTime > 0) {
                payloadObject.put("video_total_time", videoTotalTime);
            }
            payloadObject.put("progress", progress);
            payloadObject.put("video_play_status", videoPlayStatus);

            object.put(KEY_PAY_LOAD, payloadObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        uploadVideoStreaming(object);
    }

    public static void uploadTopVideoStreamingPlaying(String action, String videoId, String videoTitle, String gameId, String gameName, String videoModel, String videoPlayStatus, double videoSize, int videoTotalTime, int videoPlayTs, int progress) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();
        try {
            object.put(KEY_EVENT, "TOP_VIDEO_PLAYING");
            object.put("action", action);

            payloadObject.put("video_mode", videoModel);//视频播放方式 ["自动播放"/"点击播放"/"全屏播放"]
            payloadObject.put("video_id", videoId);
            payloadObject.put("video_title", videoTitle);
            payloadObject.put(KEY_GAME_ID, gameId);
            payloadObject.put(KEY_GAME_NAME, gameName);
            payloadObject.put("video_size", videoSize);
            payloadObject.put("video_total_time", videoTotalTime);
            payloadObject.put("progress", progress);
            payloadObject.put("video_play_ts", videoPlayTs);
            payloadObject.put("video_play_status", videoPlayStatus);

            object.put(KEY_PAY_LOAD, payloadObject);
            object.put(KEY_META, getMetaObject());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, "video_streaming", false);
    }

    public static void uploadHomeVideoStreamingPlaying(String action, boolean videoShade, String videoId, String videoTitle, String gameId, String gameName, double videoSize, int videoTotalTime, int videoPlayTs, int progress) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();
        try {
            object.put(KEY_EVENT, "HOME_VIDEO_PLAYING");
            object.put("action", action);

            payloadObject.put("video_id", videoId);
            payloadObject.put("video_title", videoTitle);
            payloadObject.put(KEY_GAME_ID, gameId);
            payloadObject.put(KEY_GAME_NAME, gameName);
            payloadObject.put("video_size", videoSize);
            payloadObject.put("video_total_time", videoTotalTime);
            payloadObject.put("progress", progress);
            payloadObject.put("video_play_ts", videoPlayTs);
            payloadObject.put("video_shade", String.valueOf(videoShade));//["true"/"false"]是否存在引导遮罩

            object.put(KEY_PAY_LOAD, payloadObject);
            object.put(KEY_META, getMetaObject());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, "video_streaming", false);
    }

    public static void uploadWelcomeDialog(String action,
                                           String dialogId,
                                           String linkId,
                                           String linkType,
                                           String linkTitle) {
        ExposureEntity payload = new ExposureEntity();
        payload.setWelcomeDialogId(dialogId);
        payload.setWelcomeDialogLinkTitle(linkTitle);

        SimpleLogContainerEntity entity = new SimpleLogContainerEntity();
        entity.setEvent("dialog");
        entity.setLinkId(linkId);
        entity.setLinkType(linkType);
        entity.setAction(action);
        entity.setMeta(MetaUtil.INSTANCE.getMeta());
        entity.setPayload(payload);
        entity.setTimestamp(System.currentTimeMillis() / 1000);

        LoghubUtils.log(GsonUtils.toJsonIgnoreNull(entity), LOG_STORE_EVENT, false);
    }

    public static void uploadLikeFromWelcomeDialog() {
        String dialogId = (String) HaloApp.get(Constants.WELCOME_DIALOG_ID, false);
        String linkTitle = (String) HaloApp.get(Constants.WELCOME_DIALOG_LINK_TITLE, false);

        ExposureEntity payload = new ExposureEntity();
        payload.setWelcomeDialogId(dialogId);
        payload.setWelcomeDialogLinkTitle(linkTitle);

        SimpleLogContainerEntity entity = new SimpleLogContainerEntity();
        entity.setEvent("like");
        entity.setMeta(MetaUtil.INSTANCE.getMeta());
        entity.setPayload(payload);
        entity.setTimestamp(System.currentTimeMillis() / 1000);

        LoghubUtils.log(GsonUtils.toJsonIgnoreNull(entity), LOG_STORE_EVENT, false);
    }

    public static void uploadCommentFromWelcomeDialog() {
        String dialogId = (String) HaloApp.get(Constants.WELCOME_DIALOG_ID, false);
        String linkTitle = (String) HaloApp.get(Constants.WELCOME_DIALOG_LINK_TITLE, false);

        ExposureEntity payload = new ExposureEntity();
        payload.setWelcomeDialogId(dialogId);
        payload.setWelcomeDialogLinkTitle(linkTitle);

        SimpleLogContainerEntity entity = new SimpleLogContainerEntity();
        entity.setEvent("comment");
        entity.setMeta(MetaUtil.INSTANCE.getMeta());
        entity.setPayload(payload);
        entity.setTimestamp(System.currentTimeMillis() / 1000);

        LoghubUtils.log(GsonUtils.toJsonIgnoreNull(entity), LOG_STORE_EVENT, false);
    }

    /**
     * 因存在部分驼峰命名的字段(appVersion和userId)，需要全部转换为下划线风格，请使用新方法{@link #getNewMetaObject}
     */
    @Deprecated
    public static JSONObject getMetaObject() {
        Meta meta = MetaUtil.INSTANCE.getMeta();
        JSONObject metaObject = new JSONObject();
        try {
            metaObject.put("dia", MetaUtil.getBase64EncodedAndroidId());
            metaObject.put("android_sdk", meta.getAndroid_sdk());
            metaObject.put("android_version", meta.getAndroid_version());
            metaObject.put("appVersion", meta.getAppVersion());
            metaObject.put("channel", meta.getChannel());
            metaObject.put("gid", meta.getGid());
            metaObject.put("jnfj", MetaUtil.getBase64EncodedIMEI());
            metaObject.put("mac", meta.getMac());
            metaObject.put("manufacturer", meta.getManufacturer());
            metaObject.put("model", meta.getModel());
            metaObject.put("network", meta.getNetwork());
            metaObject.put("os", meta.getOs());
            metaObject.put("userId", meta.getUserId());
            metaObject.put("oaid", HaloApp.getInstance().getOAID());
            metaObject.put("rom", MetaUtil.getMeta().getRom());

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return metaObject;
    }

    private static void uploadCommunity(JSONObject object) {
        try {
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, "community", false);
    }

    public static void uploadAccessToBbs(String bbsId, String location) {
        JSONObject object = new JSONObject();
        JSONObject payload = new JSONObject();
        try {
            payload.put("location", location);//关注板块/文章外所属论坛/游戏详情/文章内所属论坛
            payload.put("bbs_id", bbsId);

            object.put(KEY_EVENT, "access_to_bbs");
            object.put(KEY_PAY_LOAD, payload);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadCommunity(object);
    }

    public static void uploadAccessBbsTab() {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, "main_tab[bbs]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        uploadCommunity(object);
    }


    public static void uploadSimulatorDownload(String event, String fileName, String simulatorId, String simulatorName, String gameId, String location, String downloadType, String startTime) {
        JSONObject object = new JSONObject();
        JSONObject payload = new JSONObject();
        try {
            object.put(KEY_EVENT, event);// 取值有[开始, 完成] [simulator_download, simulator_download_complete]
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);

            payload.put("filename", fileName);// 下载模拟器文件名,每次新创建的下载任务文件名都不同,可以用来关联同一次的下载开始与完成
            payload.put("simulator_id", simulatorId);
            payload.put("simulator_name", simulatorName);
            payload.put("location", location);//启动《具体的游戏名称》/模拟器游戏/模拟器游戏-模拟器管理
            payload.put(KEY_GAME_ID, gameId);//如果是 启动《游戏名称》 这种方式, 记录这个游戏具体的游戏ID
            payload.put("download_type", downloadType);// update/download 下载类型（更新/下载）
            if (!TextUtils.isEmpty(startTime) && event.equals("simulator_download_complete")) {
                payload.put("simulator_download_timestamp", startTime);// 对应的下载开始时间
            }
            object.put(KEY_PAY_LOAD, payload);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void uploadSearchGame(String event, String location, String key, String searchType) {
        uploadSearchClick(event, location, key, searchType, "", "", 0, false, "", "");
    }

    /**
     * @param mirrorDataPosition 镜像的归类，不是镜像是为 -1 ，使用镜像 1 时为 1，使用镜像 2 时为 2
     */
    public static void uploadSearchClick(String event,
                                         String location,
                                         String key,
                                         String searchType,
                                         String gameId,
                                         String gameName,
                                         int mirrorDataPosition,
                                         Boolean isAdData,
                                         String adSpaceId,
                                         String gameAdSourceId) {
        JSONObject object = new JSONObject();
        JSONObject payload = new JSONObject();
        try {
            object.put(KEY_EVENT, event);
            object.put("location", location);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);

            payload.put("key", key); //搜索关键词
            payload.put("search_type", searchType); //搜索类型, 有四种取值 默认搜索/历史搜索/自动搜索/主动搜索
            payload.put(KEY_GAME_ID, gameId); //event为search_click才取值
            payload.put(KEY_GAME_NAME, gameName); //event为search_click才取值

            // 是否使用镜像
            if (mirrorDataPosition == 1) {
                payload.put("is_mirror_data", true);
            } else if (mirrorDataPosition == 2) {
                payload.put("is_mirror2_data", true);
            }
            payload.put("is_ad_data", isAdData);
            payload.put("ad_space_id", adSpaceId);
            payload.put("game_ad_source_id", gameAdSourceId);
            object.put(KEY_PAY_LOAD, payload);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logGameDetailStrategyButtonEvent(String gameId,
                                                        String gameName,
                                                        String text) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, "game_detail_click_strategy_button");
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_GAME_ID, gameId);
            object.put(KEY_GAME_NAME, gameName);
            object.put("text", text);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logServerTestAccessEvent(String entrance,
                                                String entranceDetail,
                                                String serverTestName,
                                                String serverTestNote) {
        JSONObject payload = new JSONObject();
        try {
            payload.put("server_test_name", serverTestName);
            payload.put("server_test_note", serverTestNote);
            payload.put(KEY_ENTRANCE, entrance);
            payload.put("entrance_detail", entranceDetail);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        logServerTestEvent("access_to_server_test", payload);
    }

    public static void logServerTestSelectTypeEvent(String buttonText,
                                                    String serverTestName,
                                                    String serverTestNote) {
        JSONObject payload = new JSONObject();
        try {
            payload.put("server_test_name", serverTestName);
            payload.put("server_test_note", serverTestNote);
            payload.put("button_text", buttonText);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        logServerTestEvent("server_test_select_type", payload);
    }

    public static void logServerTestSelectTimeEvent(String buttonText,
                                                    String serverTestName,
                                                    String serverTestNote) {
        JSONObject payload = new JSONObject();
        try {
            payload.put("server_test_name", serverTestName);
            payload.put("server_test_note", serverTestNote);
            payload.put("button_text", buttonText);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        logServerTestEvent("server_test_select_time", payload);
    }

    public static void logServerTestClickAllEvent(String serverTestName,
                                                  String serverTestNote) {
        JSONObject payload = new JSONObject();
        try {
            payload.put("server_test_name", serverTestName);
            payload.put("server_test_note", serverTestNote);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        logServerTestEvent("server_test_click_all", payload);
    }

    public static void logServerTestClickMoreEvent(String serverTestName,
                                                   String serverTestNote,
                                                   String redirectType,
                                                   String redirectLink) {
        JSONObject payload = new JSONObject();
        try {
            payload.put("server_test_name", serverTestName);
            payload.put("server_test_note", serverTestNote);
            payload.put("redirect_type", redirectType);
            payload.put("redirect_link", redirectLink);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        logServerTestEvent("server_test_click_more", payload);
    }

    private static void logServerTestEvent(String event, JSONObject payload) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, event);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
            object.put(KEY_PAY_LOAD, payload);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logSpecialCatalogContentClickEvent(String entrance, String key, int seq1, int seqContent) {
        logCatalogEvent("click_content", entrance, key, seq1, -1, seqContent, -1);
    }

    public static void logSpecialCatalogSpecificContentClickEvent(String entrance, String key, int seq1, int seqContent, int seqContentList) {
        logCatalogEvent("click_content_list", entrance, key, seq1, -1, seqContent, seqContentList);
    }

    public static void logSpecialCatalogBannerClickEvent(String key, int seq) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, "category_lunbo_click");
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);

            object.put("key", key);
            object.put("sequence", seq);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    private static void logCatalogEvent(String event, String entrance, String key, int seq1, int seq2, int seqContent, int seqContentList) {
        JSONObject object = new JSONObject();
        JSONObject payload = new JSONObject();
        try {
            object.put(KEY_EVENT, event);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);

            payload.put(KEY_ENTRANCE, entrance); //入口分类, 分为 首页或版块,
            payload.put("key", key); //搜索类型, 有四种取值 默认搜索/历史搜索/自动搜索/主动搜索
            payload.put("seq_1st", seq1); //从0开始,默认-1表示没有
            payload.put("seq_2nd", seq2); //从0开始,默认-1表示没有
            payload.put("seq_content", seqContent);  //精选页上 图片、专题-全部按钮、专题合集-全部按钮 的排序;从0开始,默认-1表示没有
            payload.put("seq_content_list", seqContentList);
            object.put(KEY_PAY_LOAD, payload);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void uploadPackageSkip(String event, String action, String gameId, String gameName) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, event);//external_jump/external_show
            object.put("action", action);
            if (!TextUtils.isEmpty(gameId) && !TextUtils.isEmpty(gameName)) {
                object.put(KEY_GAME_ID, gameId);
                object.put(KEY_GAME_NAME, gameName);
            }
            object.put(KEY_META, getMetaObject());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logStartAd(String event, StartupAdEntity adEntity) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, event);
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
            object.put(KEY_META, getMetaObject());
            if (adEntity != null) {
                object.put("abs_id", adEntity.getId());
                object.put("abs_text", adEntity.getDesc());
                if (adEntity.getButton()) {
                    object.put("abs_type", adEntity.getJump().getType());
                    object.put("abs_link", adEntity.getJump().getLink());
                    object.put("abs_link_title", adEntity.getJump().getText());
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logRecommendClick(String entrance, String recommendName, String linkType, String linkTitle, String linkId, int sequence) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, "recommend_click");
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_ENTRANCE, entrance);
            object.put("recommend_name", recommendName);
            object.put("link_id", linkId);
            object.put("link_type", linkType);
            object.put("link_text", linkTitle);
            object.put("sequence", sequence);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void uploadPackageCheck(String event, String action, GameEntity gameEntity, String linkTitle, String linkDesc, String downloadGameId, String downloadGameName) {
        if (gameEntity == null) return;

        PackageDialogEntity packageDialog = gameEntity.getPackageDialog();
        if (packageDialog == null) return;
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();
        try {
            object.put(KEY_EVENT, event);
            object.put("action", action);

            payloadObject.put(KEY_GAME_ID, gameEntity.getId());
            payloadObject.put(KEY_GAME_NAME, gameEntity.getName());
            payloadObject.put("link_title", linkTitle);
            payloadObject.put("link_desc", linkDesc);
            payloadObject.put("download_game_id", downloadGameId);
            payloadObject.put("download_game_name", downloadGameName);
            JSONArray detectionArray = new JSONArray();
            for (DetectionObjectEntity entity : packageDialog.getDetectionObjects()) {
                JSONObject detectionObject = new JSONObject();
                detectionObject.put("text", entity.getText());
                detectionObject.put("packages", new JSONArray(GsonUtils.toJson(entity.getPackages())));
                detectionArray.put(detectionObject);
            }
            payloadObject.put("detection_objects", detectionArray);

            object.put(KEY_META, getMetaObject());
            object.put(KEY_PAY_LOAD, payloadObject);
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logCategoryV2AppearanceEvent(String entrance, String classification) {
        logCategoryV2Event("access_to_classification_v2", entrance, classification, "", "", "", "", "", -1, -1, -1, -1);
    }

    public static void logCategoryV2ClickSideEvent(String entrance, String classification, String sideClassification, int seq) {
        logCategoryV2Event("click_side", entrance, classification, sideClassification, "", "", "", "", seq, -1, -1, -1);
    }

    public static void logCategoryV2ClickClassificationEvent(String entrance, String classification, String sideClassification, String classification1, String classification2, int seq1, int seq2) {
        logCategoryV2Event("click_classification", entrance, classification, sideClassification, classification1, classification2, "", "", -1, -1, seq1, seq2);
    }

    public static void logCategoryV2ClickClassificationDeleteEvent(String entrance, String classification, String classification1, String classification2, String location) {
        logCategoryV2Event("click_classification_delete", entrance, classification, "", classification1, classification2, "", location, -1, -1, -1, -1);
    }

    public static void logCategoryV2ClickDetermineEvent(String entrance, String classification, String classification2) {
        logCategoryV2Event("click_determine", entrance, classification, "", "", classification2, "", "", -1, -1, -1, -1);
    }

    public static void logCategoryV2ClickResetEvent(String entrance, String classification, String classification2, String location) {
        logCategoryV2Event("click_reset", entrance, classification, "", "", classification2, "", location, -1, -1, -1, -1);
    }

    public static void logSpecialCategoryV2BannerClickEvent(String entrance, String classification, String detail, int seq) {
        logCategoryV2Event("category_lunbo_click_v2", entrance, classification, "", "", "", detail, "", seq, -1, -1, -1);
    }

    public static void logSpecialCategoryV2ContentClickEvent(String entrance, String classification, String detail, int seq) {
        logCategoryV2Event("click_content_v2", entrance, classification, "", "", "", detail, "", seq, -1, -1, -1);
    }

    public static void logSpecialCategoryV2SpecificContentClickEvent(String entrance, String classification, String detail, int seq, int outSeq) {
        logCategoryV2Event("click_content_list_v2", entrance, classification, "", "", "", detail, "", seq, outSeq, -1, -1);
    }

    public static void logCategoryV2Event(String event,
                                          String entrance,
                                          String classification,
                                          String sideClassification,
                                          String classification1,
                                          String classification2,
                                          String detail,
                                          String location,
                                          int seq,
                                          int outSeq,
                                          int seq1,
                                          int seq2) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, event);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);

            object.put(KEY_ENTRANCE, entrance);
            object.put("classification", classification);
            object.put("side_classification", sideClassification);
            object.put("classification_1st", classification1);
            object.put("classification_2nd", classification2);
            object.put("detail", detail);
            object.put("location", location);
            object.put("sequence", seq);
            object.put("outer_sequence", outSeq);
            object.put("seq_1st", seq1);
            object.put("seq_2nd", seq2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logGameDetailFixedTopArticleClick(String gameId, String gameName, String url) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, "game_detail_click_top_strategy");
            object.put(KEY_GAME_ID, gameId);
            object.put(KEY_GAME_NAME, gameName);
            object.put("top_strategy_url", url);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void logHomeTopTabClick(String tabName, String linkType, String linkTitle, String linkId, int sequence, String entrance) {
        JSONObject object = new JSONObject();
        try {
            object.put(KEY_EVENT, "top_tab_click");
            object.put("tab_name", tabName);
            object.put("link_type", linkType);
            object.put("link_id", linkId);
            object.put("link_text", linkTitle);
            object.put("sequence", sequence);
            object.put("entrance", entrance);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void uploadRecommendPopup(String event, String popupId, String gameId, String gameName,
                                            String linkType, String linkTitle, String downloadGameId, String downloadGameName) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();
        try {
            object.put(KEY_EVENT, event);//recommend_pop_show推荐弹窗出现、recommend_pop_close推荐弹窗手动关闭、recommend_pop_link_click点击推荐弹窗链接、recommend_pop_download推荐弹窗下载开始、recommend_pop_download_complete推荐弹窗下载完成
            payloadObject.put("recommend_pop_id", popupId);
            payloadObject.put(KEY_GAME_ID, gameId);
            payloadObject.put(KEY_GAME_NAME, gameName);
            if (!TextUtils.isEmpty(linkType)) {
                payloadObject.put("link_type", linkType);
            }
            if (!TextUtils.isEmpty(linkTitle)) {
                payloadObject.put("link_title", linkTitle);
            }
            if (!TextUtils.isEmpty(downloadGameId)) {
                payloadObject.put("download_game_id", downloadGameId);
            }
            if (!TextUtils.isEmpty(downloadGameName)) {
                payloadObject.put("download_game_name", downloadGameName);
            }
            object.put(KEY_PAY_LOAD, payloadObject);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }

    public static void uploadReceiveGift(String event, String giftId, String giftName, String location, String gameId, String gameName) {
        JSONObject object = new JSONObject();
        JSONObject payloadObject = new JSONObject();
        try {
            object.put(KEY_EVENT, event);//game_gift_get_successful领取礼包、game_gift_dig_successful淘号、game_gift_code_successful复制礼包
            payloadObject.put("gift_id", giftId);
            payloadObject.put("gift_name", giftName);
            payloadObject.put("location", location);
            payloadObject.put(KEY_GAME_ID, gameId);
            payloadObject.put(KEY_GAME_NAME, gameName);
            object.put(KEY_PAY_LOAD, payloadObject);
            object.put(KEY_META, getMetaObject());
            object.put(KEY_TIMESTAMP, System.currentTimeMillis() / 1000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (BuildConfig.DEBUG) {
            Utils.log("LogUtils->" + object.toString());
        }
        LoghubUtils.log(object, LOG_STORE_EVENT, false);
    }
}
