package com.wall.dream.wallpapers.View;

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

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import com.wall.dream.wallpapers.LianXi.OnItemXianClick;
import com.wall.dream.wallpapers.R;
import com.wall.dream.wallpapers.acacctivity.WallpaperViewActivity;
import com.wall.dream.wallpapers.databinding.View1MainBinding;
import com.wall.dream.wallpapers.GJ.ComUtilsGJ;
import com.wall.dream.wallpapers.GJ.ItemHelperGJ;
import com.wall.dream.wallpapers.GJ.ObectBoxManagerGJ;

import com.wall.dream.wallpapers.data.DataBase;
import com.wall.dream.wallpapers.ItemPag.ItemFeaturedPag;

import java.util.Collections;
import java.util.List;

public class ViewFeatured extends Fragment implements OnItemXianClick {
    private View1MainBinding vb;

    public ViewFeatured() {
    }

    public static ViewFeatured newInstance() {
        return new ViewFeatured();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        vb = View1MainBinding.inflate(getLayoutInflater());
        
        // 隐藏分类标题栏（精选界面不需要标题）
        View categoryTitleBar = vb.getRoot().findViewById(R.id.category_title_bar);
        if (categoryTitleBar != null) {
            categoryTitleBar.setVisibility(View.GONE);
        }
        
        // 调整RecyclerView的布局参数，使其从顶部开始（不依赖标题栏）
        android.widget.RelativeLayout.LayoutParams params = 
            (android.widget.RelativeLayout.LayoutParams) vb.classRecycler.getLayoutParams();
        params.addRule(android.widget.RelativeLayout.ALIGN_PARENT_TOP);
        params.removeRule(android.widget.RelativeLayout.BELOW);
        // 确保RecyclerView有正确的padding
        vb.classRecycler.setPadding(
            vb.classRecycler.getPaddingLeft(),
            (int) (8 * getResources().getDisplayMetrics().density), // 顶部padding
            vb.classRecycler.getPaddingRight(),
            vb.classRecycler.getPaddingBottom()
        );
        vb.classRecycler.setLayoutParams(params);
        
        initFeaturedWallpapers();
        return vb.getRoot();
    }

    private void initFeaturedWallpapers() {
        // 显示加载指示器
        View loadingLayout = vb.getRoot().findViewById(R.id.loading_layout);
        View emptyLayout = vb.getRoot().findViewById(R.id.empty_layout);
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
        if (emptyLayout != null) {
            emptyLayout.setVisibility(View.GONE);
        }
        // 初始状态：隐藏RecyclerView，等待数据加载
        vb.classRecycler.setVisibility(View.GONE);
        
        // 在后台线程获取所有壁纸数据
        new Thread(() -> {
            // 从数据库获取所有壁纸
            List<DataBase> data = ObectBoxManagerGJ.getAllWallpapers();
            
            // 随机打乱顺序
            if (data != null && !data.isEmpty()) {
                Collections.shuffle(data);
            }
            
            // 切换到主线程更新UI
            if (getActivity() != null && isAdded()) {
                final List<DataBase> finalData = data;
                getActivity().runOnUiThread(() -> {
                    if (!isAdded() || getActivity() == null || vb == null) {
                        return;
                    }
                    
                    // 隐藏加载指示器
                    if (loadingLayout != null) {
                        loadingLayout.setVisibility(View.GONE);
                    }
                    
                    if (finalData == null || finalData.isEmpty()) {
                        // 显示空状态
                        if (emptyLayout != null) {
                            emptyLayout.setVisibility(View.VISIBLE);
                        }
                        vb.classRecycler.setVisibility(View.GONE);
                    } else {
                        // 显示数据
                        if (emptyLayout != null) {
                            emptyLayout.setVisibility(View.GONE);
                        }
                        // 确保RecyclerView可见
                        vb.classRecycler.setVisibility(View.VISIBLE);
                        initGridList(finalData);
                    }
                });
            }
        }).start();
    }

    private void initGridList(List<DataBase> data) {
        // 确保RecyclerView可见
        if (vb.classRecycler.getVisibility() != View.VISIBLE) {
            vb.classRecycler.setVisibility(View.VISIBLE);
        }
        
        // 优化item高度，根据屏幕宽度动态计算（两列布局）
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int padding = (int) (12 * getResources().getDisplayMetrics().density); // 左右padding
        int spacing = (int) (12 * getResources().getDisplayMetrics().density); // item间距
        int columnCount = 2; // 两列布局
        int itemWidth = (screenWidth - padding * 2 - spacing * (columnCount - 1)) / columnCount;
        int itemHeight = (int) (itemWidth * 1.15); // 使用1.15:1的宽高比，平衡高度和宽度
        
        ItemFeaturedPag itemList = new ItemFeaturedPag(requireContext(), itemHeight);
        itemList.setDataInfo(data);
        itemList.setInfoWallpaperListener(this);
        
        // 使用2列网格布局，优化性能
        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), columnCount);
        gridLayoutManager.setItemPrefetchEnabled(true);
        gridLayoutManager.setInitialPrefetchItemCount(4); // 两列时减少预取数量
        
        // 优化间距装饰（两列时增大间距）
        int itemSpacing = (int) (12 * getResources().getDisplayMetrics().density);
        ItemHelperGJ itemHelperGJ = new ItemHelperGJ(itemSpacing, itemSpacing, 0);
        
        // 清除旧的装饰器（如果有）
        int decorationCount = vb.classRecycler.getItemDecorationCount();
        for (int i = decorationCount - 1; i >= 0; i--) {
            vb.classRecycler.removeItemDecorationAt(i);
        }
        vb.classRecycler.addItemDecoration(itemHelperGJ);
        
        // 优化RecyclerView性能
        vb.classRecycler.setLayoutManager(gridLayoutManager);
        vb.classRecycler.setAdapter(itemList);
        vb.classRecycler.setHasFixedSize(true);
        vb.classRecycler.setItemViewCacheSize(20);
        vb.classRecycler.setDrawingCacheEnabled(true);
        vb.classRecycler.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        
        // 强制刷新
        if (itemList.getItemCount() > 0) {
            itemList.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClickAction(DataBase info) {
        Intent intent = new Intent(requireContext(), WallpaperViewActivity.class);
        intent.putExtra(ComUtilsGJ.key_info, info);
        startActivity(intent);
    }

    @Override
    public void onClickMore(String name) {
        // 精选模式下不需要此功能
    }
}

