package com.bokecc.livemodule.live.chat;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.live.chat.adapter.VerticalLiveChatTopAdapter;
import com.bokecc.livemodule.live.chat.module.ChatTopEntity;
import com.bokecc.livemodule.view.BaseRelativeLayout;
import com.bokecc.livemodule.view.PagerLayoutManager;
import com.bokecc.livemodule.view.SizeUtils;
import com.bokecc.sdk.mobile.live.common.network.model.CCChatTopBean;

import java.util.ArrayList;

/**
 * Copyright (C), 20105-2021, 创盛视联数码科技（北京）有限公司
 * FileName:
 * Author:
 * Date: 2023/1/11
 * Description:
 */
public class ChatTopLayout extends BaseRelativeLayout {


    View rootView;

    private ImageView ivChatTopPreBtn;
    private TextView tvChatTopNumber;
    private ImageView ivChatTopNextBtn;

    private Handler mHandler = new Handler(Looper.getMainLooper());


    private ArrayList<ChatTopEntity> chatTopBeanArrayList = new ArrayList<>();
    private RecyclerView recyclerView;
    private VerticalLiveChatTopAdapter adapter;
    private LinearLayout llChatTopLayout;
    private LinearLayout llVerticalChatTopBtnCon;
    private PagerLayoutManager layoutManager;
    private boolean isExpand = false;

    private int currentIndex = 0;
    private boolean canSlide = true;

    public ChatTopLayout(Context context) {
        super(context);
    }

