package com.kfzs.cfyl.media;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * Created by realicing on 2018/12/6.
 * realicing@sina.com
 */
public abstract class BaseFragment extends Fragment {

    protected View mView;
    /**
     * 是否是第一次初始化，防止重复加载些东西用
     */
    protected boolean mIsFirstInit = true;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }


    /**
     * 注意用 mIsFirstInit 判断，防止重复加载
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mView == null) {
            mIsFirstInit = true;
            mView = inflater.inflate(getLayoutId(), null);
        } else {
            mIsFirstInit = false;
        }
        return mView;
    }


    public abstract int getLayoutId();

    public abstract void onViewCreated();

    /**
     * 一般要继承这个方法
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onViewCreated();
    }

    protected boolean firstVisibleToUser = true;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && mView != null) {
            if (firstVisibleToUser) {
                initViewOnVisibleToUser();
            }
            initDataOnVisibleToUser();
            firstVisibleToUser = false;
        }
    }

    protected void initViewOnVisibleToUser() {

    }

    protected void initDataOnVisibleToUser() {

    }

    /**
     * 万能的找View类
     *
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T findViewById(@IdRes int id) {
        if(mView != null)
            return mView.findViewById(id);
        return null;
    }

}
