package com.example.iot_controlhost.base;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ViewDataBinding;
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 com.example.iot_controlhost.utils.log.MyLog;

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;

/**
 * Activity基类
 */
public abstract class BaseActivity<Binding extends ViewDataBinding, Presenter extends BasePresenter> extends AppCompatActivity implements CustomAdapt, View.OnClickListener {

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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        initTransition();
        super.onCreate(savedInstanceState);
        mContext = this;
        Type type = this.getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Class<Binding> bindingClass = (Class<Binding>) ((ParameterizedType) type).getActualTypeArguments()[0];
            Class<Presenter> controllerClass = (Class<Presenter>) ((ParameterizedType) type).getActualTypeArguments()[1];
            try {
                Method inflateMethod = bindingClass.getMethod("inflate", LayoutInflater.class);
                binding = (Binding) inflateMethod.invoke(null, getLayoutInflater());
                presenter = new ViewModelProvider(this).get(controllerClass);
//                presenter = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(controllerClass);
                binding.setLifecycleOwner(this);
                registerPresenter(presenter);
            } catch (Exception e) {
                MyLog.appError("BaseActivity初始化失败:" + e.getMessage());
                e.printStackTrace();
            }
            setContentView(binding.getRoot());
            initView();
            initListener();
            setFullScreen(true);
        }
    }

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

    /**
     * 开启加载中弹窗
     * 在IO线程中调用的
     */
    public void showLoadingDialogInIO(String msg) {
        DialogUtil.showLoadingDialogInIO(mContext, msg);
    }

    /**
     * 开启加载中弹窗
     * 在IO线程中调用的
     */
    public void showLoadingDialog(String msg) {
        DialogUtil.showLoadingDialog(mContext, msg);
    }

    /**
     * 开启加载中弹窗
     * 在IO线程中调用的
     */
    public void hideLoadingDialog() {
        DialogUtil.hideLoadingDialog();
    }

    public void setFullScreen(boolean isFullScreen) {
        if (isFullScreen) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11 及以上 (API 30+)
                getWindow().setDecorFitsSystemWindows(false);
                getWindow().getInsetsController().hide(WindowInsets.Type.navigationBars());
            } else {
                // Android 7.1 - 10 (API 25 - 29)
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |  // 隐藏导航栏
                                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | // 沉浸模式
                                View.SYSTEM_UI_FLAG_FULLSCREEN        // 全屏
                );
            }
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        }
    }

    /**
     * 初始化转场动画
     */
    protected void initTransition() {
    }

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

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

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

    /**
     * 点击事件
     * 会被防抖拦截，需要的子类可以按需重写，可选
     */
    public void myClick(View view) {
    }

    /**
     * 屏幕自适应
     */
    @Override
    public boolean isBaseOnWidth() {
        return true;
    }

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

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

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

    }

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

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

    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());
        }
    }

}

