package com.common.base;

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.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

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.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.utils.PresenterHoler;
import tech.starwin.utils.ui_utils.DialogFactory;
import tech.starwin.utils.ui_utils.QMUIHelper;
import com.common.widget.ProgressDialog;
import tech.starwin.utils.ui_utils.UIHelper;
import com.common.widget.TopBar;

/**
 * Created by SiKang on 2018/9/16.
 */
public abstract class BaseFragment extends Fragment implements IView {
    protected String TAG;
    private ViewGroup mContentView;

    /**
     * TopBar
     */
    private TopBar mTopBar;

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

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

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

    Object unBinder;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getName();
        lifecycleSubject.onNext(ActivityEvent.CREATE);
        presenterHelper = new PresenterHoler(this);
        progressDialog = new ProgressDialog(getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (mContentView != null) {
            ViewGroup parent = (ViewGroup) mContentView.getParent();
            if (parent != null) {
                parent.removeView(mContentView);
            }
            unBinder = LibConfig.bindView(this, mContentView);
        } else {
            mContentView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.base_activity_root, null);
            //是否使用沉浸式状态栏
            if (useTransparentStatusBar()) {
                QMUIStatusBarHelper.translucent(getActivity());
            }
            //判断是否要显示TopBar
            if (useTopBar()) {
                mTopBar = QMUIHelper.insertTopBar(mContentView, useTransparentStatusBar());
                if (mTopBar != null)
                    initTopBar(mTopBar);
            }
            LayoutInflater.from(getActivity()).inflate(bindLayout(), mContentView, true);
            unBinder = LibConfig.bindView(this, mContentView);
            initView(mContentView);
        }

        return mContentView;
    }

    public ViewGroup getContentView() {
        return mContentView;
    }

    @LayoutRes
    public abstract int bindLayout();

    /**
     * 初始化入口
     */
    public abstract void initView(ViewGroup contentView);

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

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

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


    //------------------------------------------- IView -------------------------------------------
    @Override
    public void onHttpStart(String action, boolean isShowLoading) {
        if (isShowLoading) {
            //500ms后如果还没有收到返回数据，显示loading
            progressDialog.setEnable(true);
            mContentView.postDelayed(() -> progressDialog.showLoading(), 500);
        }
    }

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

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


    //------------------------------------------- Lifecycle -------------------------------------------
    @Override
    public void onStart() {
        super.onStart();
        lifecycleSubject.onNext(ActivityEvent.START);
    }

    @Override
    public void onResume() {
        super.onResume();
        lifecycleSubject.onNext(ActivityEvent.RESUME);
    }

    @Override
    public void onPause() {
        super.onPause();
        lifecycleSubject.onNext(ActivityEvent.PAUSE);
        progressDialog.dissmissLoading();
    }

    @Override
    public void onStop() {
        super.onStop();
        lifecycleSubject.onNext(ActivityEvent.STOP);
    }

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

    public View findViewById(@IdRes int id) {
        return mContentView.findViewById(id);
    }

    @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);
    }


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

    public <T extends BasePresenter> T getPresenter(Class<T> clz) {
        return presenterHelper.getPresenter(clz);
    }

    public void startFragment(Fragment fragment, boolean isOpenAnime) {
        if (getActivity() instanceof BaseActivity)
            ((BaseActivity) getActivity()).startFragment(fragment, isOpenAnime);

    }

    public void startFragmentAndDestroyCurrent(Fragment fragment, boolean isOpenAnime) {
        if (getActivity() instanceof BaseActivity)
            ((BaseActivity) getActivity()).startFragmentAndDestroyCurrent(fragment, isOpenAnime);
    }
}
