/**
 * @Title: BaseFragment.java
 * @Package com.sto.fingersupervise.common
 * @Description: TODO(用一句话描述该文件做什么)
 * @author admin
 * @date 2016年8月24日 下午4:06:32
 * @version V1.0
 */
package com.fxy.baselibrary.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jaeger.library.StatusBarUtil;
import com.fxy.baselibrary.R;
import com.fxy.baselibrary.pagemanager.MyPageListener;
import com.fxy.baselibrary.pagemanager.MyPageManager;
import com.fxy.baselibrary.util.StringUtils;

import java.lang.reflect.Field;

import es.dmoral.toasty.Toasty;
import me.yokeyword.fragmentation.SupportFragment;


/**
 * @author admin
 * @version V1.0
 * @Title: BaseFragment.java
 * @Package com.sto.fingersupervise.common
 * @Description: TODO
 * @date 2016年8月24日 下午4:06:32
 */
public abstract class BaseFragment extends SupportFragment {
//    protected ImmersionBar mImmersionBar;
    public static final String BROADCAST_ACTION_UPDATE_DATA = "updateData";
    protected LayoutInflater inflater;
    private View rootView;
    private Context context;
    private ViewGroup container;
    protected RelativeLayout tb_rl;
    protected RelativeLayout rl_top;
    private InputMethodManager inputMethodManager;

    // 左侧
    protected ImageView tb_iv_left;
    protected TextView tb_tv_left;

    // 右侧
    protected TextView tb_tv_right;
    protected ImageView tb_iv_right;

    // 标题
    protected TextView tb_tv_title;
    protected LinearLayout contentLayout;
    protected AppCompatEditText editText;
    protected SearchView mSearchView;
    private static final int titleMaxLength = 11;
    MyPageManager pageStateManager;
    private TextView txt_content;
    /**
     * 加载框
     */
    public Dialog loadDialog;
    private LinearLayout ll_base_root;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity().getApplicationContext();
    }

    protected static Activity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        this.inflater = inflater;
//        this.container = container;
//        onCreateView(savedInstanceState);

        if (null != getArguments()) {
            getBundleExtras(getArguments());
        }
        if (rootView == null) {
            ViewStub mVs_toolbar ;
            FrameLayout fl_container;
            //为空时初始化。
            if (showToolBar() && getToolBarResId() != 0) {
                //如果需要显示自定义toolbar,并且资源id存在的情况下，实例化baseView;
                rootView = inflater.inflate(R.layout.ac_base, container, false);//根布局
                ll_base_root = (LinearLayout) rootView.findViewById(R.id.ll_base_root);
                 mVs_toolbar = (ViewStub) rootView.findViewById(R.id.vs_toolbar);//toolbar容器
                 fl_container = (FrameLayout) rootView.findViewById(R.id.fl_container);//子布局容器
                mVs_toolbar.setLayoutResource(getToolBarResId());//toolbar资源id
                mVs_toolbar.inflate();//填充toolbar
                inflater.inflate(getLayoutRes(), fl_container, true);//子布局
                if (getToolBarResId() == R.layout.layout_common_toolbar) {
                    tb_rl = (RelativeLayout) findViewById(R.id.tb_rl);
                    rl_top = (RelativeLayout) findViewById(R.id.rl_top);
                    tb_iv_left = (ImageView) findViewById(R.id.tb_iv_left);
                    tb_tv_right = (TextView) findViewById(R.id.tb_tv_right);
                    tb_tv_left = (TextView) findViewById(R.id.tb_tv_left);
                    tb_iv_right = (ImageView) findViewById(R.id.tb_iv_right);
                    tb_tv_title = (TextView) findViewById(R.id.tb_tv_title);
                    mSearchView = (SearchView) findViewById(R.id.search_view);
                }
            } else {
                //不显示通用toolbar
                rootView = inflater.inflate(R.layout.ac_base, container, false);//根布局
                ll_base_root = (LinearLayout) rootView.findViewById(R.id.ll_base_root);
                 mVs_toolbar = (ViewStub) rootView.findViewById(R.id.vs_toolbar);//toolbar容器
                 fl_container = (FrameLayout) rootView.findViewById(R.id.fl_container);//子布局容器
                inflater.inflate(getLayoutRes(), fl_container, true);//子布局
            }
            if (isInitState()) {

                pageStateManager = MyPageManager.init(fl_container, new MyPageListener() {
                    @Override
                    protected void onReallyRetry() {
                        retry();

                    }

                    @Override
                    public void onEmtptyViewClicked(View emptyView) {
                        super.onEmtptyViewClicked(emptyView);

                        retry();
                    }
                });
            }

        }
        initView(rootView);
        return rootView;

    }
    /**
     * @return 是否需要状态切换
     */
    public boolean isInitState() {
        return false;
    }

    protected void showContent() {
        pageStateManager.showContent();
    }

    protected void showEmptyView() {
        showEmptyView(getString(R.string.page_empty));

    }

    /**
     * @param content 内容为空时的提示
     */
    protected void showEmptyView(String content) {
        pageStateManager.showEmpty(content);

    }

    protected void showErrorView() {
        showErrorView(getString(R.string.page_load_error));
    }

    /**
     * @param content 错误提示
     */
    protected void showErrorView(String content) {
        pageStateManager.showError(content);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);

        initLogic();
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (immersionEnabled()) {
            immersionInit();
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
    }

    /**
     * 当前页面Fragment支持沉浸式初始化。默认返回false，可设置支持沉浸式初始化
     * Immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean immersionEnabled() {
        return true;
    }

    /**
     * 状态栏初始化（immersionEnabled默认为false时不走该方法）
     */
    protected void immersionInit() {

        StatusBarUtil.setColor(mActivity, ContextCompat.getColor(mActivity,R.color.md_blue_500),0);
//        mImmersionBar = ImmersionBar.with(this);
//        mImmersionBar.init();   //所有子类都将继承这些相同的属性
    }

    /**
     * 是否显示通用toolBar
     */
    public boolean showToolBar() {
        return false;
    }

    /**
     * 获取自定义toolbarview 资源id 默认为0，showToolBar()方法必须返回true才有效
     */
    public int getToolBarResId() {
        return R.layout.layout_common_toolbar;
    }

    /**
     * 获取布局文件
     */
    protected abstract int getLayoutRes();

    /**
     * 初始化view
     */
    protected abstract void initView(View rootView);

    /**
     * 获取bundle信息
     *
     * @param bundle
     */
    protected abstract void getBundleExtras(Bundle bundle);

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (mImmersionBar != null)
//            mImmersionBar.destroy();
    }

    /**
     * 获取数据失败状态下的点击事件
     */
    public void retry() {

    }

    /**
     * 逻辑内容初始化，懒加载模式
     */
    protected abstract void initLogic();

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        rootView = null;
        container = null;
        inflater = null;
        dismissLoadDialog();
    }

    public Context getApplicationContext() {
        return context;
    }

    public void setRootView(int layoutResID) {
        setRootView(inflater.inflate(layoutResID, container, false));
    }

    public void setRootView(View view) {
        rootView = view;
    }

    public View getRootView() {
        return rootView;
    }

    public View findViewById(int id) {
        if (rootView != null) {
            return rootView.findViewById(id);
        }
        return null;
    }

    /**
     * 创建加载框
     */
    public void createLoadDialog(Context context) {
        // loadDialog = new ProgressDialog(context);// 创建加载框
        // loadDialog.setMessage("正在加载中，请稍候...");// 设置显示的消息
        // loadDialog.setCancelable(true);// 设置是否可以取消
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.view_progress_dialog, null);// 得到加载view
//		SpinnerLoading iv=( SpinnerLoading )v.findViewById( R.detailId.iv_progress );
//		iv.setPaintMode(1);
//		iv.setCircleRadius(5);
//		iv.setItemCount(8);
//		iv.setImageDrawable(new LoadingDrawable(new MaterialLoadingRenderer(context)));
        loadDialog = new Dialog(context, R.style.MyProgressDialog);// 创建自定义样式dialog

        loadDialog.setCancelable(true);// 不可以用“返回键”取消
        loadDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
