package com.ttstd.dialer.base.mvvm.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.ttstd.dialer.base.BaseDialogFragment;
import com.ttstd.dialer.base.BaseFragment;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;

/**
 * @author: lml
 * @date: 2021/12/15
 */
public abstract class BaseMvvmDialogFragment<VM extends ViewModel, VDB extends ViewDataBinding> extends BaseDialogFragment {
    protected String mTag = this.getClass().getSimpleName();
    /**
     * 是否顯示了
     */
    protected boolean mIsVisible;
    /**
     * 是否準備好了-Created
     */
    protected boolean mHasPrepare;


    protected VM mViewModel;
    protected VDB mViewDataBinding;
    protected Class<VM> vmClass;
    //
//    protected Toolbar toolbar;
//    protected View statusBarView;
    //
    protected Bundle bundle;//来自getArguments()
    protected Bundle savedInstanceState;

//    protected Context context;

    /**
     * 上下文
     */
    private WeakReference<Context> ctx;

    public Context getCtx() {
        return ctx == null ? null : ctx.get();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
//        this.context = context;
        ctx = new WeakReference<>(context);
    }

    /**
     * onCreate、onResume里不能调用
     *
     * @return
     */
    public boolean isAttached() {
        boolean flag = getCtx() != null && isAdded();
        Log.e(" >> isAttached >>", "flag = " + flag);
        return flag;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //ViewDataBinding
        mViewDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false);
        mViewDataBinding.setLifecycleOwner(this);

        //ViewModel
        vmClass = (Class<VM>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        mViewModel = new ViewModelProvider(this).get(vmClass);
        //
        return mViewDataBinding.getRoot();
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

//        if (initStatusBarToolBar()) {
//            toolbar = getToolbar();
//        }
        //注册eventbus
//        if (getClass().isAnnotationPresent(BindEventBus.class))
//            EventBusManager.register(this);
        //

//        fitsLayoutOverlap();
        initDataBinding();
        initView(bundle = getArguments());
        //
        initData(this.savedInstanceState = savedInstanceState);
        //
        if (mIsVisible) {
            onEnter();
        }
        mHasPrepare = true;
        //
//        LiveDataBus.get().with(ConstantUtils.DATA_BUS_LOADING_FRAGMENT, Boolean.class).observe(getActivity(), bool -> {
//            L.e(" >> LiveDataBus >> DATA_BUS_LOADING_FRAGMENT: %s", bool);
//            if(bool) {
//                showLoading(R.string.str_please_wait);
//            } else {
//                hideLoading();
//            }
//        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mHasPrepare = false;
        mViewDataBinding = null;
        //移除eventbus
//        if (getClass().isAnnotationPresent(BindEventBus.class))
//            EventBusManager.unregister(this);
        //
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (mIsVisible == getUserVisibleHint())
            return;
        mIsVisible = getUserVisibleHint();
        if (mIsVisible) {
            if (!mHasPrepare)
                return;
            onEnter();
        } else {
            onExit();
        }
    }

    @LayoutRes
    protected abstract int getLayoutId();

//    protected abstract Toolbar getToolbar();

//    protected View getStatusView() {
//        return null;
//    }

    protected abstract void initDataBinding();

    protected abstract void initView(Bundle bundle);

    protected abstract void initData(Bundle savedInstanceState);

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        fitsLayoutOverlap();
    }

//    protected boolean isImmersionBarEnabled() {
//        return true;
//    }

//    protected boolean initStatusBarToolBar() {
//        return true;
//    }


//    private void fitsLayoutOverlap() {
//        if (!isImmersionBarEnabled()) return;
//        if (statusBarView != null) {
//            ImmersionBar.setStatusBarView(getActivity(), statusBarView);
//        }
//        if (toolbar != null) {
//            ImmersionBar.setTitleBar(getActivity(), toolbar);
//        }
//    }

    protected void hideInputMethod(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = activity.getCurrentFocus();
        if (view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    protected void hideInputMethod(Activity activity, EditText editText) {
        InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
        View view = activity.getCurrentFocus();
        if (view != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void showInputMethod(EditText editText) {
        InputMethodManager imm = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
    }


//    private CustomDialog mWaitDialog;
//
//    public void showLoading(@StringRes int contentID) {
//        showLoading(contentID, R.color.white);
//    }
//
//    public void showLoading(@StringRes int contentID, @ColorRes int color) {
//        hideLoading();
//        DialogX.init(getActivity());
//        if (color == R.color.white) {
//            mWaitDialog = DialogXUtil.getInstance().showLoading(getActivity(), getString(contentID), getResources().getColor(color));
//        } else {
//            mWaitDialog = DialogXUtil.getInstance().showLoading_black(getActivity(), getString(contentID), getResources().getColor(color));
//        }
//    }
//
//    public void updateLoadingTip(@StringRes int messageID, int percent) {
//        try {
//            if (mWaitDialog != null && mWaitDialog.isShow()) {
//                TextView tvTip = mWaitDialog.getCustomView().findViewById(R.id.tv_load_tip);
//                if (tvTip != null)
//                    tvTip.setText(getResources().getString(messageID) + (percent == -1 ? "" : percent + "%"));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    public boolean isShowLoading() {
//        return mWaitDialog != null && mWaitDialog.isShow();
//    }
//
//    public void hideLoading() {
//        try {
//            boolean isShow = isShowLoading();
//            L.d(" >> hideLoading :: isShow: %s", isShow);
//            if (isShow)
//                mWaitDialog.dismiss();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 進入界面
     */
    protected void onEnter() {

    }

    /**
     * 離開界面
     */
    protected void onExit() {

    }

}
