package com.yunbao.common;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yunbao.common.bean.ChatAnchorParam;
import com.yunbao.common.bean.ChatAudienceParam;
import com.yunbao.common.http.CommonHttpUtil;
import com.yunbao.common.http.HttpCallback;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.RouteUtil;
import com.yunbao.common.utils.SpUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-03-22
// +———————————————————————————————————
public class CommonAppContext extends MultiDexApplication {

    public static CommonAppContext sInstance;
    private int mCount;
    private boolean mFront;//是否前台

    private static Handler sMainThreadHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        //初始化Http
        CommonHttpUtil.init();
        //初始化友盟统计
//        UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null);
        registerActivityLifecycleCallbacks();
    }

    @Override
    protected void attachBaseContext(Context base) {
        MultiDex.install(this);
        super.attachBaseContext(base);
    }
    public static CommonAppContext getInstance() {
        if (sInstance == null) {
            try {
                Class clazz = Class.forName("android.app.ActivityThread");
                Method method = clazz.getMethod("currentApplication", new Class[]{});
                Object obj = method.invoke(null, new Object[]{});
                if (obj != null && obj instanceof CommonAppContext) {
                    sInstance = (CommonAppContext) obj;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sInstance;
    }

    private void registerActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {
                mCount++;
                if (!mFront) {
                    mFront = true;
                    onFrontGround();
                    L.e("AppContext------->处于前台");
                    CommonAppConfig.getInstance().setFrontGround(true);

                    if (CommonAppConfig.getInstance().isLaunched()) {
                        String chatCallAncData = SpUtil.getInstance().getStringValue(SpUtil.CHAT_CALL_ANC_DATA);
                        if (!TextUtils.isEmpty(chatCallAncData)) {
                            final JSONObject obj = JSON.parseObject(chatCallAncData);
                            long time = obj.getLongValue(Constants.CALL_TIME);
                            if (SystemClock.elapsedRealtime() - time > Constants.CHAT_WAIT_TIME) {//超过了接听时候的等待时间 1分钟
                                SpUtil.getInstance().setStringValue(SpUtil.CHAT_CALL_ANC_DATA, "");
                                return;
                            }
                            CommonHttpUtil.checkConversation(obj.getString("showid"), new HttpCallback() {
                                @Override
                                public void onSuccess(int code, String msg, String[] info) {
                                    if (code == 0 && info.length > 0) {
                                        if (JSON.parseObject(info[0]).getIntValue("status") == 0) {
                                            ChatAnchorParam param = new ChatAnchorParam();
                                            param.setSessionId(obj.getString("showid"));
                                            param.setChatType(obj.getIntValue("type"));
                                            param.setAudienceID(obj.getString("id"));
                                            param.setAudienceAvatar(obj.getString("avatar"));
                                            param.setAudienceName(obj.getString("user_nickname"));
                                            param.setAnchorActive(false);
                                            RouteUtil.forwardAnchorActivity(param);
                                        }
                                    }
                                }
                            });
                            return;
                        }

                        String chatCallAudData = SpUtil.getInstance().getStringValue(SpUtil.CHAT_CALL_AUD_DATA);
                        if (!TextUtils.isEmpty(chatCallAudData)) {
                            final JSONObject obj = JSON.parseObject(chatCallAudData);
                            long time = obj.getLongValue(Constants.CALL_TIME);
                            if (SystemClock.elapsedRealtime() - time > Constants.CHAT_WAIT_TIME) {//超过了接听时候的等待时间 1分钟
                                SpUtil.getInstance().setStringValue(SpUtil.CHAT_CALL_AUD_DATA, "");
                                return;
                            }
                            CommonHttpUtil.checkConversation(obj.getString("showid"), new HttpCallback() {
                                @Override
                                public void onSuccess(int code, String msg, String[] info) {
                                    if (code == 0 && info.length > 0) {
                                        if (JSON.parseObject(info[0]).getIntValue("status") == 0) {
                                            ChatAudienceParam param = new ChatAudienceParam();
                                            param.setSessionId(obj.getString("showid"));
                                            param.setChatType(obj.getIntValue("type"));
                                            param.setAnchorID(obj.getString("id"));
                                            param.setAnchorAvatar(obj.getString("avatar"));
                                            param.setAnchorName(obj.getString("user_nickname"));
                                            param.setAnchorLevel(obj.getIntValue("level_anchor"));
                                            param.setAnchorPrice(obj.getString("total"));
                                            param.setAudienceActive(false);
                                            RouteUtil.forwardAudienceActivity(param);
                                        }
                                    }
                                }
                            });

                        }
                    }

                }
            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {
                mCount--;
                if (mCount == 0) {
                    mFront = false;
                    L.e("AppContext------->处于后台");
                    CommonAppConfig.getInstance().setFrontGround(false);
                }
            }

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

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    /**
     * 获取主线程的Handler
     */
    private static void getMainThreadHandler() {
        try {
            Class clazz = Class.forName("android.app.ActivityThread");
            Field field = clazz.getDeclaredField("sMainThreadHandler");
            field.setAccessible(true);
            Object obj = field.get(clazz);
            if (obj != null && obj instanceof Handler) {
                sMainThreadHandler = (Handler) obj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void postDelayed(Runnable runnable, long delayMillis) {
        if (sMainThreadHandler == null) {
            getMainThreadHandler();
        }
        if (sMainThreadHandler != null) {
            sMainThreadHandler.postDelayed(runnable, delayMillis);
        }
    }

    public static void post(Runnable runnable) {
        if (sMainThreadHandler == null) {
            getMainThreadHandler();
        }
        if (sMainThreadHandler != null) {
            sMainThreadHandler.post(runnable);
        }
    }


    /**
     * 回到前台
     */
    protected void onFrontGround() {

    }


}
