package com.zkjc.common.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import com.hjq.toast.ToastUtils;
import com.jaeger.library.StatusBarUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.integration.AppManager;
import com.jess.arms.integration.lifecycle.ActivityLifecycleable;
import com.jess.arms.mvp.IPresenter;
import com.jess.arms.utils.ArmsUtils;
import com.xdja.watermarklibrary.WaterMarkUtils;
import com.zkjc.common.broadcast.NetBroadcastReceiver;
import com.zkjc.common.event.IEvent;
import com.zkjc.common.event.NetEvent;
import com.zkjc.common.gps.LocationService;
import com.zkjc.common.utils.ApkUtils;
import com.zkjc.common.utils.NetUtils;
import com.zkjc.common.utils.StartAppScreen;
import com.zkjc.common.utils.StatusBarUtils;

import com.zkjc.common.view.GrayFrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import javax.inject.Inject;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;

public abstract class ZkjcBaseActivity<P extends IPresenter> extends BaseActivity<P> implements IActivity, ActivityLifecycleable {

    @Inject
    AppManager mAppManager;
    protected SharedPreferences sharedPreferences;
    private CompositeDisposable mCompositeDisposable;
    private WeakReference<Context> reference;
    private NetBroadcastReceiver netBroadcastReceiver;
    private boolean bDisconnection = true;
    private int recount = 0;
    private AtomicInteger index = new AtomicInteger(0);
    private AtomicBoolean atomicBoolean = new AtomicBoolean(true);
    private AtomicBoolean atomicRun = new AtomicBoolean(false);
    // private Long[] delay = new Long[]{1000L,1000L,1000L,3000L,3000L,3000L,5000L,5000L,5000L,5000L};
//    private int index = 0;
    private AtomicInteger runStatus = new AtomicInteger(0);
   /* private Intent service;*/
    //屏幕保护
    // private StartAppScreen instance;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onThisEvent(IEvent event) {

    }

    protected void refreshUI() {
    }

  /*  @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        try {
            if ("FrameLayout".equals(name)) {
                int count = attrs.getAttributeCount();
                for (int i = 0; i < count; i++) {
                    String attributeName = attrs.getAttributeName(i);
                    String attributeValue = attrs.getAttributeValue(i);
                    if (attributeName.equals("id")) {
                        int id = Integer.parseInt(attributeValue.substring(1));
                        String idVal = getResources().getResourceName(id);
                        if ("android:id/content".equals(idVal)) {
                            GrayFrameLayout grayFrameLayout = new GrayFrameLayout(context, attrs);
//                            grayFrameLayout.setWindow(getWindow());
                            return grayFrameLayout;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onCreateView(name, context, attrs);
    }*/

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        StatusBarUtil.setTranslucentForImageViewInFragment(this,
                0, null);
        StatusBarUtil.setLightMode(this);
        Intent intent = getIntent();
        if (null == sharedPreferences)
            sharedPreferences = getSharedPreferences("sys", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        // instance = StartAppScreen.getInstance(this);
        String officeName = intent.getStringExtra("officeName");
        if (!TextUtils.isEmpty(officeName)) {
            edit.putString("officeName", officeName);
        }

        String userId = intent.getStringExtra("userId");
        if (!TextUtils.isEmpty(userId)) {
            edit.putString("userId", userId);
        }
        String jh = intent.getStringExtra("pcswhrjh");
        if (!TextUtils.isEmpty(jh)) {
            edit.putString("jh", jh);
        }
        String photoGongzhang = intent.getStringExtra("photoGongzhang");
        if (!TextUtils.isEmpty(photoGongzhang)) {
            edit.putString("photoGongzhang", photoGongzhang);
        }
        String name = intent.getStringExtra("name");
        if (!TextUtils.isEmpty(name)) {
            edit.putString("name", name);
        }
        String phone = intent.getStringExtra("phone");
        if (!TextUtils.isEmpty(phone)) {
            edit.putString("phone", phone);
        }
        String officeId = intent.getStringExtra("officeId");
        if (!TextUtils.isEmpty(officeId)) {
            edit.putString("officeId", officeId);
        }
        String photo = intent.getStringExtra("photo");
        if (!TextUtils.isEmpty(photo)) {
            edit.putString("photo", photo);
        }
        String cardNo = intent.getStringExtra("cardNo");
        if (!TextUtils.isEmpty(cardNo)) {
            edit.putString("cardNo", cardNo);
        }
        float font_size = intent.getFloatExtra("font_size", 1.0f);
        edit.putFloat("font_size", font_size);
        String token = intent.getStringExtra("token");
        if (!TextUtils.isEmpty(token)) {
            edit.putString("token", token);
        }
        edit.commit();
       /* String account = sharedPreferences.getString("account", "");
        String sspcs = sharedPreferences.getString("role_name", "");
   String prefix = "";
        if (TextUtils.isEmpty(sharedPreferences.getString("account", "")))
            prefix = sharedPreferences.getString("role_name", "") + sharedPreferences.getString("account", "");
        else
            prefix = sharedPreferences.getString("role_name", "") + sharedPreferences.getString("account", "");
        String waterMark = "　　" + prefix;
        WaterMarkUtils.addWaterMark(this, waterMark, 350);*/
        if (!ApkUtils.isDemo(this)) {
            //Android 7.0以上需要动态注册
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //实例化IntentFilter对象
                IntentFilter filter = new IntentFilter();
                filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                filter.addAction(Intent.ACTION_SCREEN_ON);
                filter.addAction(Intent.ACTION_SCREEN_OFF);
                filter.addAction(Intent.ACTION_USER_PRESENT);
                filter.addAction(Intent.ACTION_USER_UNLOCKED);

                netBroadcastReceiver = new NetBroadcastReceiver();
                //注册广播接收
                registerReceiver(netBroadcastReceiver, filter);
            }

        }
       /* service = new Intent(this, LocationService.class);
        startService(service);*/
    }


    protected void toClipData(String text) {
        toClipData("anything", text);
    }

    protected void toClipData(String label, String text) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText(label, text);
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /*@Override
    protected void onStart() {
        super.onStart();
        if (useHermesEventBus())
            HermesEventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        if (useHermesEventBus())
            HermesEventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public boolean useHermesEventBus() {
        return false;
    }*/

    @Override
    protected void onResume() {
        //instance.startTipsTimer();
        super.onResume();

    }

