package com.unis.sxzcl.base;

import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.NavController;
import androidx.navigation.NavDirections;
import androidx.navigation.NavOptions;
import androidx.navigation.Navigation;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewbinding.ViewBinding;

import com.google.gson.Gson;
import com.unis.model.Constant;
import com.unis.sxzcl.R;
import com.unis.sxzcl.databinding.ListEmptyLayoutBinding;
import com.unis.sxzcl.databinding.ListErrorLayoutBinding;
import com.unis.sxzcl.databinding.ListLoadingLayoutBinding;
import com.unis.sxzcl.widget.dialog.ProgressSysDialog;
import com.xyxsbj.mylibrary.tool.DPTool;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.SPTool;


/**
 * 包名: com.unis.sxzcl.base
 * 类名: BaseFragment
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/11/9 14:05
 * 更新人:
 * 更新时间: 2020/11/9 14:05
 * 更新说明:
 * 版本号: 1.0
 */
public abstract class BaseFragment<T extends ViewBinding> extends Fragment {

    private boolean active;

    public T mBinding;
    public View mRootView;
    private LinearLayout mEmptyView;
    private LinearLayout mLoadingView;
    private LinearLayout mErrorView;
    private ProgressSysDialog mProgressDialog;
    private Gson mGson;

    protected abstract T getViewBinding(LayoutInflater inflater, ViewGroup container);

    protected abstract void init();

    protected abstract void onFirstShow();

    protected void onShowFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mBinding = getViewBinding(inflater, container);
        mRootView = mBinding.getRoot();
        mRootView.setClickable(true);
        return mRootView;
    }

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

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        active = true;
        init();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        hideProgress();
        active = false;
    }

    public void setStatusBarWhite(boolean statusBarWhite) {
        FragmentActivity activity = getActivity();
        if (activity instanceof BaseActivity) {
            ((BaseActivity) activity).setStatusBarWhite(statusBarWhite);
        }
    }

    /**
     * 获取空布局
     */
    protected View getEmptyView(View.OnClickListener listener) {
        if (mEmptyView == null)
            mEmptyView = ListEmptyLayoutBinding.inflate(getLayoutInflater()).getRoot();
        if (listener != null)
            mEmptyView.setOnClickListener(listener);
        return mEmptyView;
    }

    /**
     * 获取等待布局
     */
    protected View getLoadingView() {
        if (mLoadingView == null)
            mLoadingView = ListLoadingLayoutBinding.inflate(getLayoutInflater()).getRoot();
        return mLoadingView;
    }

    /**
     * 获取错误布局
     */
    protected View getErrorView(View.OnClickListener listener) {
        //错误布局
        if (mErrorView == null)
            mErrorView = ListErrorLayoutBinding.inflate(getLayoutInflater()).getRoot();
        if (listener != null)
            mErrorView.setOnClickListener(listener);
        return mErrorView;
    }

    /**
     * 初始化刷新控件
     */
    protected void initRefreshView(SwipeRefreshLayout refreshLayout,
                                   SwipeRefreshLayout.OnRefreshListener listener) {
//        refreshLayout.setColorSchemeResources(R.color.colorTheme, R.color.colorThemeL);
        refreshLayout.setColorSchemeResources(R.color.colorTheme);
        refreshLayout.setOnRefreshListener(listener);
    }

    protected void showProgress(String msg, boolean isTouch) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressSysDialog(getContext());
        }
        if (msg == null)
            msg = "请等待...";
        mProgressDialog.setMessage(msg);
        mProgressDialog.getDialog().setCancelable(isTouch);
        if (!mProgressDialog.getDialog().getDialog().isShowing())
            mProgressDialog.show();
    }

    protected void showProgress(String msg) {
        showProgress(msg, true);
    }

    protected void hideProgress() {
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
    }

    public void onBack() {
        Navigation.findNavController(getView()).popBackStack();
    }


    public void finish() {
        if (isActive())
            getActivity().finish();
    }

    public boolean isActive() {
        return active;
    }


    /**
     * 获取WebView文字大小
     */
    public static int getWebTextZoom() {
        String mThemeFlag = SPTool.getString(Constant.KEY_TEXT_SIZE, "2");
        int zoom = 100;
        switch (mThemeFlag) {
            case "1":
                zoom = 90;
                break;
            case "2":
                zoom = 100;
                break;
            case "3":
                zoom = 110;
                break;
            case "4":
                zoom = 120;
                break;
            case "5":
                zoom = 130;
                break;
            case "6":
                zoom = 140;
                break;
        }
        return zoom;
    }

    public Gson getGson() {
        if (mGson == null)
            mGson = new Gson();
        return mGson;
    }

    public int getStatusHeight() {
        //获取状态栏高度
        int height = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            height = getResources().getDimensionPixelSize(resourceId);
        }
        LogTool.i("状态栏高度:" + height);
        return height;
    }

    /************************ Fragment导航方法 ************************/
    public void navigation(@IdRes int resId) {
        navigation(getView(), resId, null);
    }

    public void navigation(View view, @IdRes int resId) {
        navigation(view, resId, null);
    }

    public void navigation(@IdRes int resId, Bundle bundle) {
        navigation(getView(), resId, bundle);
    }

    public void navigation(View view, @IdRes int resId, Bundle bundle) {
        if (bundle == null) {
            bundle = new Bundle();
        }
        NavOptions options = new NavOptions.Builder()
                .setLaunchSingleTop(true)
//                .setEnterAnim(R.anim.slide_in_right)
//                .setExitAnim(R.anim.slide_out_left)
//                .setPopEnterAnim(R.anim.slide_in_left)
//                .setPopExitAnim(R.anim.slide_out_right)
                .build();

        NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
        navController.navigate(resId, bundle, options);
    }

    public void navigation(NavDirections directions) {
        NavOptions options = new NavOptions.Builder()
                .setLaunchSingleTop(true)
//                .setEnterAnim(R.anim.slide_in_right)
//                .setExitAnim(R.anim.slide_out_left)
//                .setPopEnterAnim(R.anim.slide_in_left)
//                .setPopExitAnim(R.anim.slide_out_right)
                .build();

        NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment);
        navController.navigate(directions, options);
    }


    /************************ 获取Res资源 ************************/
    public int getAttrForResId(int resId) {
        TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(new int[]{resId});
        return DPTool.px2sp(getContext(), typedArray.getDimension(0, 0));
    }

    public int getColorForResId(int resId) {
        return ContextCompat.getColor(getContext(), resId);
    }


    /************************ 懒加载逻辑 ************************/
    //Fragment onHiddenChanged方法值 默认false(未隐藏)
    private boolean isHidden;

    //Fragment onResume方法 默认false(未显示)
    private boolean isResume;

    //ViewPager+Fragment时的 setUserVisibleHint方法
    //默认true(已显示) 只有ViewPager+Fragment才会修改值
    private boolean isVisibleToUser = true;

    //第一次加载
    public boolean isFirstLoad = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        lazyData();
    }

    @Override
    public void onResume() {
        super.onResume();
        isResume = true;
        lazyData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        lazyData();
    }

    private void lazyData() {
        //已执行resume  已显示当前页面  未隐藏Fragment  第一次加载
        if (isResume && isVisibleToUser && !isHidden && isFirstLoad) {
            onFirstShow();
            isFirstLoad = false;
        }
        if (isResume && isVisibleToUser && !isHidden) {
            onShowFragment();
        }
    }


}
