package com.sjkj.base_lib.view;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleObserver;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.sjkj.base_lib.weight.LoadingDialog;

public abstract class BaseFragment extends Fragment implements BaseFragmentCallBack, LifecycleObserver {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = initBinding(inflater, container, savedInstanceState);
        initView();
        initListener();
        loadData();
        return rootView;
    }


    //布局
    protected abstract int initLayout();

    /**
     * 绑定当前页面
     *
     * @return
     */
    protected ViewDataBinding getViewDataBing(LayoutInflater inflater, ViewGroup container) {
        return DataBindingUtil.inflate(inflater, initLayout(), container, false);
    }


    public void finishRefreshOrLoadMore(RefreshLayout refreshLayout) {
        if (refreshLayout == null) {
            return;
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh();
        }
        if (refreshLayout.getState() == RefreshState.Loading) {
            refreshLayout.finishLoadMore();
        }
    }


    private LoadingDialog dialog;

    public void showLoadingDialog() {
        if (dialog == null)
            dialog = new LoadingDialog(getActivity());
        dialog.showDialog();
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);
    }

    public void hideLoadingDialog(int code) {
        if (code == LoadingDialog.LOADING_SUCCESS) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != dialog && dialog.isShowing()) {
                        dialog.hideDialog();
                    }
                }
            }, 300);

        } else {
            if (null != dialog && dialog.isShowing()) {
                dialog.hideDialog();
            }
        }


    }

}
