package com.gem.media;

import static android.app.Application.getProcessName;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;

import androidx.core.content.ContextCompat;

import com.ads.cal.core.ListenerHelper.AdListenerHelper;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.activity.CameraActivity;
import com.ads.cal.picturetranslate.activity.PictureTranslateListMainActivity;
import com.ads.cal.picturetranslate.activity.PictureTranslateResultActivity;
import com.android.gem.core.ReportBean;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdStatusCallBack;
import com.gem.media.ad.InterstitialAdManager;
import com.gem.media.ad.InterstitialAdStatusCallBack;
import com.gem.media.ad.InterstitialHalfAdManager;
import com.gem.media.ad.NativeAdClearManager;
import com.gem.media.ad.NativeAdManager;
import com.gem.media.ad.NativeAdStatusCallBack;
import com.gem.media.ad.NativeCleanAdStatusCallBack;
import com.gem.media.ad.OpenAdManager;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PROP;
import com.gem.media.splash.base.utils.PkgUtils;
import com.or.ange.database.LikePal;
import com.or.ange.dot.Settings;
import com.or.ange.dot.UsageStats;
import com.or.ange.dot.utils.LLog;
import com.tencent.bugly.crashreport.CrashReport;
import com.thinkup.nativead.api.TUNativeView;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class InitA {


    private static final class InitAHolder {
        private static final InitA INIT_UTIL = new InitA();
    }

    public static InitA getInstance() {
        return InitA.InitAHolder.INIT_UTIL;
    }


    private String cvPkg;
    private Messenger messenger;
    private Messenger cleanMessenger;
    private String uuid;
    private volatile int alertWindowOpen = -1;
    private int pid = -1;
    private AdListenerHelper.AdShownCallback adShownCallback;
    private AdListenerHelper.AdNativeShownCallback adNativeShownCallback;


    public void init(Application context) {
        if (isMainProcess(context)) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                String processName = getProcessName();
                if (!context.getPackageName().equals(processName)) {
                    WebView.setDataDirectorySuffix(processName);
                }
            }

            pid = android.os.Process.myPid();
            initBugly(context);
            initInterstitialAdListener();
            initOpenAdListener();
            initNativeAdListener();
            initNativeAdClearListener();
            initInterstitialHalfAdListener();
            context.registerActivityLifecycleCallbacks(mLifecycleCallbacks);
            registerScreenBroadcastReceiver(context);
            CleanUtil.init(context);
        }
    }

    private void initBugly(Context context) {
        try {
            String pkgName = context.getPackageName();
            String buglyAppId = "66bcabe3b5";
            if ("com.solide.filemanager.lte".equals(pkgName)) {
                buglyAppId = "77338e3566";
            } else if ("com.mystickers.stickermaker".equals(pkgName)) {
                buglyAppId = "220dc0dc54";
            }
            CrashReport.initCrashReport(context, buglyAppId, false);
        } catch (Exception e) {
        }
    }


    private boolean isMainProcess(Context context) {
        String processName = "";
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
            processName = getProcessName();
        } else {
            processName = getCurrentProcessName(context);
        }
        return context.getPackageName().equals(processName);
    }

    private String getCurrentProcessName(Context context) {
        int pid = android.os.Process.myPid();
        try {
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processInfos = manager.getRunningAppProcesses();
            if (null == processInfos) {
                return "";
            }

            for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
                if (processInfo.pid == pid) {
                    return processInfo.processName;
                }
            }
        } catch (Exception e) {
            ALog.d("MediaApplication", "getProcessName exception: e =" + e);
        }
        return "";
    }


    private volatile boolean isMediaAppInit = false;
    public void initMediaApp(String appId, Context context) {
        ALog.e("MediaApplication", (isMainProcess(context)) + "");
        if (isMainProcess(context)) {
            if (isMediaAppInit) {
                ALog.w("MediaApplication", "init success channelId = " + appId);
                return;
            }
            ALog.w("MediaApplication", "init success channelId = " + appId);
            isMediaAppInit = true;
            initDot(appId, context);
            AdReqHasCallBackUtil.checkAdReqHasCallBack();
            statStart();
            KpLiveHelper.getInstance().init();
            RestartAndOnlineTimeStaticsHelper.setRestartCount();
        } else {
            ALog.w("MediaApplication", "init not is MainProcess channelId = " + appId);
        }
    }

    private static void initDot(String appId, Context context) {
        try {
            LikePal.initialize(context);
            UsageStats.setDebug(PROP.isLogEnabled());
            Settings settings = UsageStats.initialize(context, appId, "out", "wz_ad_table", true);
            settings.reportUrl("https://api.weatherlive.world/odborwer_dot/cm");
            ALog.w("MediaApplication", "initDot");
        } catch (Exception e) {
            ALog.w("MediaApplication", "initDot e : " + Log.getStackTraceString(e));
        }
    }

    private Activity currentActivity;

    private int foregroundPageNumbers = 0;
    public boolean isAppBackground() {
        boolean isBackground = foregroundPageNumbers <= 0;
        ALog.d("MediaApplication", "isBackground = " + isBackground);
        return isBackground;
    }


    private static final int RUN_DELAY = 2000;
    private long lastRun = 0L;
    private SystemDialogReceiver systemDialogReceiver;

    private final Application.ActivityLifecycleCallbacks mLifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {

        @Override
        public void onActivityStopped(Activity activity) {
            if (foregroundPageNumbers > 0) {
                foregroundPageNumbers--;
            }
            if (foregroundPageNumbers < 0) {
                foregroundPageNumbers = 0;
            }
            ALog.d("MediaApplication", "onActivityStopped :" + activity);
            if (isAppBackground()) {
                if (null != systemDialogReceiver) {
                    try {
                        PictureApplication.getApplication().unregisterReceiver(systemDialogReceiver);
                    } catch (Exception e) {
                        //
                    } finally {
                        systemDialogReceiver = null;
                    }
                }

                try {
                    if (SystemDialogReceiver.toRecent) {
                        SystemDialogReceiver.toRecent = false;
                        return;
                    }

                    long currentTime = System.currentTimeMillis();
                    if (currentTime - lastRun < RUN_DELAY) {
                        return;
                    }
                    lastRun = currentTime;

                    Message message = Message.obtain();
                    message.what = 20002;
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("notify", !(activity instanceof CameraActivity));
                    message.setData(bundle);
                    if (cleanMessenger != null) {
                        cleanMessenger.send(message);
                        return;
                    }
                    if (messenger != null) {
                        messenger.send(message);
                    }
                } catch (Exception e) {
                    LLog.d("MediaApplication", Log.getStackTraceString(e));
                    //
                }
//                try {
//                    activity.onBackPressed();
//                } catch (Exception e) {
//                    StatsStaticHelper.onEvent("b_er", e.getMessage());
//                }
//                cleanTask();
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            foregroundPageNumbers++;
            if (foregroundPageNumbers == 1) {
                if (systemDialogReceiver == null) {
                    try {
                        systemDialogReceiver = new SystemDialogReceiver();
                        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                        ContextCompat.registerReceiver(PictureApplication.getApplication(), systemDialogReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
                    } catch (Exception e) {
                        //
                        systemDialogReceiver = null;
                    }
                }
            }
            ALog.d("MediaApplication", "onActivityStarted :" + activity.getLocalClassName());
            if (activity instanceof PictureTranslateListMainActivity || activity instanceof NActivity) {
                currentActivity = activity;
            }
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

        @Override
        public void onActivityResumed(Activity activity) {}

        @Override
        public void onActivityPaused(Activity activity) {}

        @Override
        public void onActivityDestroyed(Activity activity) {
            ALog.d("MediaApplication", "onActivityDestroyed :" + activity.getLocalClassName()) ;
            if (activity instanceof PictureTranslateListMainActivity || activity instanceof NActivity) {
                currentActivity = null;
            }
        }

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            try {
                Window window = activity.getWindow();
                if (window != null) {
                    window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void cleanTask(Context context, int i) {
        foregroundPageNumbers = 0;
        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.AppTask> appTasks = activityManager.getAppTasks();
            for (ActivityManager.AppTask task : appTasks) {
                ActivityManager.RecentTaskInfo info = task.getTaskInfo();

                if (info == null || info.baseIntent == null) {
                    continue;
                }

                ComponentName componentName = info.baseIntent.getComponent();
                if (componentName == null) {
                    continue;
                }

                task.finishAndRemoveTask();
            }
        } catch (Exception e) {
        } finally {
            adShownCallback = null;
        }
    }

    public void closeActivity(int i) {
        ALog.d("MediaApplication", "currentActivity " + currentActivity+" i= "+i);
        if (currentActivity != null && currentActivity instanceof PictureTranslateListMainActivity) {
            currentActivity.runOnUiThread(() -> {
                if (currentActivity == null) {
                    return;
                }
                if (currentActivity instanceof PictureTranslateListMainActivity) {
                    closeActivity();
                }
            });
        }
    }

    public void closeNActivity(int i) {
        ALog.d("MediaApplication", "currentActivityN " + currentActivity+" i= "+i);
        if (currentActivity != null && currentActivity instanceof NActivity) {
            currentActivity.runOnUiThread(() -> {
                if (currentActivity == null) {
                    return;
                }
                if (currentActivity instanceof NActivity) {
                    closeActivity();
                }
            });
        }

    }

    private void closeActivity() {
        boolean isFinishing = currentActivity.isFinishing();
        boolean isDestroyed = currentActivity.isDestroyed();
        ALog.d("MediaApplication", "currentActivity runOnUiThread  isFinishing = " + isFinishing+"  isDestroyed ="+isDestroyed);
        if (isFinishing || isDestroyed) {
            currentActivity = null;
            return;
        }
        currentActivity.finish();
        currentActivity = null;
    }

    public Activity getCurrentActivity() {
        return currentActivity;
    }



    public static void registerScreenBroadcastReceiver(Context context) {
        ScreenBroadcastReceiver screenBroadcastReceiver = new ScreenBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);// 灭屏
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);// 灭屏
        context.registerReceiver(screenBroadcastReceiver, intentFilter);
        ALog.d("ScreenBroadcastReceiver注册了");
    }

    private void statStart() {
        StatsStaticHelper.onEvent("media_start");
    }

    public void setCvPkg(String cvPkg) {
        this.cvPkg = cvPkg;
    }

    public void setCleanMessenger(Messenger cleanMessenger) {
        this.cleanMessenger = cleanMessenger;
    }

    public Messenger getCleanMessenger() {
        return cleanMessenger;
    }

    public void setMessenger(Messenger messenger) {
        this.messenger = messenger;
    }

    public Messenger getMessenger() {
        return messenger;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getUuid() {
        return null == uuid ? "" : uuid;
    }

    public void setAlertWindowOpen(boolean open) {
        if (open) {
            alertWindowOpen = 1;
        } else {
            alertWindowOpen = 0;
        }
//        statAlertWindowSwitchState();
        PViewManager.getInstance().showOrRemoveWindow();
    }

    public void statAlertWindowSwitchState() {
        boolean alertWindowOpen =  getAlertWindowOpen();
        ALog.d("MediaApplication","alertWindowOpen :" + alertWindowOpen);
//        if (alertWindowOpen) {
//            StatsStaticHelper.onEvent("alertWindowOpen");
//        } else {
//            StatsStaticHelper.onEvent("alertWindowClose");
//        }
    }

    public boolean getAlertWindowOpen() {
        return alertWindowOpen == 1;
    }

    private void initInterstitialAdListener() {
        InterstitialAdManager.getInstance().setAdStatusCallBack(new InterstitialAdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);
                if (null != adShownCallback) {
                    adShownCallback.onAdCompleted();
                }
            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }


            @Override
            public void onInterstitialAdVideoStart(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onInterstitialAdVideoEnd(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onInterstitialAdVideoError(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }
        });
    }

    private void initOpenAdListener() {
        OpenAdManager.getInstance().setAdStatusCallBack(new AdStatusCallBack() {
            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time, String scenario) {
                sendAdStatusMessage(type, ad_type, reason, time, scenario);

            }
        });
    }

    private void initNativeAdClearListener() {
        NativeAdClearManager.setAdStatusCallBack(new NativeCleanAdStatusCallBack() {

            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String adId, String scenario, String adPosition) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
                if (isAppBackground()) {
                    return;
                }
                ALog.e("AudioEditorInit", "setAdNativeDisplayListener   6 " + adNativeShownCallback);
                if (adNativeShownCallback != null) {
                    ALog.e("AudioEditorInit", "setAdNativeDisplayListener   7 " + PictureApplication.getApplication());
                    if (PictureApplication.getApplication() == null) {
                        adNativeShownCallback.onAdCompleted(null, adPosition);
                        return;
                    }
                    NativeAdClearManager nativeManager = AdManager.getInstance().getNativeManager(adPosition);
                    if (nativeManager != null && nativeManager.isNativeAdReady()) {
                        displayNativeAd(nativeManager, PictureApplication.getApplication(), adNativeShownCallback);
                        return;
                    }
                    NativeAdClearManager cachedManager = AdManager.getInstance().searchHasCacheNativeAd();
                    if (cachedManager != null && cachedManager.isNativeAdReady()) {
                        displayNativeAd(cachedManager, PictureApplication.getApplication(), adNativeShownCallback);
                        return;
                    }
                    // 没有可用广告时返回空视图
                    adNativeShownCallback.onAdCompleted(null, adPosition);
                }
            }

            private void displayNativeAd(NativeAdClearManager manager, Context context,
                                         AdListenerHelper.AdNativeShownCallback callback) {
                try {
                    TUNativeView view = (TUNativeView) LayoutInflater.from(context)
                            .inflate(R.layout.view_native_ad_layout, null);
                    LLog.e("AudioEditorInit", "setAdNativeDisplayListener   8 " + view);
                    CleanUtil.showNativeView(manager, view);
                    callback.onAdCompleted(view, manager.getAdPosition());
                } catch (Exception e) {
                    LLog.e("AudioEditorInit", "显示广告时出错: " + e.getMessage());
                    callback.onAdCompleted(null, manager.getAdPosition());
                }
            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String adId, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onNativeAdVideoStart(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onNativeAdVideoEnd(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onNativeAdVideoError(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }
        });
    }

    private void initNativeAdListener() {
        NativeAdManager.getInstance().setAdStatusCallBack(new NativeAdStatusCallBack() {

            @Override
            public void onNativeAdVideoStart(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onNativeAdVideoEnd(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onNativeAdVideoError(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);

            }
        });
    }

    private void initInterstitialHalfAdListener() {
        InterstitialHalfAdManager.getInstance().setAdStatusCallBack(new InterstitialAdStatusCallBack() {
            @Override
            public void onInterstitialAdVideoStart(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onInterstitialAdVideoEnd(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onInterstitialAdVideoError(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoad(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoaded(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onNoAdError(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdShow(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdClick(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdDismiss(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }

            @Override
            public void onAdLoadTimeout(String type, String ad_type, String reason, long time, String scenario) {
                sendNativeAdStatusMessage(type, ad_type, reason, time, scenario);
            }
        });
    }

    private void sendAdStatusMessage(String type, String ad_type, String reason, long time, String scenario) {
        Context context = PictureApplication.getApplication();
        Map<String, String> map = new HashMap<>();
        if (pid == -1) {
            pid = android.os.Process.myPid();
        }
        map.put("pid", String.valueOf(pid));
        map.put("type", type);
        try {
            map.put("ad_type", ad_type);
            map.put("time", String.valueOf(time));
            map.put("reason", reason);
            map.put("ad_msg_error", reason);
            map.put("net",NetworkUtils.getNetworkType(context).name());
            String pkgName = context.getPackageName();
            map.put(Constants.TARGET_PKG, !TextUtils.isEmpty(cvPkg) ? cvPkg : pkgName);
            map.put(Constants.MEDIA_PKG, pkgName);
            map.put("scenario", scenario);
            map.put("uuid", getUuid());
            map.put("vn", PkgUtils.getAppVersionName(context, pkgName));
            map.put("vc", PkgUtils.getAppVersionCode(context, pkgName));
            map.put("c_time", System.currentTimeMillis() + "");
            ALog.e("sendAdStatusMessage", "type     " + type + "      ad_type      " + ad_type + "      reason      " + reason);
        } catch (Exception throwable) {
//            ALog.e("sendAdStatusMessage", "finish e: " + Log.getStackTraceString(throwable));
        }
        try {
            ReportBean reportBean = new ReportBean();
            reportBean.setType(type);
            if (!map.isEmpty()) {
                reportBean.setData(map);
            }
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 5001;
                Bundle bundle = new Bundle();
                bundle.putParcelable("reportBean", reportBean);
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void sendNativeAdStatusMessage(String type, String ad_type, String reason, long time, String scenario) {
        Context context = PictureApplication.getApplication();
        Map<String, String> map = new HashMap<>();
        if (pid == -1) {
            pid = android.os.Process.myPid();
        }
        map.put("pid", String.valueOf(pid));
        map.put("type", type);
        try {
            map.put("ad_type", ad_type);
            map.put("time", String.valueOf(time));
            map.put("reason", reason);
            map.put("ad_msg_error", reason);
            map.put("net",NetworkUtils.getNetworkType(context).name());
            String pkgName = context.getPackageName();
            map.put(Constants.TARGET_PKG, "");
            map.put(Constants.MEDIA_PKG, pkgName);
            map.put("scenario", scenario);
            map.put("uuid", getUuid());
            map.put("vn", PkgUtils.getAppVersionName(context, pkgName));
            map.put("vc", PkgUtils.getAppVersionCode(context, pkgName));
            map.put("c_time", System.currentTimeMillis() + "");
            ALog.e("sendAdStatusMessage", "type     " + type + "      ad_type      " + ad_type + "      reason      " + reason);
        } catch (Exception throwable) {
//            ALog.e("sendAdStatusMessage", "finish e: " + Log.getStackTraceString(throwable));
        }
        try {
            ReportBean reportBean = new ReportBean();
            reportBean.setType(type);
            if (!map.isEmpty()) {
                reportBean.setData(map);
            }
            if (messenger != null) {
                Message message = Message.obtain();
                if (Objects.equals(scenario, Constants.SCENARIO_NATIVE_CLEAR)) {
                    message.what = 5004;
                } else if (Objects.equals(scenario, Constants.SCENARIO_NATIVE)){
                    message.what = 5002;
                }
                Bundle bundle = new Bundle();
                bundle.putParcelable("reportBean", reportBean);
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    public AdListenerHelper.AdShownCallback getAdShownCallback() {
        return adShownCallback;
    }

    public void setAdShownCallback(AdListenerHelper.AdShownCallback adShownCallback) {
        this.adShownCallback = adShownCallback;
    }

    public void setAdNativeShownCallback(AdListenerHelper.AdNativeShownCallback adNativeShownCallback) {
        this.adNativeShownCallback = adNativeShownCallback;
    }
}
