package com.mints.goodmoney;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.WebView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.bun.miitmdid.core.JLibrary;
import com.component.dly.xzzq_ywsdk.YwSDK;
import com.mints.goodmoney.common.Constant;
import com.mints.goodmoney.manager.MiitHelper;
import com.mints.goodmoney.manager.TtCsjAdManager;
import com.mints.goodmoney.manager.UserManager;
import com.mints.goodmoney.manager.YlhAdManager;
import com.mints.goodmoney.net.LoanService;
import com.mints.goodmoney.utils.ForegroundOrBackground;
import com.mints.goodmoney.utils.LogUtil;
import com.mints.goodmoney.utils.SystemUtils;
import com.yilan.sdk.ui.YLUIInit;
import com.yilan.sdk.ui.configs.CommentConfig;
import com.yilan.sdk.ui.configs.FeedConfig;
import com.yilan.sdk.ui.configs.YLUIConfig;

import rx.Scheduler;
import rx.schedulers.Schedulers;

/**
 * 描述：Application
 * 作者：孟崔广
 * 时间：2020/10/09 11:40
 */
public class MintsApplication extends MultiDexApplication {

    private static Context mContext;
    public static String OAID = "";

    private static LocalBroadcastManager mLocalBroadcatManager;
    private Scheduler defaultSubscribeScheduler;

    private LoanService loanService;

    public static Context getContext() {
        return mContext;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this.getApplicationContext();
        // 判断应用是否在前台
        ForegroundOrBackground.init(this);
        // 三方配置
        thirdConfig();
    }

    @Override
    public void onLowMemory() {
        android.os.Process.killProcess(android.os.Process.myPid());
        super.onLowMemory();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);

        // 移动安全联盟
        try {
            JLibrary.InitEntry(base);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 三方配置
     */
    private void thirdConfig() {
        // 移动安全联盟 oaid
        initMiitHelper();

        //Android 9 or above must be set
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName();
            if (!getPackageName().equals(processName)) {
                WebView.setDataDirectorySuffix(processName);
            }
        }

        // 子线程初始化三方SDK
        String processName = SystemUtils.INSTANCE.getProcessName(this, android.os.Process.myPid());
        if (processName != null) {
            // 判断onCreate方法执行是否在当前应用的application上
            boolean defaultProcess = TextUtils.equals(processName, Constant.MINTS_PKG_NAME);
            if (defaultProcess) {
                InitAppService.Companion.start(this); //初始化数据
            }
        }

        // 优量汇
        initYlh();

        // 穿山甲
        initCsj();

        // 一览视频
        initYL();

//        // 猎豹游戏初始化
//        LiebaoManager.getInstance().initCmGameSdk();
    }

    private MiitHelper.AppIdsUpdater appIdsUpdater = ids -> OAID = ids;

    /**
     * 移动安装联盟 获取OAID等设备标识符
     */
    private void initMiitHelper() {
        try {
            MiitHelper miitHelper = new MiitHelper(appIdsUpdater);
            miitHelper.initDeviceIds(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e(e);
        }
    }

    /**
     * 优量汇
     */
    private void initYlh() {
        YlhAdManager.INSTANCE.initYlhAd(this);
    }

    /**
     * 穿山甲
     */
    private void initCsj() {
        TtCsjAdManager.init(this);
    }

    /**
     * 一览视频
     */
    private void initYL() {
        YLUIInit.getInstance()
                .setCrashOpen(false)
                .setApplication(this)
                .setAccessKey("ylxgszgwjrr8")
                .setAccessToken("lmnzhm9yjdlc86xiy74cjgixnqpxe4o2")
                .build();

        //页面个性化配置
        YLUIConfig.getInstance() //抖音样式小视频配置
                .littleLikeShow(true) //是否显示点赞
                .littleShareShow(false) //是否显示分享
                .littleShowGuide(true)//是否显示新手引导滑动浮层（第一次安装进入显示）
                .littleComment(CommentConfig.CommentType.DISMISS_COMMENT) //评论,参数详见文档；
                //feed流短视频样式配置
                .videoComment(CommentConfig.CommentType.DISMISS_COMMENT) //评论,参数详见文档；
                .videoLikeShow(false) //是否显示点赞
                .videoShareShow(false) //是否显示分享
                .followAvailable(false) //关注功能是否可用
                .feedAvatarClickable(true) //头像是否支持点击跳转到作者页面
                .feedPlayAuto(true) //feed自动播放
                .feedSwipeRefreshEnable(true); //feed是否可以下拉刷新
        FeedConfig.getInstance().setPlayerStyle(FeedConfig.STYLE_FEED_PLAY); //FeedConfig.STYLE_FEED_PLAY当前页面播放
    }

    /**
     * 鱼丸盒子
     */
    public void initYwSdk() {
        UserManager userManager = UserManager.getInstance();
        String userID = userManager.getUserID();
        if (!userManager.userIsLogin() || TextUtils.isEmpty(userID)) {
            // 用户id为空 或 未登录 = 游客
            userID = "0";
        }

        String appid;
        String appSecret;
        if (BuildConfig.DEBUG) {
            appid = "1725";
            appSecret = "0yzizbqwyjt104gsdukmto53qclo9ljs";
        } else {
            appid = "1726";
            appSecret = "g4fuod79v6e7cw4liw91iwfm5qryvz1u";
        }
        String oaid = "";
        if (Build.VERSION.SDK_INT > 28) {
            oaid = OAID;
        }
        YwSDK.Companion.setDebugMode();
        YwSDK.Companion.init(this, appSecret, appid, userID, "1", oaid);
    }

    /**
     * app退出
     */
    public void exitApp() {
        Intent intent = new Intent();
        intent.setAction(Constant.ACTION_EXIT_APP);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        MintsApplication.getLocalBroadcastManager().sendBroadcast(intent);

        System.gc();
    }

    /**
     * 获得LocalBroadcastManager对象
     */
    public static LocalBroadcastManager getLocalBroadcastManager() {
        if (mLocalBroadcatManager == null) {
            mLocalBroadcatManager = LocalBroadcastManager.getInstance(mContext);
        }
        return mLocalBroadcatManager;
    }

    public LoanService getLoanService() {
        if (loanService == null) {
            loanService = LoanService.Factory.create();
        }
        return loanService;
    }

    public Scheduler defaultSubscribeScheduler() {
        if (defaultSubscribeScheduler == null) {
            defaultSubscribeScheduler = Schedulers.io();
        }
        return defaultSubscribeScheduler;
    }
}
