package com.example.iot_controlhost.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.StringUtils;
import com.example.iot_controlhost.R;
import com.example.iot_controlhost.utils.DialogUtil;
import com.example.iot_controlhost.utils.global.Variable;

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

import es.dmoral.toasty.Toasty;
import me.jessyan.autosize.internal.CustomAdapt;

/**
 * Fragment基类
 *
 * @Author:DuanKaiji
 */
public abstract class BaseFragment<Binding extends ViewDataBinding, Presenter extends BasePresenter> extends Fragment implements CustomAdapt, View.OnClickListener {

    protected Binding binding;
    protected Presenter presenter;
    protected Context mContext;
    /**
     * 防抖
     */
    long lastClickTime;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Class<Binding> bindingClass = (Class<Binding>) ((ParameterizedType) type).getActualTypeArguments()[0];
            Class<Presenter> presenterClass = (Class<Presenter>) ((ParameterizedType) type).getActualTypeArguments()[1];
            try {
                Method inflateMethod = bindingClass.getMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
                binding = (Binding) inflateMethod.invoke(null, inflater, container, false);
                presenter = new ViewModelProvider(this).get(presenterClass);
//                presenter = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(requireActivity().getApplication())).get(presenterClass);
                binding.setLifecycleOwner(getViewLifecycleOwner());
            } catch (Exception e) {
                e.printStackTrace();
            }
            registerPresenter(presenter);
        }
        return binding.getRoot();
    }

    protected void registerPresenter(BasePresenter presenter) {
        presenter.getIsLoadingLiveData().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String msg) {
                if (StringUtils.isEmpty(msg)) {
                    DialogUtil.hideLoadingDialog();
                } else {
                    DialogUtil.showLoadingDialog(mContext, msg);
                }
            }
        });
        presenter.getErrorTips().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String msg) {
                error(msg);
            }
        });
        presenter.getSuccessTips().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String msg) {
                success(msg);
            }
        });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContext = getActivity();
        init();
        initListener();
    }

    /**
     * 初始化界面
     */
    public abstract void init();

    /**
     * 初始化监听器
     */
    public void initListener() {
    }

    @Override
    public final void onClick(View view) {
        //防抖拦截
        long now = System.currentTimeMillis();
        if (now - lastClickTime > Variable.CLICK_INTERVAL) {
            myClick(view);
        }
        lastClickTime = now;
    }

    /**
     * 点击事件
     * 会被防抖拦截
     *
     * @param view
     */
    public void myClick(View view) {
    }

    @Override
    public boolean isBaseOnWidth() {
        return true;
    }

    @Override
    public float getSizeInDp() {
        return 0;
    }

    protected <T> void fillDataInText(TextView textView, T data) {
        if (data == null) {
            textView.setText(getText(R.string.none));
        } else if (data instanceof Double && (Double) data == 0) {
            textView.setText(getText(R.string.none));
        } else if (data instanceof Integer && (Integer) data == 0) {
            textView.setText(getText(R.string.none));
        } else {
            textView.setText(data.toString());
        }
    }

    /**
     * 通用成功提示
     */
    public void success() {
        Toasty.success(mContext, getString(R.string.operate_success)).show();
    }

    public void success(String msg) {
        if (StringUtils.isEmpty(msg)) {
            success();
        } else {
            Toasty.success(mContext, msg).show();
        }
    }

    /**
     * 通用错误提示
     */
    public void error() {
        Toasty.error(mContext, getString(R.string.operate_fail)).show();
    }

    public void error(String msg) {
        if (StringUtils.isEmpty(msg)) {
            error();
        } else {
            Toasty.error(mContext, msg).show();
        }
    }

    /**
     * 开启加载中弹窗
     */
    public void showLoadingDialog(String msg) {
        DialogUtil.showLoadingDialog(mContext, msg);
    }

    /**
     * 关闭加载中弹窗
     */
    public void hideLoadingDialog() {
        DialogUtil.hideLoadingDialog();
    }
}
