package com.videogo.ui.playback.querylist;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.videogo.openapi.bean.EZAlarmInfo;
import com.videogo.openapi.bean.resp.CloudPartInfoFile;
import com.videogo.ui.playback.RemoteListContant;
import com.videogo.ui.playback.RemoteListUtil;
import com.videogo.ui.playback.bean.ClickedListItem;
import com.videogo.util.DataManager;
import com.videogo.util.EZUtils;
import com.videogo.util.Utils;

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

import ezviz.ezopensdk.R;

/**
 * 录像片段列表适配器（RecyclerView版本）
 */
public class RecordRecyclerAdapter extends RecyclerView.Adapter<RecordRecyclerAdapter.ViewHolder> {

    private final List<CloudPartInfoFile> dataList = new ArrayList<>();
    private final Context context;
    private int selectedPosition = -1;
    private int recordType;
    private String deviceSerial;
    private OnRecordItemClickListener listener;

    public interface OnRecordItemClickListener {
        void onRecordItemClick(CloudPartInfoFile file, ClickedListItem clickedListItem);
    }

    public RecordRecyclerAdapter(Context context) {
        this.context = context;
    }

    public void setOnRecordItemClickListener(OnRecordItemClickListener listener) {
        this.listener = listener;
    }

    public void setRecordType(int recordType) {
        this.recordType = recordType;
    }

    public void setDeviceSerial(String deviceSerial) {
        this.deviceSerial = deviceSerial;
    }

    public void setData(List<CloudPartInfoFile> files) {
        dataList.clear();
        if (files != null) {
            dataList.addAll(files);
        }
        notifyDataSetChanged();
    }

    public List<CloudPartInfoFile> getData() {
        return dataList;
    }

    public void setSelectedPosition(int position) {
        int old = selectedPosition;
        selectedPosition = position;
        if (old >= 0 && old < dataList.size()) notifyItemChanged(old);
        if (position >= 0 && position < dataList.size()) notifyItemChanged(position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_record, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        CloudPartInfoFile file = dataList.get(position);

        // 显示开始时间
        Calendar cal = Utils.convert14Calender(file.getStartTime());
        holder.tvTime.setText(formatTime(cal));

        // 显示时长
        holder.tvDuration.setText(RemoteListUtil.convToUIDuration(file));

        // 显示封面
        Bitmap bitmap = file.getBitmap();
        if (bitmap != null) {
            holder.ivCover.setImageBitmap(bitmap);
        } else if (file.isCloud() && !TextUtils.isEmpty(file.getPicUrl())) {
            // 云存储录像：通过picUrl加载封面
            holder.ivCover.setImageResource(R.drawable.record_cover_placeholder);
            String verifyCode = DataManager.getInstance().getDeviceSerialVerifyCode(deviceSerial);
            String coverUrl = RemoteListUtil.getCloudListItemPicUrl(
                    file.getPicUrl(), file.getKeyCheckSum(), verifyCode);
            EZAlarmInfo alarmInfo = new EZAlarmInfo();
            alarmInfo.setDeviceSerial(deviceSerial);
            alarmInfo.setAlarmPicUrl(coverUrl);
            alarmInfo.setCrypt(1);
            EZUtils.loadImage(context, holder.ivCover, alarmInfo, null);
        } else {
            holder.ivCover.setImageResource(R.drawable.record_cover_placeholder);
        }

        // 选中高亮
        holder.ivCover.setSelected(position == selectedPosition);

        // 点击事件
        holder.itemView.setOnClickListener(v -> {
            int pos = holder.getAdapterPosition();
            if (pos == RecyclerView.NO_POSITION) return;
            CloudPartInfoFile clickedFile = dataList.get(pos);
            ClickedListItem clickedItem = new ClickedListItem(
                    clickedFile.getPosition(), recordType,
                    clickedFile.getStartMillis(), clickedFile.getEndMillis(), pos);
            clickedItem.setFileSize(clickedFile.getFileSize());
            setSelectedPosition(pos);
            if (listener != null) {
                listener.onRecordItemClick(clickedFile, clickedItem);
            }
        });
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    private String formatTime(Calendar cal) {
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        int minute = cal.get(Calendar.MINUTE);
        return String.format("%02d:%02d", hour, minute);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCover;
        TextView tvTime;
        TextView tvDuration;

        ViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCover = itemView.findViewById(R.id.iv_cover);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvDuration = itemView.findViewById(R.id.tv_duration);
        }
    }

    /**
     * 网格等间距装饰器
     * 保证列表左右边距和item之间的间距一致
     */
    public static class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
        private final int spanCount;
        private final int spacing;

        public GridSpacingItemDecoration(int spanCount, int spacing) {
            this.spanCount = spanCount;
            this.spacing = spacing;
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                                   @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view);
            int column = position % spanCount;
            // 左右间距均匀分配，使得每列宽度一致且间距相等
            outRect.left = spacing - column * spacing / spanCount;
            outRect.right = (column + 1) * spacing / spanCount;
            // 顶部间距（第一行额外加）
            if (position < spanCount) {
                outRect.top = spacing;
            }
            outRect.bottom = spacing;
        }
    }
}
