package com.maniu.mn_2020_6_11;

import android.os.Bundle;
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 android.widget.TextView;


public abstract class BaseFragment extends Fragment {

    public String mTextviewContent;
    public MainActivity mMainActivity;
    //根View
    public View view;
    //记录onCreateView有没有执行完毕
    private boolean isViewCreated = false;
    //当前Frgment是否是可见
    private boolean isShow = false;

    final String TAG = "MN---------->";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(getLayoutRes(), container, false);
        initView();
        return view ;
    }

    /**
     * 返回实现类的布局文件
     * @return
     */
    protected abstract int getLayoutRes();

    protected abstract void initView();

    /**
     * 当返回到当前页面的时候 重新刷新数据
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.e(TAG, "onViewCreated: setUserVisibleHint");
        isViewCreated = true;
        lazyLoad();
    }

    /**
     * 监听Fragment的隐藏与显示状态
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e(TAG, mTextviewContent+"setUserVisibleHint: "+isVisibleToUser);
        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
        if(isVisibleToUser){    //当前这个Fragment是显示的
            isShow = true;
            lazyLoad();
        }else{    //当前这个Fragment是隐藏的
            isShow = false;
        }
    }

    /**
     * 进行懒加载的方法
     */
    private void lazyLoad() {
        //这里进行双重标记判断,是因为setUserVisibleHint会多次回调,并且会在onCreateView执行前回调,必须确保onCreateView加载完毕且页面可见,才加载数据
        if(isViewCreated && isShow){
            loadData();

            isViewCreated = false;
            isShow = false;

            printLog(mTextviewContent+"可见,加载数据");
        }
    }


    /**
     * 加载数据
     */
    protected abstract void loadData();


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //页面销毁,恢复标记
        isShow = false;
        isViewCreated = false;
        printLog(mTextviewContent +"销毁了");
    }

    public void printLog(String logStr) {
        TextView logView = new TextView(getContext());
        logView.setText(logStr);
        mMainActivity.addLog(logView);
    }

    /**Fragment中TextView显示的内容*/
    protected abstract String getFragmentTextviewContent();
}