/*    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                instance.endTipsTimer();
                break;
            case MotionEvent.ACTION_UP:
                instance.resetTipsTimer();
                break;
            default:
                instance.endTipsTimer();
                break;

        }
        return super.dispatchTouchEvent(ev);
    }*/

    @Override
    protected void onPause() {
        //instance.endTipsTimer();
        super.onPause();
    }

   /* public void reconnect() {
        atomicRun.set(false);
//        runStatus.set(0);
        if (ApkUtils.isDemo(this)){
            return;
        }else {
            reconnect(true);
        }

    }*/

  /*  public void reconnect(boolean isShow) {
//        if(0 != runStatus.get()) return;
        if(atomicRun.get() && 0 != runStatus.get()) {
            if(isShow)
                ToastUtils.show("安全客户端正在启动");
            return;
        }
        atomicRun.set(true);
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            try {
                Activity currentActivity = AppManager.getAppManager().getCurrentActivity();
                if(null == currentActivity) return;
                Context context = currentActivity.createPackageContext("com.zkjc.policedemo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
                reference = new WeakReference<>(context);
//                Timber.d("重新连接" + (atomicInteger.getAndIncrement()) + "次");

//                    Log.d("aaaaa", "重新连接" + (++recount) + "次");
                if(null == reference.get()) {
                    SystemClock.sleep(1000);
                    reconnect(isShow);
                    emitter.onComplete();
                }


//                index = 0;
                index.set(0);
                for(Long time : delay) {
//                    index++;
                    index.incrementAndGet();

                    if(!atomicRun.get()) {
                        atomicRun.set(false);
                        runStatus.set(0);
                        emitter.onComplete();
                        break;
                    }

                    *//*if(false == isForeground(this)) {
//                        bDisconnection = false;
//                    atomicBoolean.set(false);
                        atomicRun.set(false);
                        runStatus.set(0);
                        emitter.onComplete();
                    }*//*
                    NetUtils.reConnect(reference.get(), isShow, status -> {
                        if(status) {
                            refreshUI();
                            if(isShow)
                                ToastUtils.show("安全客户端已连接");
//                            atomicBoolean.set(false);
//                            atomicInteger.set(0);
                            atomicRun.set(false);
                            runStatus.set(0);
                            emitter.onComplete();
                        } else {
                            runStatus.set(index.get());
                            emitter.onNext(status);
                            if(index.get() >= 10) {
                                if(isShow) {
                                    Observable.timer(3, TimeUnit.SECONDS).subscribe(aLong -> {
                                        ToastUtils.show("安全客户端连接失败");
                                    });
                                }

                                atomicRun.set(false);
                                runStatus.set(0);
                                emitter.onComplete();
                            }
                        }
                    });
                    Timber.d("第" + index +  "次重新连接，延时" + time + "ms秒");
                    SystemClock.sleep(time);
                }

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            emitter.onComplete();
        })
        .doOnSubscribe(disposable -> {
            Timber.v("requestLogin===doOnSubscribe:" + Thread.currentThread().getName());
            addDispose(disposable);//在订阅时必须调用这个方法,不然Activity退出时可能内存泄漏
        }).subscribeOn(Schedulers.io())
        .subscribeOn(AndroidSchedulers.mainThread())
        .observeOn(AndroidSchedulers.mainThread())
        .throttleLast(1000, TimeUnit.SECONDS)
        .subscribe();
    }*/

  /*  public synchronized void reconnect1(boolean isShow) {
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            try {
                Activity currentActivity = AppManager.getAppManager().getCurrentActivity();
                if(null == currentActivity) return;
                Context context = currentActivity.createPackageContext("com.zkjc.policedemo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
                reference = new WeakReference<>(context);
//                Timber.d("重新连接" + (atomicInteger.getAndIncrement()) + "次");
                if(false == isForeground(this)) {
//                        bDisconnection = false;
                    atomicBoolean.set(false);
                    emitter.onComplete();
                }
//                    Log.d("aaaaa", "重新连接" + (++recount) + "次");
                if(null == reference.get()) {
                    SystemClock.sleep(1000);
                    reconnect(isShow);
                    emitter.onComplete();
                }

                delay = new Long[]{1000L,1000L,1000L,3000L,3000L,3000L,5000L,5000L,5000L,5000L};
                for(Long time : delay) {
                    NetUtils.reConnect(reference.get(), isShow, status -> {
                        if(status) {
                            atomicBoolean.set(false);
//                            bDisconnection = false;
//                            atomicInteger.set(0);
                            emitter.onNext(status);
                            emitter.onComplete();
                        }
                    });
                    SystemClock.sleep(time);
                }



                *//*while (atomicBoolean.get()) {
                    Timber.d("重新连接" + (atomicInteger.getAndIncrement()) + "次");
                    if(false == isForeground(this)) {
//                        bDisconnection = false;
                        atomicBoolean.set(false);
                        break;
                    }
//                    Log.d("aaaaa", "重新连接" + (++recount) + "次");
                    if(null == reference.get()) {
                        SystemClock.sleep(1000);
                        reconnect(isShow);
                        break;
                    }

                    NetUtils.reConnect(reference.get(), isShow, status -> {
                        if(status) {
                            atomicBoolean.set(false);
//                            bDisconnection = false;
                            atomicInteger.set(0);
                            emitter.onComplete();
                        }
                        emitter.onNext(status);
                    });

                    if(atomicInteger.get() <= 3) {
                        Timber.d("重新连接间隔1s");
                        SystemClock.sleep(1000);
                    }
                    else if(atomicInteger.get() > 3 && atomicInteger.get() <= 6) {
                        Timber.d("重新连接间隔3s");
                        SystemClock.sleep(3000);
                    }
                    else if(atomicInteger.get() > 6 && atomicInteger.get() < 10) {
                        Timber.d("重新连接间隔5s");
                        SystemClock.sleep(5000);
                    }
                    else {
                        atomicBoolean.set(false);
//                        bDisconnection = false;
                        atomicInteger.set(0);
                        break;
                    }
                }*//*

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            emitter.onComplete();
        })
                .doOnSubscribe(disposable -> {
                    Timber.v("requestLogin===doOnSubscribe:" + Thread.currentThread().getName());
                    addDispose(disposable);//在订阅时必须调用这个方法,不然Activity退出时可能内存泄漏
                }).subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .throttleLast(1000, TimeUnit.SECONDS)
                .subscribe(b -> {
                    if(b)
                        refreshUI();
                    else
                        reconnect(isShow);
                });

//        Intent redIntent = new Intent();
//        redIntent.setClassName("com.zkjc.policedemo", "com.zkcj.policedemo.login.AuthActivity");
//        startActivity(redIntent);
    }
*/

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    protected void goHome() {
        PackageManager packageManager = AppManager.getAppManager().getCurrentActivity().getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage("com.zkjc.policedemo");
        startActivity(intent);
        finish();
        if (true) return;

        Intent redIntent = new Intent();
        redIntent.setClassName("com.zkjc.policedemo", "com.zkcj.MainActivityV3");
        startActivity(redIntent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unDispose();

        if (null != netBroadcastReceiver)
            unregisterReceiver(netBroadcastReceiver);
      /*  stopService(service);*/
    }

    public void addDispose(Disposable disposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(disposable);//将所有 Disposable 放入集中处理
    }

    /**
     * 停止集合中正在执行的 RxJava 任务
     */
    public void unDispose() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();//保证 Activity 结束时取消所有正在执行的订阅
        }
    }

   /* @Override
    public Resources getResources() {
        try {
            Context packageContext = createPackageContext("com.zkjc.policedemo", CONTEXT_IGNORE_SECURITY);
            SharedPreferences sp = packageContext.getSharedPreferences("FontSize", MODE_WORLD_READABLE);
            float font_size = sp.getFloat("font_size", 1.0f);
          //  System.out.println("当前字体大小" + font_size);
            Resources res = super.getResources();
            Configuration config = res.getConfiguration();
            config.fontScale = font_size;//1 设置正常字体大小的倍数
            res.updateConfiguration(config, res.getDisplayMetrics());
            return res;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return super.getResources();
    }*/
   @Subscribe(threadMode = ThreadMode.MAIN)
   public void onMessageEvent(Object object) {
        if (object instanceof Integer) {
            if (((Integer) object) == 1) {
                finish();
            }
        }

   }
}
