package com.webclip.base;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.webclip.base.databinding.ActivityNotifylistBinding;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 通知列表
 */
public class NotifyListActivity extends AppCompatActivity {
    ActivityNotifylistBinding activityNotifylistBinding;
    private LinearLayoutManager manager;
    private MyNotifyListAdapter adapter;
    private List<MessageInfo> listdata = new ArrayList<>();
    private int userId = 2;
    private int page = 1;
    private boolean isNextPages = false;

    private  MessageInfo messageInfoItem;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        userId = MainActivity.getInt(NotifyListActivity.this,"user_code",userId);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        super.onCreate(savedInstanceState);
        View decor = getWindow().getDecorView();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        activityNotifylistBinding = ActivityNotifylistBinding.inflate(getLayoutInflater());
        setContentView(activityNotifylistBinding.getRoot());
        enableEdgeToEdge(getWindow(), activityNotifylistBinding.getRoot(), true, false);
        messageInfoItem = (MessageInfo) getIntent().getSerializableExtra("message");
        activityNotifylistBinding.backIv.setOnClickListener(view -> finish());
        manager = new LinearLayoutManager(this);
        activityNotifylistBinding.recyclerNofity.setLayoutManager(manager);
        activityNotifylistBinding.recyclerNofity.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int visibleCount = manager.getChildCount();
                int totalCount = manager.getItemCount();
                int firstvisibleCount = manager.findFirstVisibleItemPosition();
                if (visibleCount > 0 && visibleCount + firstvisibleCount == totalCount) {  //滑动到底部
                    if (!isNextPages) {
//                        Toast.makeText(NotifyListActivity.this, getString(R.string.app_toastloading), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    page++;
                    getNotifyList();
                }
//                super.onScrolled(recyclerView, dx, dy);
            }
        });
        adapter = new MyNotifyListAdapter(NotifyListActivity.this, listdata,messageInfoItem);
        activityNotifylistBinding.recyclerNofity.setAdapter(adapter);
        adapter.setOnItemClick(position -> {
            try{
                MessageInfo messageInfo = listdata.get(position);
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(messageInfo.getJumpUrl()));
                startActivity(intent);
            }catch (Exception e){

            }

        });
        getNotifyList();
    }
    /**
     * 启用Edge-to-Edge模式（核心方法）
     *
     * @param window               Activity的Window对象
     * @param rootView             Activity的根布局（用于调整内边距）@param isLightStatusBar     状态栏文字是否为浅色（true=白色，false=黑色）
     *      *
     * @param isLightNavigationBar 导航栏文字是否为浅色（仅Android O+生效）
     */
    public void enableEdgeToEdge(Window window, View rootView,
                                 boolean isLightStatusBar, boolean isLightNavigationBar) {
        WindowCompat.setDecorFitsSystemWindows(window, true);

        // 3. 直接设置导航栏颜色（兼容所有版本）
        window.setNavigationBarColor(Color.TRANSPARENT);
        // 4. 可选：设置导航栏文字颜色（保证可读性）
        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(window, window.getDecorView());
        insetsController.setAppearanceLightStatusBars(isLightStatusBar);
        // true=浅色文字（白色），false=深色文字（黑色），根据导航栏颜色调整
        insetsController.setAppearanceLightNavigationBars(isLightNavigationBar);
        window.getDecorView().setBackgroundColor(Color.WHITE);


    }

    public void getNotifyList() {
        //通知列表
        Api.getInstance().getNotifyList(userId, page, 10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<>() {
                    @Override
                    public void onSuccess(Result<ResultDataInfo<MessageInfo>> o) {
                        if (o.data != null) {
                            isNextPages = o.data.isHasNextPage();
                            if (page == 1) {
                                listdata.clear();
                            }
                            listdata.addAll(o.data.getList());
                            adapter.setListdata(listdata);

                        }

                    }

                    @Override
                    public void onError(int code, String msg) {
                        LogUtils.i("获取的结果error" + msg);
                        if (page > 1) {
                            page--;
                        }
                    }

                    @Override
                    public void onError2(Result<ResultDataInfo<MessageInfo>> o) {
                        LogUtils.i("获取的结果error");
                        if (page > 1) {
                            page--;
                        }
                    }
                });
    }
}
