package xn.hxp.base;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.OnHttpListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import xn.hxp.R;
import xn.hxp.databinding.IncludeTitleBinding;
import xn.hxp.event.UpdateTimeEvent;
import xn.hxp.http.HttpTool;
import xn.hxp.room.bean.BaseConfig;
import xn.hxp.room.tool.BaseConfigTool;

public abstract class BaseActivity extends AppCompatActivity implements OnHttpListener<Object> {
    private BaseActivityHelp baseActivityHelp;
    private final AtomicBoolean isCountCdTime = new AtomicBoolean(false);
    private int cdTime = 60;
    private IncludeTitleBinding includeTitleBinding;
    private BaseConfig baseConfig;

    private final CountDownTimer countDownTimer = new CountDownTimer(1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {

        }

        @Override
        public void onFinish() {
            if (!isFinishing() && !isDestroyed() && isCountCdTime.get()) {
                cdTime(cdTime);
                cdTime--;
                if (cdTime <= 0) {
                    cdFinish();
                } else {
                    countDownTimer.start();
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseActivityHelp = new BaseActivityHelp(this);
        EdgeToEdge.enable(this);
        ViewBinding binding = setViewBinding();
        View main = binding.getRoot();
        ViewGroup mainVG = (ViewGroup) binding.getRoot();
        mainVG.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        View titleView = main.findViewById(R.id.includeTitle);
        baseConfig = BaseConfigTool.INSTANCE.getBaseConfig();
        if (null != titleView) {
            includeTitleBinding = IncludeTitleBinding.bind(titleView);
            // 学院图标
            String circularLogo = baseConfig.getCircularLogo();
            if (!TextUtils.isEmpty(circularLogo)) {
                Glide.with(includeTitleBinding.titlePic).load(HttpTool.INSTANCE.checkUrl(circularLogo)).into(includeTitleBinding.titlePic);
            }
            // 学院名称
            String deptName = baseConfig.getDeptName();
            includeTitleBinding.titleName.setText(TextUtils.isEmpty(deptName) ? "" : deptName);
            // 日期
            TimeUtils.getNowString(new SimpleDateFormat("M月d日  EEEE  HH:mm", Locale.getDefault()));

        }
        setContentView(main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        onInit();
        countDownTimer.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isCountCdTime.set(true);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        isCountCdTime.set(false);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isCountCdTime.set(false);
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        if (null != baseConfig) {
            cdTime = baseConfig.getBackTime();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        baseActivityHelp.onDestroy();
        isCountCdTime.set(false);
        countDownTimer.cancel();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateTime(UpdateTimeEvent event) {
        if (null != includeTitleBinding) {
            String nowString = TimeUtils.getNowString(new SimpleDateFormat("M月d日  EEEE  HH:mm", Locale.getDefault()));
            includeTitleBinding.timeDate.setText(TextUtils.isEmpty(event.getTime()) ? nowString : event.getTime());
        }
    }

    protected abstract ViewBinding setViewBinding();

    protected abstract void onInit();

    protected abstract void cdFinish();

    protected abstract void cdTime(int cd);

    public void showLoading(String msg) {
        baseActivityHelp.showLoading(msg);
    }

    public void dismissLoading() {
        baseActivityHelp.dismissLoading();
    }

    public void showToast(String msg) {
        baseActivityHelp.showToast(msg);
    }

    public void showSuccess(String msg) {
        baseActivityHelp.showSuccess(msg);
    }

    public void showErr(String msg) {
        baseActivityHelp.showErr(msg);
    }

    public void showErr(String msg, String hint) {
        baseActivityHelp.showErr(msg, hint);
    }

    @Override
    public void onHttpStart(@NonNull IRequestApi api) {
        showLoading("请求中...");
    }

    @Override
    public void onHttpSuccess(@NonNull Object result) {

    }

    @Override
    public void onHttpFail(@NonNull Throwable throwable) {
        showErr(throwable.getMessage());
    }

    @Override
    public void onHttpEnd(@NonNull IRequestApi api) {
        dismissLoading();
    }
}
