package com.wall.proshot.wallpapers.myitem;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.wall.proshot.wallpapers.FreeWallPaper;
import com.wall.proshot.wallpapers.myconnector.OnItemClick;
import com.wall.proshot.wallpapers.bean.Data;
import com.wall.proshot.wallpapers.mytool.MyComUtils;
import com.wall.proshot.wallpapers.mytool.MyObectBoxManager;
import com.wall.proshot.wallpapers.R;
import com.wall.proshot.wallpapers.databinding.MyItemMainBinding;

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

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

public class MyItemMain extends RecyclerView.Adapter<MyItemMain.HomeParentHolder> {
    private List<String> data = new ArrayList<>();
    private Context mContext;
    private OnItemClick listener;
    private MultiTransformation<Bitmap> multiTransformation = new MultiTransformation<>(
            new CenterCrop(),
            new RoundedCornersTransformation(MyComUtils.dp2Px(12), 0)
    );

    // 修复1：设置数据时避免null
    public void setData(List<String> data) {
        this.data = data != null ? data : new ArrayList<>();
        notifyDataSetChanged();
    }

    public void setInfoWallpaperListener(OnItemClick onItemClick) {
        this.listener = onItemClick;
    }

    @NonNull
    @Override
    public HomeParentHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        MyItemMainBinding inflate = MyItemMainBinding.inflate(LayoutInflater.from(mContext), parent, false);
        return new HomeParentHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull HomeParentHolder holder, int position) {
        // 修复2：position合法性校验
        if (position < 0 || position >= data.size()) {
            holder.itemBing.tvClassName.setText("");
            holder.itemBing.preview.setImageResource(R.mipmap.im_placeholder);
            return;
        }

        String name = data.get(position);
        List<Data> data1 = MyObectBoxManager.queryHome(name);

        // 修复3：data1空判断（核心！避免get(0)越界）
        if (data1 == null || data1.isEmpty()) {
            holder.itemBing.tvClassName.setText(name);
            holder.itemBing.preview.setImageResource(R.mipmap.im_placeholder);
            return;
        }

        // 到这里data1一定非空，可安全调用get(0)
        Data firstData = data1.get(0);
        String previewUrl = firstData.getPreviewUrl1080();
        // 降级备用地址
        if (previewUrl == null || previewUrl.isEmpty()) {
            previewUrl = firstData.getPreviewUrl400();
        }

        // 设置分类名称
        holder.itemBing.tvClassName.setText(name);
        // 设置底部间距
        holder.itemBing.spaceView.setVisibility(position == data.size() - 1 ? View.VISIBLE : View.GONE);

        // 加载图片
        Glide.with(mContext)
                .asDrawable()
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .load(previewUrl != null ? previewUrl : R.mipmap.im_placeholder)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        Log.e(FreeWallPaper.TAG, "图片加载失败：" + (e != null ? e.getMessage() : "未知错误"));
                        holder.itemBing.preview.setImageResource(R.mipmap.im_placeholder);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .placeholder(R.mipmap.im_placeholder)
                .transform(multiTransformation)
                .into(holder.itemBing.preview);

        // 点击事件（修复4：listener空判断）
        holder.itemBing.preview.setOnClickListener(v -> {
            if (listener != null) {
                listener.onClickMore(name);
            }
        });
    }

    // 修复5：返回实际数据大小
    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

    static class HomeParentHolder extends RecyclerView.ViewHolder {
        private MyItemMainBinding itemBing;

        public HomeParentHolder(@NonNull MyItemMainBinding itemView) {
            super(itemView.getRoot());
            itemBing = itemView;
        }
    }
}