package com.common.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.CheckResult;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.jcminarro.philology.Philology;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;

import io.github.inflationx.viewpump.ViewPumpContextWrapper;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
import tech.starwin.LibConfig;
import tech.starwin.R;
import tech.starwin.base.BasePresenter;


import tech.starwin.mvp.IView;
import tech.starwin.mvp.presenter.UserPresenter;
import tech.starwin.utils.context_utils.AppLanguageUtils;
import tech.starwin.utils.PresenterHoler;
import tech.starwin.utils.context_utils.FragmentLauncher;
import tech.starwin.utils.format_utils.StringDecrypt;
import tech.starwin.utils.ui_utils.DialogFactory;
import tech.starwin.utils.ui_utils.QMUIHelper;

import com.common.widget.ProgressDialog;
import com.common.widget.TopBar;

/**
 * Created by SiKang on 2018/9/14.
 */
public abstract class BaseActivity extends AppCompatActivity implements IView {
    public String TAG;
    /**
     * 根布局
     */
    public ViewGroup rootLayout;

    /**
     * TopBar
     */
    private TopBar mTopBar;

    /**
     * 创建和缓存Presenter实例
     */
    private PresenterHoler presenterHelper;

    /**
     * 侧滑抽屉
     */
    private DrawerLayout drawerLayout;

    /**
     * loading、error 提示
     */
    protected ProgressDialog progressDialog;

    private FragmentLauncher fragmentLauncher;


    private Object unBinder;

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();


    /**
     * 逻辑代码托管
     */
    private BaseTrustee trustee;

    @Override
    protected void attachBaseContext(Context newBase) {
//        super.attachBaseContext(AppLanguageUtils.attachBaseContext(newBase, LibConfig.LANGUAGE));
        Context languageContext = AppLanguageUtils.attachBaseContext(newBase, LibConfig.LANGUAGE);
        super.attachBaseContext(ViewPumpContextWrapper.wrap(Philology.INSTANCE.wrap(languageContext)));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ScreenAutoSize.getInstance().resizeDensity(this, 360f);
        TAG = getClass().getSimpleName();
        lifecycleSubject.onNext(ActivityEvent.CREATE);
        progressDialog = new ProgressDialog(this);
        presenterHelper = new PresenterHoler(this);
        initRootLayout();

        if (getTrustee() != null) {
            getTrustee().onCreate();
        }
    }

    public ViewGroup getContentView() {
        return rootLayout;
    }

    @Override
    protected void onStart() {
        super.onStart();
        //TODO - FireBase配置
        //如果是通过FireBase CloudMessage 调起的界面，将消息交给Service处理
//        String action = getIntent().getAction() == null ? "" : getIntent().getAction();
//        String from = getIntent().getStringExtra("from");
//        if (action.equals("android.intent.action.MAIN") &&
//                !TextUtils.isEmpty(from)) {
//            MsgHandleService.handleMsg(this, new RemoteMessage(getIntent().getExtras()));
//        }
        lifecycleSubject.onNext(ActivityEvent.START);
        if (getTrustee() != null) {
            getTrustee().onStart();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (getTrustee() != null) {
            getTrustee().onRestart();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
        if (getTrustee() != null) {
            getTrustee().onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        progressDialog.dissmissLoading();
        if (getTrustee() != null) {
            getTrustee().onPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        progressDialog.setEnable(false);
        lifecycleSubject.onNext(ActivityEvent.STOP);
        if (getTrustee() != null) {
            getTrustee().onStop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unBinder != null) {
            LibConfig.unBindView(unBinder);
        }
        lifecycleSubject.onNext(ActivityEvent.DESTROY);
        presenterHelper.onDestory();
        if (getTrustee() != null) {
            getTrustee().onDestroy();
        }
    }


    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }


    //-----------------------------------  IView  ----------------------------------------


    @Override
    public void onHttpStart(String action, boolean isShowLoading) {
        if (isShowLoading && !progressDialog.isShowing()) {
            //500ms后如果还没有收到返回数据，显示loading
            progressDialog.setEnable(true);
            rootLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressDialog.showLoading();
                }
            }, 500);
        }
    }

    @Override
    public void onHttpSuccess(String action, Object result) {
    }

    @Override
    public void onHttpFinish(String action) {
        progressDialog.setEnable(false);
        progressDialog.dissmissLoading();
    }

    @Override
    public void onHttpError(String action, String msg) {
        Log.e(TAG, action + "： " + msg);
        DialogFactory.createMessageDialog(this, "Tip", msg, "OK").show();
    }

    //-----------------------------------  Layout  ----------------------------------------

