package com.mayi.fastdevelop.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.mayi.fastdevelop.comnon.AppCallback;
import com.mayi.fastdevelop.util.ToastUtil;
import com.mayi.fastdevelop.view.LoadingDialog;

public abstract class BaseFragment extends Fragment {
    private Dialog dialog;

    /**
     * Fragment加载到Acrtivity中的Tag
     *
     * @return
     */
    public abstract String getFragmentTag();

    /**
     * 接收并处理数据
     *
     * @param data
     * @param callback
     */
    public abstract void receiveAndHandleInfo(String data, AppCallback<String> callback);

    /**
     * 发送消息给Acticity/Fragment
     *
     * @param tag  发送的目的地
     * @param data 发送的数据
     */
    public void sendInfo(String tag, String data, AppCallback<String> callback) {
        FragmentActivity activity = getActivity();
        if (activity instanceof BaseFragmentActivity) {
            BaseFragmentActivity fragmentActivity = (BaseFragmentActivity) activity;
            fragmentActivity.receiveInfo(tag, data, callback);
        } else {
            throw new RuntimeException("Activity必须继承BaseFragmentActivity");
        }
    }

    public void showLoadingDialog() {
        if (dialog == null) {
            dialog = LoadingDialog.init(getContext()).show();
        } else {
            dialog.show();
        }
    }

    public void dismssLoadingDialog() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 跳转页面并结束当前页面
     *
     * @param activity
     */
    public void gotoActivityAndFinish(Class activity) {
        Intent intent = new Intent(getContext(), activity);
        startActivity(intent);
        Activity a = getActivity();
        if (a != null) {
            a.finish();
        }
    }

    /**
     * 跳转页面
     *
     * @param activity
     */
    public void gotoActivity(Class activity) {
        Intent intent = new Intent(getContext(), activity);
        startActivity(intent);
    }

    /**
     * 跳转页面并结束当前页面
     *
     * @param activity
     */
    public void gotoActivityAndFinish(Class activity, Bundle bundle) {
        Intent intent = new Intent(getContext(), activity);
        intent.putExtras(bundle);
        startActivity(intent);
        Activity a = getActivity();
        if (a != null) {
            a.finish();
        }
    }

    /**
     * 跳转页面
     *
     * @param activity
     */
    public void gotoActivity(Class activity, Bundle bundle) {
        Intent intent = new Intent(getContext(), activity);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void showToast(String msg) {
        ToastUtil.show(getContext(), msg);
    }


    @Override
    public void onDestroyView() {
        dismssLoadingDialog();
        super.onDestroyView();
    }
}