//		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
//				DisplayUtil.getDisplayMetrics().x * 6 / 13,DisplayUtil.getDisplayMetrics().y * 2 / 13);
        loadDialog.setContentView(v, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
        loadDialog.show();
    }


    /**
     * 显示加载框
     */
    protected void showLoadDialog() {
        showLoadDialog(getString(R.string.loading), false);
    }

    /**
     * 显示加载框
     */
    protected void showLoadDialog(String content) {
        showLoadDialog(content, false);
    }

    /**
     * 显示加载框
     */
    protected void showLoadDialog(String content, boolean iscancel) {
        if (loadDialog != null) {
            loadDialog.setCancelable(iscancel);
            if (!loadDialog.isShowing()) {
                ((TextView)loadDialog.findViewById(R.id.txt_content)).setText(content);
                loadDialog.show();
            }
        } else {
            createLoadDialog(context);
        }
    }

    /**
     * 加载框消失
     */
    protected void dismissLoadDialog() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    /**
     * 页面跳转
     */
    protected static void intent2Page(Activity act, Class<?> act2, boolean isFinish) {
        Intent missionIntent = new Intent(act, act2);
        act.startActivity(missionIntent);
        if (isFinish) {
            act.finish();
        }
    }

    /**
     * 页面跳转
     * @param isFinish 是否关闭act界面
     */
    protected static void intent2Page(Activity act, Class<?> act2, boolean isFinish, Bundle bundle) {
        Intent missionIntent = new Intent(act, act2);
        if (bundle != null) {
            missionIntent.putExtras(bundle);
        }
        act.startActivity(missionIntent);
        if (isFinish) {
            act.finish();
        }
    }

    /**
     * 页面跳转
     */
    protected static void intent2Page(Class<?> act2, boolean isFinish) {
        Intent missionIntent = new Intent(mActivity,act2);
        mActivity.startActivity(missionIntent);
        if (isFinish) {
            mActivity.finish();
        }
    }

    protected void setTitleName(String title) {
        if (tb_tv_title != null) {
            if (!TextUtils.isEmpty(title)) {
                if (title.length() > titleMaxLength) {
                    tb_tv_title.setText(title.substring(0, titleMaxLength - 1) + "...");
                } else {
                    tb_tv_title.setText(title);
                }
            }
        }
    }

    protected void showToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.normal(context, content).show();
        }
    }

    protected void showErrorToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.error(context, content).show();
        }
    }

    protected void showSuccessToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.success(context, content).show();
        }
    }

    protected void showInfoToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.info(context, content).show();

        }
    }

    protected void showWarningToast(String content) {
        if (!StringUtils.isEmpty(content)) {
            Toasty.warning(context, content).show();

        }
    }

    protected void showIconToast(String content, int img) {
        Drawable icon = ContextCompat.getDrawable(context, img);
        if (!StringUtils.isEmpty(content)) {
            Toasty.normal(context, content, icon).show();

        }
    }


    // http://stackoverflow.com/questions/15207305/getting-the-error-java-lang-illegalstateexception-activity-has-been-destroyed
    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
