package com.stm.asset.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.stm.asset.R;

import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.List;

import me.jessyan.autosize.internal.CustomAdapt;

/**
 * 类名称：BaseFragmentActivity
 * 类描述：FragmentActivity基类
 * 创建人：story
 * 创建时间：2021-12-07 13:48
 */
public abstract class BaseFragmentActivity extends FragmentActivity implements CustomAdapt {

    protected WeakReference<Activity> weakReference;
    protected StmApplication sApp;
    protected TextView titleTxt, backTxt, rightTxt;
    protected ImageView backImg, rightImg;
    protected LinearLayout backLayout, rightLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sApp = StmApplication.getInstance();
        weakReference = new WeakReference<>((Activity) this);
        sApp.enterActivity(weakReference);
    }

    protected void initTitle(){
        try {
            titleTxt = findViewById(R.id.common_title_middle_txt);
            backImg = findViewById(R.id.common_title_back_img);
            backTxt = findViewById(R.id.common_title_back_txt);
            backLayout = findViewById(R.id.common_title_back_layout);
            rightImg = findViewById(R.id.common_title_right_img);
            rightTxt = findViewById(R.id.common_title_right_txt);
            rightLayout = findViewById(R.id.common_title_right_layout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (!isAppOnForeground()) {
                    try {
                        // 弹出Toast提示
                        StmApplication.getInstance().getCurrentAct().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (StmApplication.getInstance().isShowBackground()) {
//                                    StmApplication.getInstance().showToastShort(StmApplication.getInstance().getResources().getString(R.string.app_name) + "已经被切到后台运行");
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 500);
    }

    @Override
    protected void onDestroy() {
        sApp.removeActivity(weakReference);
        super.onDestroy();
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 846;
    }

    private boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivityPackageName;
        int sdkVersion;
        try {
            sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            sdkVersion = 0;
        }
        if (sdkVersion >= 21) {
            runningActivityPackageName = getCurrentPkgName(getApplicationContext());
        } else {
            runningActivityPackageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
        }
        if (getPackageName().equals(runningActivityPackageName)) {
            return true;
        }
        return false;
    }

    private static String getCurrentPkgName(Context context) {
        // 5x系统以后利用反射获取当前栈顶activity的包名.
        ActivityManager.RunningAppProcessInfo currentInfo = null;
        Field field = null;
        int START_TASK_TO_FRONT = 2;
        String pkgName = null;
        try {
            // 通过反射获取进程状态字段.
            field = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List appList = am.getRunningAppProcesses();
        ActivityManager.RunningAppProcessInfo app;
        for (int i = 0; i < appList.size(); i++) {
            app = (ActivityManager.RunningAppProcessInfo) appList.get(i);
            //表示前台运行进程.
            if (app.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                Integer state = null;
                try {
                    state = field.getInt(app);// 反射调用字段值的方法,获取该进程的状态.
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 根据这个判断条件从前台中获取当前切换的进程对象
                if (state != null && state == START_TASK_TO_FRONT) {
                    currentInfo = app;
                    break;
                }
            }
        }
        if (currentInfo != null) {
            pkgName = currentInfo.processName;
        }
        return pkgName;
    }
}
