package com.dahe.mylibrary.base;


import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.dahe.mylibrary.R;
import com.dahe.mylibrary.callback.RefreshCallBack;
import com.dahe.mylibrary.utils.StatusBar;
import com.dahe.mylibrary.utils.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

import qiu.niorgai.StatusBarCompat;

/**
 * <p>
 * Fragment基类，封装了懒加载的实现
 * <p>
 * 1、Viewpager + Fragment情况下，fragment的生命周期因Viewpager的缓存机制而失去了具体意义
 * 该抽象类自定义一个新的回调方法，当fragment可见状态改变时会触发的回调方法
 *
 * @see #onFragmentVisibleChange(boolean)
 * @see #onFragmentFirstVisible()
 */
public abstract class BaseFragment<VB extends ViewBinding> extends Fragment {
    private boolean isFragmentVisible;
    private boolean isReuseView;
    private boolean isFirstVisible;
    private boolean isPause;
    private View rootView;
    private static final String TAG = "BaseFragment";
    protected Context mContext;
    protected int mRefreshPage = 1;
    protected int mRefreshCount = 20;
    protected Toolbar mToolbar;
    protected final int DEFAULT_STATUS_BAR_ALPHA = 0;

    public VB binding;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Log.i(TAG, "onViewCreated: " + (rootView == null) + "---getUserVisibleHint()" + getUserVisibleHint() + "---isFirstVisible" + isFirstVisible);
        //如果setUserVisibleHint()在rootView创建前调用时，那么
        //就等到rootView创建完后才回调onFragmentVisibleChange(true)
        //保证onFragmentVisibleChange()的回调发生在rootView创建完成之后，以便支持ui操作
        if (rootView == null) {
            rootView = view;
            if (getUserVisibleHint()) {
                if (isFirstVisible) {
                    onFragmentFirstVisible();
                    isFirstVisible = false;
                }

                onFragmentVisibleChange(isFirstVisible);
                isFragmentVisible = true;
            }
        }
        super.onViewCreated(isReuseView && rootView != null ? rootView : view, savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        try {
            Class<VB> cls = (Class<VB>) superClass.getActualTypeArguments()[0];
            Method method = cls.getMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.TYPE);
            method.setAccessible(true);
            binding = (VB) method.invoke(null, inflater,container, Boolean.FALSE);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        if (binding!=null&&binding.getRoot()!=null) {
            mContext = getActivity();
            return binding.getRoot();
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    /**
     * 标题栏的颜色 文字白色
     */
    public void setStatusBarCancelLightColor() {
        StatusBar.cancelLightStatusBar(getActivity());
    }

    /**
     * 设置沉浸式标题栏 标题栏的颜色
     */
    public void setStatusBarColor(int color) {
        StatusBarCompat.setStatusBarColor(getActivity(), ContextCompat.getColor(mContext, color), DEFAULT_STATUS_BAR_ALPHA);
        StatusBar.changeToLightStatusBar(getActivity());
    }

    /**
     * 设置沉浸式标题栏 里面是Fragment
     */
    public void setStatusBarColorInFragment() {
        StatusBarCompat.translucentStatusBar(getActivity());
    }

    public void setStatusBarColorToLight() {
        StatusBar.translucentStatusBar(getActivity(), true);
        StatusBar.changeToLightStatusBar(getActivity());
    }

    @Override
    public void onDestroy() {
        initVariable();
        super.onDestroy();
    }


    protected void showToast(Object message) {
        ToastUtils.showToast(mContext, message instanceof String ? message + "" : getResources().getString((int) message));
    }

    /**
     * 设置刷新控件
     *
     * @param refreshLayout
     * @param callBack      访问网络回调
     */
    protected void setRefresh(final SmartRefreshLayout refreshLayout, final RefreshCallBack callBack) {
        refreshLayout.setEnableOverScrollDrag(true)
                .setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mRefreshPage++;
                        callBack.getRefreshDate(2, mRefreshPage, mRefreshCount);
                    }

                    @Override
                    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                        mRefreshPage = 1;
                        callBack.getRefreshDate(1, mRefreshPage, mRefreshCount);
                    }
                });
    }

    /**
     * 网络访问完成 刷新控件
     *
     * @param refreshLayout
     * @param isLoadMore    false禁用下拉加载更多
     */
    protected void setFinishRefresh(final SmartRefreshLayout refreshLayout, boolean isLoadMore) {
        if (refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh();
        else if (refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore();
        if (!isLoadMore){
            refreshLayout.finishLoadMore();      //加载完成
            refreshLayout.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
        }
//        refreshLayout.setEnableLoadMore(isLoadMore);
    }

    /**
     * 设置标题
     */

    protected void setTitleBar(String title, View.OnClickListener listener) {
        mToolbar = (Toolbar) rootView.findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title))
            ((TextView) rootView.findViewById(R.id.common_toolBar_title)).setText(title);
        mToolbar.setNavigationIcon(R.drawable.black_back);
        mToolbar.setNavigationOnClickListener(listener);
    }

    /**
     * 设置标题
     */

    protected void setTitleBar(String title) {
        mToolbar = (Toolbar) rootView.findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title))
            ((TextView) rootView.findViewById(R.id.common_toolBar_title)).setText(title);
    }

    /**
     * 设置标题
     */

    protected void setTitleBar(String title, boolean isRight, View.OnClickListener listener) {
        mToolbar = (Toolbar) rootView.findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title)) {
            ((TextView) rootView.findViewById(R.id.common_toolBar_title)).setText(title);
            ((RelativeLayout) rootView.findViewById(R.id.rlMessage)).setVisibility(isRight ? View.VISIBLE : View.GONE);
            (rootView.findViewById(R.id.rlMessage)).setOnClickListener(listener);
        }
    }

    /**
     * 设置标题
     */

    protected void setTitleBar(String title, boolean isRight,String message, View.OnClickListener listener) {
        mToolbar = (Toolbar) rootView.findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title)) {
            ((TextView) rootView.findViewById(R.id.common_toolBar_title)).setText(title);
            ((RelativeLayout) rootView.findViewById(R.id.rlMessage)).setVisibility(isRight ? View.VISIBLE : View.GONE);
            ((TextView) rootView.findViewById(R.id.tvMessage)).setText(message);
            (rootView.findViewById(R.id.rlMessage)).setOnClickListener(listener);
        }
    }

    /**
     * 设置标题
     */

    protected void setBadView(boolean isRight) {
        if (null != ((TextView) rootView.findViewById(R.id.tvCount))) {
            ((TextView) rootView.findViewById(R.id.tvCount)).setVisibility(isRight ? View.VISIBLE : View.GONE);
        }
    }

    protected void setCount(int count) {
        if (count > 100) {
            ((TextView) rootView.findViewById(R.id.tvCount)).setText("99··");
        } else {
            ((TextView) rootView.findViewById(R.id.tvCount)).setText(count + "");
        }

    }


    //setUserVisibleHint()在Fragment创建时会先被调用一次，传入isVisibleToUser = false
    //如果当前Fragment可见，那么setUserVisibleHint()会再次被调用一次，传入isVisibleToUser = true
    //如果Fragment从可见->不可见，那么setUserVisibleHint()也会被调用，传入isVisibleToUser = false
    //总结：setUserVisibleHint()除了Fragment的可见状态发生变化时会被回调外，在new Fragment()时也会被回调
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        Log.i(TAG, "isFirstVisible: " + isFirstVisible + "--isVisibleToUser" + isVisibleToUser + "--rootView == null" + (rootView == null));
        super.setUserVisibleHint(isVisibleToUser);
        //setUserVisibleHint()有可能在fragment的生命周期外被调用
        if (rootView == null) {
            return;
        }
        if (isFirstVisible && isVisibleToUser) {
            onFragmentFirstVisible();
            isFirstVisible = false;
            isFragmentVisible = true;
            return;
        }
        if (isVisibleToUser) {
            onFragmentVisibleChange(true);
            isFragmentVisible = true;
            return;
        }
        if (isFragmentVisible) {
            isFragmentVisible = false;
            onFragmentVisibleChange(false);
        }
    }

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


    private void initVariable() {
        isFirstVisible = true;
        isFragmentVisible = false;
        isPause = false;
        rootView = null;
        isReuseView = true;
    }

    @Override
    public void onPause() {
        isPause = true;
        super.onPause();
    }

    @Override
    public void onResume() {
        if (isPause && getUserVisibleHint())
            onFragmentVisibleChange(true);
        super.onResume();
    }

    /**
     * @param isReuse
     */
    protected void reuseView(boolean isReuse) {
        isReuseView = isReuse;
    }

    /**
     * 去除setUserVisibleHint()多余的回调场景，保证只有当fragment可见状态发生变化时才回调
     * 回调时机在view创建完后，所以支持ui操作，解决在setUserVisibleHint()里进行ui操作有可能报null异常的问题
     * <p>
     * 可在该回调方法里进行一些ui显示与隐藏
     *
     * @param isVisible true  不可见 -> 可见
     *                  false 可见  -> 不可见
     */
    protected abstract void onFragmentVisibleChange(boolean isVisible);

    /**
     * 在fragment首次可见时回调，可用于加载数据，防止每次进入都重复加载数据
     */
    protected abstract void onFragmentFirstVisible();

    protected boolean isFragmentVisible() {
        return isFragmentVisible;
    }
}