    private void initRootLayout() {
        setContentView(R.layout.base_activity_root);
        rootLayout = findViewById(R.id.root_layout);
        //是否使用沉浸式状态栏
        if (useTransparentStatusBar()) {
            QMUIStatusBarHelper.translucent(this);
        }
        //判断是否要显示TopBar
        if (useTopBar()) {
            mTopBar = QMUIHelper.insertTopBar(rootLayout, useTransparentStatusBar());
            if (mTopBar != null)
                initTopBar(mTopBar);
        }
        //填充Activity -> bindLayout();
        if (bindLayout() != 0) {
            //是否使用了侧滑
            if (bindDrawerLayout() != 0) {
                drawerLayout = LayoutInflater.from(this).inflate(R.layout.base_activity_drawer, rootLayout, true).findViewById(R.id.root_drawer_layout);
                FrameLayout content = drawerLayout.findViewById(R.id.root_content);
                FrameLayout drawer = drawerLayout.findViewById(R.id.root_drawer);
                drawer.setClickable(true);
                LayoutInflater.from(this).inflate(bindLayout(), content, true);
                LayoutInflater.from(this).inflate(bindDrawerLayout(), drawer, true);
            } else {
                LayoutInflater.from(this).inflate(bindLayout(), rootLayout, true);
            }
        }
        unBinder = LibConfig.bindView(this, rootLayout);
        initView();
        getFragmentLauncher();
    }

    /**
     * 绑定布局文件
     */
    @LayoutRes
    public abstract int bindLayout();

    /**
     * Activity初始化
     */
    public abstract void initView();

    /**
     * 是否使用TopBar，默认使用
     */
    public boolean useTopBar() {
        return true;
    }

    /**
     * 是否使用沉浸式状态栏，默认使用
     */
    public boolean useTransparentStatusBar() {
        return true;
    }


    /**
     * 是否使用侧滑
     */
    public int bindDrawerLayout() {
        return 0;
    }


    /**
     * 初始化TopBar，需要自定义TopBar样式时重写
     * 默认TopBar只包含一个BackButton 和 Titile
     */
    protected void initTopBar(TopBar topBar) {
//        topBar.toolBar().addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        //bug fix：每个客户单独定制初始化动作
        QMUIHelper.getTopbarCustomizer2().initTopBar(topBar, this);
    }

    public void setTopBarTitle(String title) {
        if (title != null && mTopBar != null) {
//            mTopBar.setTitle(title);
            mTopBar.toolBar().setTitle(title);
        }
    }

    @IdRes
    public int bindFragmentLayout() {
        return 0;
    }

    public FragmentLauncher getFragmentLauncher() {
        if (bindFragmentLayout() != 0 && fragmentLauncher == null) {
            fragmentLauncher = new FragmentLauncher(this, bindFragmentLayout());
            if (getTrustee() != null) {
                getTrustee().setFragmentLauncher(fragmentLauncher);
            }
        }
        return fragmentLauncher;
    }

    public DrawerLayout getDrawer() {
        return drawerLayout;
    }

    //-----------------------------------  Presenter  ----------------------------------------

    /**
     * 获取Presenter
     */
    public <T extends BasePresenter> T getPresenter(Class<T> clz) {
        return presenterHelper.getPresenter(clz);
    }

    //-----------------------------------  Fragment  ----------------------------------------

    /**
     * 打开一个Fragment
     */
    public void startFragment(Fragment fragment, boolean isOpenAnime) {
        if (getFragmentLauncher() != null) {
            FragmentLauncher.TransitionConfig config = null;
            if (isOpenAnime) {
                config = new FragmentLauncher.TransitionConfig(
                        R.anim.slide_open_enter, R.anim.slide_open_exit,
                        R.anim.slide_close_enter, R.anim.slide_close_exit);

            }
            getFragmentLauncher().startFragment(fragment, config, isOpenAnime);
        }
    }

    /**
     * 打开一个Fragment，且替换BackStack栈顶Fragment
     */
    public void startFragmentAndDestroyCurrent(final Fragment fragment, boolean isOpenAnime) {
        if (getFragmentLauncher() != null) {
            FragmentLauncher.TransitionConfig config = null;
            if (isOpenAnime) {
                config = new FragmentLauncher.TransitionConfig(
                        R.anim.slide_open_enter, R.anim.slide_open_exit,
                        R.anim.slide_close_enter, R.anim.slide_close_exit);

            }
            getFragmentLauncher().startFragmentAndDestroyCurrent(fragment, config);
        }
    }


    public void finishDelayed(int ms) {
        rootLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, ms);
    }


    public BaseTrustee bindTrustee() {
        return null;
    }

    public BaseTrustee getTrustee() {
        if (trustee == null) {
            trustee = bindTrustee();
        }
        return trustee;
    }


}
