package com.example.wallisyn.fragment;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wallisyn.MyApp;
import com.example.wallisyn.Activity.WallpaperListActivity;
import com.example.wallisyn.Activity.WallpaperActivity;
import com.example.wallisyn.databinding.FragmentHomeMainBinding;
import com.example.wallisyn.tool.ComUtils;
import com.example.wallisyn.connector.OnItemClick;
import com.example.wallisyn.mybean.MyData;
import com.example.wallisyn.item.MainWallpaperItem;

import java.util.List;

public class HomeMainFragment extends Fragment implements OnItemClick {
    private FragmentHomeMainBinding vb;
    private MainWallpaperItem adapter; // 保存Adapter实例，避免重复创建
    private GridLayoutManager layoutManager; // 保存布局管理器，保留滚动状态
    private int scrollPosition = 0; // 保存列表滚动位置

    public HomeMainFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        vb = FragmentHomeMainBinding.inflate(inflater, container, false);
        vb.loadingPb.setVisibility(View.VISIBLE);
        // 初始化RecyclerView基础配置（只执行一次）
        initRecyclerViewConfig();
        return vb.getRoot();
    }

    /**
     * 初始化RecyclerView配置（布局管理器、间距、Adapter），只创建一次
     */
    private void initRecyclerViewConfig() {
        if (getContext() == null || vb == null || vb.classRecycler == null) return;

        // 1. 初始化布局管理器（保存实例，避免重复创建）
        layoutManager = new GridLayoutManager(getContext(), 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return 1; // 固定1列，保持分类项大小一致
            }
        });

        // 2. 初始化间距（固定间距，避免切换后变化）
        int spacing = ComUtils.dp2Px(6);
        vb.classRecycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                int pos = parent.getChildAdapterPosition(view);
                if (pos == RecyclerView.NO_POSITION) return;
                int col = pos % 2;
                // 左右间距均分，上下间距只给第2项及以后添加，保持布局一致
                outRect.left = spacing - col * spacing / 2;
                outRect.right = (col + 1) * spacing / 2;
                if (pos >= 2) outRect.top = spacing;
            }
        });

        // 3. 初始化Adapter（保存实例，避免重复创建）
        adapter = new MainWallpaperItem();
        adapter.setInfoWallpaperListener(this);

        // 4. 绑定RecyclerView
        vb.classRecycler.setLayoutManager(layoutManager);
        vb.classRecycler.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 加载分类数据（只更新数据，不重新初始化RecyclerView）
        loadCategoryData();
    }

    /**
     * 加载分类数据，避免重复初始化布局
     */
    private void loadCategoryData() {
        if (vb == null) return;

        // 直接获取预定义分类，无需轮询
        List<String> categoryList = MyApp.getCategoryNames();
        vb.loadingPb.setVisibility(View.GONE);

        // 只更新Adapter数据，不重新创建Adapter和布局
        if (adapter != null) {
            adapter.setData(categoryList);
            adapter.notifyDataSetChanged(); // 刷新数据，保留原有布局状态
        }

        // 恢复滚动位置（如果之前有保存）
        if (layoutManager != null && scrollPosition != 0) {
            vb.classRecycler.scrollToPosition(scrollPosition);
        }
    }

    @Override
    public void onItemClickAction(MyData info) {
        if (getContext() == null || info == null) return;
        Intent intent = new Intent(getContext(), WallpaperActivity.class);
        intent.putExtra(ComUtils.key_info, info);
        startActivity(intent);
    }

    @Override
    public void onClickMore(String name) {
        if (getContext() == null || name == null) return;
        Intent intent = new Intent(getContext(), WallpaperListActivity.class);
        intent.putExtra(WallpaperListActivity.key_index, name);
        startActivity(intent);
    }

    /**
     * 保存滚动位置，避免Fragment切换后重置
     */
    @Override
    public void onPause() {
        super.onPause();
        // 保存当前滚动位置
        if (vb != null && vb.classRecycler != null && layoutManager != null) {
            scrollPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
        }
    }

    /**
     * 恢复滚动位置和状态
     */
    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        // 从保存的状态中恢复滚动位置（如屏幕旋转、Fragment重建）
        if (savedInstanceState != null) {
            scrollPosition = savedInstanceState.getInt("scroll_position", 0);
        }
    }

    /**
     * 保存Fragment状态（滚动位置）
     */
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("scroll_position", scrollPosition);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 释放资源，避免内存泄漏
        if (vb != null && vb.classRecycler != null) {
            vb.classRecycler.setAdapter(null); // 解除Adapter绑定
        }
        vb = null;
        adapter = null;
        layoutManager = null;
    }
}