package com.dahe.mylibrary.base;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.viewbinding.ViewBinding;

import com.dahe.mylibrary.R;
import com.dahe.mylibrary.callback.RefreshCallBack;
import com.dahe.mylibrary.utils.BarUtils;
import com.dahe.mylibrary.utils.ConvertUtils;
import com.dahe.mylibrary.utils.StatusBar;
import com.dahe.mylibrary.utils.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.constant.RefreshState;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

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

import qiu.niorgai.StatusBarCompat;


public abstract class BaseActivity<VB extends ViewBinding> extends AppCompatActivity {
    protected Context mContext;
    protected final int DEFAULT_STATUS_BAR_ALPHA = 0;
    private static final String TAG = "BaseActivity";
    protected Toolbar mToolbar;
    protected int mRefreshPage = 1;
    protected int mRefreshCount = 15;

    public VB binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = createBinding();
        if (binding==null)
            return;
        setContentView(binding.getRoot());
        mContext = this;
        setStatusBarColorToLight();
        initView(savedInstanceState);
        initDate();
    }


    private VB createBinding() {
        try {
            Class<VB> vbClass = getVBClass();
            Method inflateMethod = vbClass.getMethod("inflate", LayoutInflater.class);
            inflateMethod.setAccessible(true);
            return (VB) inflateMethod.invoke(null, getLayoutInflater());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Class<VB> getVBClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class<VB> vbClass = (Class<VB>) type.getActualTypeArguments()[0];

        return vbClass;
    }

//    protected abstract VB getViewBinding();

    /**
     * 标题栏的颜色 文字白色
     */
    public void setStatusBarCancelLightColor() {
        StatusBar.cancelLightStatusBar(this);
    }


    /**
     * 设置沉浸式标题栏 标题栏的颜色
     */
    public void setStatusBarColor(int color) {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(mContext, color), DEFAULT_STATUS_BAR_ALPHA);
        StatusBar.changeToLightStatusBar(this);  //黑色 下边白色
//        StatusBar.cancelLightStatusBar(this);
    }

    /**
     * 设置沉浸式标题栏 标题栏的颜色
     */
    public void setStatusBarColor() {
//        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(mContext, color), DEFAULT_STATUS_BAR_ALPHA);
//        StatusBar.changeToLightStatusBar(this);  //黑色 下边白色
        StatusBar.cancelLightStatusBar(this);
    }

    /**
     * 设置沉浸式标题栏 里面是Fragment
     */
    public void setStatusBarColorInFragment() {
        StatusBarCompat.translucentStatusBar(this);
    }

    /**
     * 设置透明沉浸式标题栏
     * * true标题栏无背景,false标题栏有背景
     */
    public void setStatusBarColorToLight() {
        StatusBar.translucentStatusBar(this, true);
        StatusBar.changeToLightStatusBar(this);
    }

    /**
     * 设置透明沉浸式标题栏
     * true标题栏无背景,false标题栏有背景
     */
    public void setStatusBarColorToLight(boolean isHide) {
        StatusBar.translucentStatusBar(this, isHide);
        StatusBar.changeToLightStatusBar(this);

    }

    /**
     * 设置标题
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void setTitleBar(String title, View.OnClickListener listener) {
        mToolbar = (Toolbar) findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title))
            ((TextView) findViewById(R.id.common_toolBar_title)).setText(title);
        mToolbar.setNavigationIcon(R.drawable.left_black);
        mToolbar.setNavigationOnClickListener(listener);
    }

    /**
     * 设置标题
     */
    protected void setTitleBar(String title) {
        mToolbar = (Toolbar) findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title))
            ((TextView) findViewById(R.id.common_toolBar_title)).setText(title);
    }
    /**
     * 设置标题
     */
    protected void setTitleBar(String title,boolean isBack) {
        mToolbar = (Toolbar) findViewById(R.id.common_toolbar);
        mToolbar.setBackgroundColor(Color.TRANSPARENT);
        if (isBack){
            mToolbar.setNavigationIcon(R.drawable.left_black);
            mToolbar.setNavigationOnClickListener(view -> finish());
        }
        if (!TextUtils.isEmpty(title))
            ((TextView) findViewById(R.id.common_toolBar_title)).setText(title);
    }

    /**
     * 显示右边标题
     *
     * @param title
     * @param listener
     * @param isVisible
     * @param right
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    protected void setTitleBar(String title, View.OnClickListener listener, boolean isVisible, String right, View.OnClickListener rightListener) {
        mToolbar = (Toolbar) findViewById(R.id.common_toolbar);
        if (!TextUtils.isEmpty(title))
            ((TextView) findViewById(R.id.common_toolBar_title)).setText(title);
        TextView mTextRight = (TextView) findViewById(R.id.common_toolBar_text_right);
        if (isVisible) {
            mTextRight.setVisibility(View.VISIBLE);
            mTextRight.setText(right);
            mTextRight.setOnClickListener(rightListener);
        }
        mToolbar.setNavigationIcon(R.drawable.left_black);
        mToolbar.setNavigationOnClickListener(listener);
    }

    /**
     * 设置距离顶部距离
     */
    protected void setStatusHeightParams(View llContent) {
        RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        closeLayoutParams.topMargin = ConvertUtils.dp2px(8) + BarUtils.getStatusBarHeight();
//        closeLayoutParams.topMargin =  BarUtils.getStatusBarHeight();
        llContent.setLayoutParams(closeLayoutParams);
    }

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void initDate();

    protected void showToast(Object message) {
        ToastUtils.showToast(this, message instanceof String ? message + "" : getResources().getString((int) message));
    }

    protected void canCelToast() {
        ToastUtils.cancelToast();
    }


//    protected void showToast(Object message,int time) {
//        ToastUtils.showToast(this, message instanceof String ? message + "" : getResources().getString((int) message),time);
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放持有，防止泄露
        binding = null;
    }


    /**
     * 设置刷新控件
     *
     * @param refreshLayout
     * @param callBack      访问网络回调
     */
    protected void setRefresh(final SmartRefreshLayout refreshLayout, final RefreshCallBack callBack) {
        refreshLayout.setEnableOverScrollDrag(true)
                .setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mRefreshPage++;
                        callBack.getRefreshDate(2, mRefreshPage, mRefreshCount);
                    }

                    @Override
                    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                        mRefreshPage = 1;
                        callBack.getRefreshDate(1, mRefreshPage, mRefreshCount);
                    }
                });
    }

    /**
     * 网络访问完成 刷新控件
     *
     * @param refreshLayout
     * @param isLoadMore    false禁用下拉加载更多
     */
    protected void setFinishRefresh(final SmartRefreshLayout refreshLayout, boolean isLoadMore) {
        if (refreshLayout != null && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh();
        else if (refreshLayout != null && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore();
        if (!isLoadMore) {
            refreshLayout.finishLoadMore();      //加载完成
            refreshLayout.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
        }
//        refreshLayout.setEnableLoadMore(isLoadMore);
    }

    public void onClick(View view) {

    }


    /**
     * 获取Drawable
     *
     * @param id
     * @return
     */
    protected Drawable getDrawableV4(@DrawableRes int id) {
        return ContextCompat.getDrawable(this, id);
    }

    /**
     * 获取Color
     *
     * @param id
     * @return
     */
    protected int getColorV4(@ColorRes int id) {
        return ContextCompat.getColor(this, id);
    }

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

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


}