package com.daya.live_teaching.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.cooleshow.base.utils.ScreenUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.daya.live_teaching.R;
import com.daya.live_teaching.model.ClassMember;
import com.daya.live_teaching.model.Role;
import com.daya.live_teaching.model.UserInfo;
import com.daya.live_teaching.ui.base.BaseRecyclerAdapter;
import com.daya.live_teaching.ui.base.BaseViewHolder;
import com.daya.live_teaching.ui.fragmnet.VideoViewManager;
import com.daya.live_teaching.ui.view.ClassVideoListItem;
import com.daya.live_teaching.ui.view.RadioRtcVideoView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import androidx.annotation.NonNull;


/**
 * 视频列表的 Adapter
 */
public class GonggeVideoListAdapter extends BaseRecyclerAdapter<GonggeVideoListAdapter.ViewHolder> {


    public  List<ClassMember>      memberList;
    private OnUserUpdateListener   listener;
    private List<String>           updateUserIds = Collections.synchronizedList(new ArrayList<String>());
    private OnItemBtnClickListener itemBtnClicklistener;
    Context mContext;
    private int         removePosition = -1;
    private ClassMember removeMember;
    private UserInfo    userInfo;
    private int         screenHeight;
    private int         screenWidth;
    private int         dividerWidth   = 1;
    int height = 0;
    int width  = 0;
    private ClassMember bigClassMember = null;

    public GonggeVideoListAdapter(Context context) {
        this.mContext = context;
        this.screenHeight = ScreenUtils.getScreenHeight();
        dividerWidth = SizeUtils.dp2px(10);
        this.screenWidth = (ScreenUtils.getScreenWidth() - dividerWidth * 2);

    }

    @Override
    public int getItemCount() {
        return memberList == null ? 0 : memberList.size();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

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


    public class ViewHolder extends BaseViewHolder {
        ClassVideoListItem item;
        LinearLayout       clGroup;

        public ViewHolder(View itemView) {
            super(itemView);
            item = itemView.findViewById(R.id.video_view);
            clGroup = itemView.findViewById(R.id.cl_group);
        }

        @Override
        protected void onBind(int position) {
            ClassMember classMember = memberList.get(position);
            if (bigClassMember != null && classMember.getUserId().equals(bigClassMember.getUserId())) {
                return;
            }
            if (width > 0) {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) item.getLayoutParams();
                if (layoutParams == null) {
                    layoutParams = new LinearLayout.LayoutParams(width, height);
                } else {
                    layoutParams.height = height;
                    layoutParams.width = width;
                }
                clGroup.setLayoutParams(layoutParams);
            }
            ClassMember oldData = item.getData();
            item.setUserInfo(userInfo);
            item.setData(classMember);
            item.setOnItemMemberClickListener((type, isChecked, member) -> {
                itemBtnClicklistener.onClick(type, isChecked, member);
            });
            if (oldData != null) {
                //如果不为空，则判读是当前的人是否还是同一个人， 如果不是， 则通知刷新
                boolean update = isUpdate(classMember.getUserId());
                if (classMember == null || update || !oldData.getUserId().equals(classMember.getUserId())) {
                    // 通知解绑和绑定
                    if (listener != null) {
                        listener.onUpdate(item, position, classMember);
                    }
                }
            } else {
                // 通知订阅
                if (listener != null) {
                    listener.onUpdate(item, position, classMember);
                }
            }
            item.setOnClickListener(view -> {
                RadioRtcVideoView videoView = VideoViewManager.getInstance().get(classMember.getUserId());
                boolean has = item.hasVideoView(videoView);
                if (has) {
                    bigClassMember = classMember;
                    onItemClickListener.onItemClick(classMember);
                }
            });
        }
    }

    public void setListData(List<ClassMember> memberList, UserInfo userInfo, boolean isNotify) {
        this.memberList = memberList;
        this.userInfo = userInfo;
        int horizontalNum = memberList.size() > 4 ? 3 : 2;
        int verticalNum = 1;
        if (memberList.size() > 6) {
            verticalNum = 3;
        } else if (memberList.size() > 2) {
            verticalNum = 2;
        }
        this.width = (screenWidth - dividerWidth * (horizontalNum - 1)) / horizontalNum;
        this.height = (screenHeight - dividerWidth * (verticalNum - 1)) / verticalNum;
        if (isNotify) {
            notifyDataSetChanged();
        }
    }

    public void setOnUserUpdateListener(OnUserUpdateListener listener) {
        this.listener = listener;
    }


    public void notifyDataSetChanged(List<String> userIds) {
        if (userIds == null || userIds.size() <= 0) {
            return;
        }
        if (updateUserIds == null) {
            updateUserIds = userIds;
        } else {
            for (String userId : userIds) {
                boolean contains = updateUserIds.contains(userId);
                if (!contains) {
                    updateUserIds.add(userId);
                }
            }
        }
        userIds.clear();
        notifyDataSetChanged();
    }

    public void removeItemSetChanged(ClassMember member) {
        if (null == member) {
            return;
        }
        if (removePosition >= 0 && removeMember != null && (!removeMember.getUserId().equals("-1") || member.getRole() != Role.LECTURER)) {
            memberList.add(removePosition, removeMember);
        }

        Iterator<ClassMember> iterator = memberList.iterator();
        while (iterator.hasNext()) {
            ClassMember members = iterator.next();
            if (members.getUserId().equals(member.getUserId())) {
                removePosition = memberList.indexOf(members);
                removeMember = members;
                iterator.remove();
                notifyItemRemoved(removePosition);
            }
        }
        notifyDataSetChanged();
    }

    public void addRemoveItemNotifyChanged() {
        if (removePosition >= 0 && removeMember != null) {
            memberList.add(removePosition, removeMember);
        }
        notifyItemRangeChanged(removePosition, memberList.size() - removePosition);
        //        notifyDataSetChanged();
        removePosition = -1;
        removeMember = null;
    }

    private boolean isUpdate(String userId) {
        if (updateUserIds == null || updateUserIds.size() <= 0) {
            return false;
        }

        boolean contains = updateUserIds.contains(userId);
        if (contains) {
            int index = updateUserIds.indexOf(userId);
            updateUserIds.remove(index);
        }
        return contains;
    }

    public interface OnUserUpdateListener {
        void onUpdate(ClassVideoListItem view, int position, ClassMember newMember);
    }

    public void setOnItemBtnClickListener(OnItemBtnClickListener itemBtnClicklistener) {
        this.itemBtnClicklistener = itemBtnClicklistener;
    }

    public interface OnItemBtnClickListener {
        void onClick(ClassVideoListItem.BtnOperate type, boolean isChecked, ClassMember member);
    }


    public OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(ClassMember member);
    }

    public void removeBigClassMember() {
        bigClassMember = null;
    }

}