    public ChatTopLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ChatTopLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void initViews() {

        rootView = LayoutInflater.from(getContext()).inflate(R.layout.layout_chat_top_vertical,this);

        llChatTopLayout = rootView.findViewById(R.id.ll_chat_top_layout);

        recyclerView = rootView.findViewById(R.id.view_pager);


        ivChatTopPreBtn = rootView.findViewById(R.id.iv_chat_top_pre_btn);
        llVerticalChatTopBtnCon = rootView.findViewById(R.id.ll_vertical_chat_top_btn_con);
        tvChatTopNumber = rootView.findViewById(R.id.tv_chat_top_number);
        ivChatTopNextBtn = rootView.findViewById(R.id.iv_chat_top_next_btn);
        this.addOnLayoutChangeListener(new OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                int height = v.getHeight();
                int maxHeight = SizeUtils.dp2px(mContext,150);
                if (height>maxHeight){
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(SizeUtils.dp2px(mContext,300),maxHeight);
                    layoutParams.setMargins(0,0,0,SizeUtils.dp2px(mContext,5));
                    layoutParams.setMarginStart(SizeUtils.dp2px(mContext,15));
                    v.setLayoutParams(layoutParams);
                }else {
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(SizeUtils.dp2px(mContext,300),LinearLayout.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(0,0,0,SizeUtils.dp2px(mContext,5));
                    layoutParams.setMarginStart(SizeUtils.dp2px(mContext,15));
                    v.setLayoutParams(layoutParams);
                }
            }
        });
        ivChatTopPreBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!canSlide){
                    return;
                }
                canSlide = false;
                isExpand = false;
                //收缩
                adapter.collapseAll();
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int lastPosition = currentIndex;
                        //收缩
                        startLoop();
                        recyclerView.scrollToPosition(Math.max(0,lastPosition-1));
                        currentIndex = Math.max(0,lastPosition-1);
                        canSlide = true;
                    }
                },100);
                tvChatTopNumber.setText(((currentIndex+1)+"/"+chatTopBeanArrayList.size()));
            }
        });
        ivChatTopNextBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!canSlide){
                    return;
                }
                canSlide = false;
                isExpand = false;
                adapter.collapseAll();
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        int lastPosition = currentIndex;
                        //收缩
                        startLoop();
                        recyclerView.scrollToPosition(Math.min(chatTopBeanArrayList.size()-1,lastPosition+1));
                        currentIndex = Math.min(chatTopBeanArrayList.size()-1,lastPosition+1);
                        canSlide = true;
                    }
                },100);
                tvChatTopNumber.setText(((currentIndex+1)+"/"+chatTopBeanArrayList.size()));
            }
        });

        layoutManager = new PagerLayoutManager(mContext, LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        adapter = new VerticalLiveChatTopAdapter(getContext());

        adapter.setOnExpandChangeListener(new VerticalLiveChatTopAdapter.OnExpandChangeListener() {
            @Override
            public void onExpand(int position, boolean expand, int height) {
                //只处理当前显示的item
                if (position!=currentIndex){
                    return;
                }
                if (llChatTopLayout.getLayoutParams() instanceof RelativeLayout.LayoutParams){
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) llChatTopLayout.getLayoutParams();
                    if (expand){
                        isExpand = true;
                        layoutManager.setScrollEnable(false);
                        //展开，取消轮播
                        layoutParams.height = height;
                        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) llVerticalChatTopBtnCon.getLayoutParams();
                        layoutParams1.height = SizeUtils.dp2px(getContext(),90f);
                        llVerticalChatTopBtnCon.setLayoutParams(layoutParams1);
                        llVerticalChatTopBtnCon.setBackgroundResource(R.drawable.shape_chat_top_btn_bg_2);
                        stopLoop();

                    }else {
                        isExpand = false;
                        layoutManager.setScrollEnable(true);

                        layoutParams.height = height;
                        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) llVerticalChatTopBtnCon.getLayoutParams();
                        layoutParams1.height = LinearLayout.LayoutParams.MATCH_PARENT;
                        llVerticalChatTopBtnCon.setLayoutParams(layoutParams1);
                        llVerticalChatTopBtnCon.setBackgroundResource(R.drawable.shape_chat_top_btn_bg);
                        startLoop();

                    }
                    llChatTopLayout.setLayoutParams(layoutParams);
                    //定位到当前
                    recyclerView.scrollToPosition(currentIndex);
                }
            }
        });

        recyclerView.setAdapter(adapter);
    }

    private boolean visible = false;

    public void setData(ArrayList<CCChatTopBean> chatTopBeanArrayList) {
        if (chatTopBeanArrayList==null||chatTopBeanArrayList.size()==0){
            visible = false;
            //停止滚动
            stopLoop();
            this.setVisibility(GONE);
            return;
        }else {
            visible = true;
            this.setVisibility(VISIBLE);
        }
        ArrayList<ChatTopEntity> arrayList = new ArrayList<>();
        for (CCChatTopBean ccChatTopBean:chatTopBeanArrayList){
            ChatTopEntity chatTopEntity = new ChatTopEntity(ccChatTopBean.getId(),ccChatTopBean.getContent(),ccChatTopBean.getFromViewerId(),ccChatTopBean.getFromViewerName(),ccChatTopBean.getFromViewerAvatar(),ccChatTopBean.getFromViewerGroupId(),ccChatTopBean.getFromViewerRole());
            arrayList.add(chatTopEntity);
        }
        this.chatTopBeanArrayList = arrayList;
        //停止滚动
        stopLoop();

        tvChatTopNumber.setText(((1)+"/"+chatTopBeanArrayList.size()));

        adapter.setList(arrayList);
        recyclerView.scrollToPosition(0);
        ChatTopLayout.this.currentIndex = 0;

        startLoop();
    }

    private void stopLoop() {
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onDetachedFromWindow() {
        stopLoop();
        super.onDetachedFromWindow();
    }

    private void loop(){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!canSlide){
                    return;
                }
                if (!visible){
                    return;
                }
                if (ChatTopLayout.this.currentIndex<chatTopBeanArrayList.size()-1){
                    ChatTopLayout.this.currentIndex++;
                }else {
                    ChatTopLayout.this.currentIndex = 0;
                }
                recyclerView.smoothScrollToPosition(ChatTopLayout.this.currentIndex);
                tvChatTopNumber.setText(((currentIndex+1)+"/"+chatTopBeanArrayList.size()));

                loop();
            }
        },10000);
    }

    private void startLoop(){
        stopLoop();
        loop();
    }
}
