package com.tencent.liteav.live.ui.widget;

import android.view.View;
import android.view.ViewGroup;

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

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.tabs.TabLayout;
import com.tencent.imsdk.v2.V2TIMGroupInfoResult;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.liteav.live.R;
import com.tencent.liteav.live.databinding.ViewRoomListBinding;
import com.tencent.liteav.live.model.TRTCMeeting;
import com.tencent.liteav.live.ui.MemberEntity;
import com.tencent.liteav.live.ui.widget.msg.TCConstants;
import com.wisewoods.base.app.BaseApp;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.RedisList;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.page.PageInfo;
import com.wisewoods.base.utils.$;

import org.jetbrains.annotations.NotNull;

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

import retrofit2.Call;
import retrofit2.Response;

public class RoomListDialog extends BottomSheetDialog implements OnItemChildClickListener,
        TabLayout.OnTabSelectedListener, OnLoadMoreListener {


    private ViewRoomListBinding binding;
    //    private RoomListAdapter roomListAdapter;
    RoomListListener listener;
    private String key = "studentMap";
    private String groupId;
    private RoomListAdapter roomListAdapter;
    private PageInfo pageInfo;

    private ArrayList<RedisList.RedisData.DataBean> mInviteList;
    private List<MemberEntity> mMemberEntityList;
    private int onlineTotal;

    public void refresh() {
        if (roomListAdapter != null) {
            roomListAdapter.notifyDataSetChanged();
        }
    }

    public void change(BaseEvent.UserEvent event) {
        for (String s : event.memberList) {
            for (RedisList.RedisData.DataBean datum : roomListAdapter.getData()) {
                if (datum.id.equals(s)) {
                    if (event.isAdd) {
                        datum.state = 1;
                        String num = binding.tvOnline.getText().toString();
                        int i;
                        try {
                            i = Integer.parseInt(num);
                            i++;
                            binding.tvOnline.setText(i + "");
                        } catch (Exception e) {

                        }

                    } else {
                        datum.state = 0;
                        String num = binding.tvOnline.getText().toString();
                        int i;
                        try {
                            i = Integer.parseInt(num);
                            i--;
                            if (i < 0) {
                                i = 0;
                            }
                            binding.tvOnline.setText(i + "");
                        } catch (Exception e) {

                        }
                    }
                }
            }
        }
        roomListAdapter.notifyDataSetChanged();

    }

    public static interface RoomListListener {
        void invite(RedisList.RedisData.DataBean item);
    }

    public void setListener(RoomListListener listener) {
        this.listener = listener;

    }

    public RoomListDialog(String groupId, ArrayList<RedisList.RedisData.DataBean> mInviteList, List<MemberEntity> mMemberEntityList) {
        super(ActivityUtils.getTopActivity(), R.style.BottomSheetDialog);
        this.groupId = groupId;
        this.mInviteList = mInviteList;
        this.mMemberEntityList = mMemberEntityList;

        binding = ViewRoomListBinding.inflate(getLayoutInflater());
        binding.btnMuteAudioAll.setOnClickListener(v -> {
            String speechSwitch = "On";
            boolean flag = true;
            if ("取消全体禁言".equals(binding.btnMuteAudioAll.getText().toString())) {
                speechSwitch = "Off";
                flag = false;
            } else {
                speechSwitch = "On";
                flag = true;
            }
            muteAll(speechSwitch, flag);

        });
        setContentView(binding.getRoot());
        ViewGroup.LayoutParams layoutParams = binding.llList.getLayoutParams();
        layoutParams.height = ScreenUtils.getScreenHeight() * 2 / 3;
        binding.llList.setLayoutParams(layoutParams);

        binding.tablayout.addOnTabSelectedListener(this);

        binding.rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        roomListAdapter = new RoomListAdapter(mInviteList, key, mMemberEntityList);
        roomListAdapter.setOnItemChildClickListener(this);
        roomListAdapter.getLoadMoreModule().setOnLoadMoreListener(this);
        binding.rvList.setAdapter(roomListAdapter);
        pageInfo = new PageInfo();
        getData();


    }

    private void muteAll(String speechSwitch, boolean flag) {
        BaseApp.api.modifyGroupBaseInfo(groupId + "", speechSwitch)
                .enqueue(new JDCallback<RedisList>() {
                    @Override
                    public void onS(Response<RedisList> response, RedisList redisList) {
                        if (flag) {
                            binding.btnMuteAudioAll.setText("取消全体禁言");
                        } else {
                            binding.btnMuteAudioAll.setText("全体禁言");
                        }
                    }
                });
    }

    private void getData() {
        V2TIMManager.getGroupManager().getGroupsInfo(getList(groupId + ""), new V2TIMValueCallback<List<V2TIMGroupInfoResult>>() {
            @Override
            public void onError(int i, String s) {
                $.toast(s);
                dismiss();
            }

            @Override
            public void onSuccess(List<V2TIMGroupInfoResult> v2TIMGroupInfoResults) {
                if (v2TIMGroupInfoResults != null && v2TIMGroupInfoResults.size() == 1) {
                    final V2TIMGroupInfoResult v2TIMGroupInfoResult = v2TIMGroupInfoResults.get(0);
                    if (v2TIMGroupInfoResult != null) {
                        boolean allMuted = v2TIMGroupInfoResult.getGroupInfo().isAllMuted();
                        if (allMuted) {
                            binding.btnMuteAudioAll.setText("取消全体禁言");
                        } else {
                            binding.btnMuteAudioAll.setText("全体禁言");
                        }
                    } else {
                        onError(7666, "群信息获取异常");
                    }
                }
                BaseApp.api.getRedisCacheList(groupId, key, pageInfo.page, pageInfo.size)
                        .enqueue(new JCallback<RedisList>() {
                            @Override
                            public void onS(Response<RedisList> response, RedisList redisList) {
                                String label = "班级学员";
                                switch (binding.tablayout.getSelectedTabPosition()) {
                                    case 0:
                                        label = "班级学员";
                                        break;
                                    case 1:
                                        label = "教师";
                                        break;
                                    case 2:
                                        label = "游客";
                                        break;
                                }
                                binding.tvContent.setText(label + "总人数" + redisList.data.total + "人,"
                                        + "在线");
                                binding.tvOnline.setText(redisList.data.onlineTotal + "");

                                if (pageInfo.isFirstPage()) {
                                    roomListAdapter.setNewInstance(redisList.data.rows);
                                } else {
                                    roomListAdapter.addData(redisList.data.rows);
                                }

                                if (redisList.data.rows.size() < pageInfo.size || redisList.data.total <= pageInfo.currentSize()) {
                                    roomListAdapter.getLoadMoreModule().loadMoreEnd();
                                } else {
                                    roomListAdapter.getLoadMoreModule().loadMoreComplete();
                                }
                                // page加一
                                pageInfo.nextPage();
                            }

                            @Override
                            public void onFailure(Call<RedisList> call, Throwable t) {
                                super.onFailure(call, t);
                                roomListAdapter.getLoadMoreModule().setEnableLoadMore(true);
                                roomListAdapter.getLoadMoreModule().loadMoreFail();
                            }
                        });
            }
        });


    }


    @Override
    public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter,
                                 @NonNull @NotNull View view, int position) {
        RedisList.RedisData.DataBean item = roomListAdapter.getItem(position);
        if (view.getId() == R.id.tv_invite) {
            TRTCMeeting.sharedInstance(Utils.getApp())
                    .sendRoomCustomMsg(
                            TCConstants.CODE_ROOM_LINK + "",
                            item.id, (code, msg) -> {
                                if (code == 0) {
                                    if (listener != null) {
                                        item.time = TimeUtils.getNowMills();
                                        listener.invite(item);
                                    }
                                } else {
                                    $.toast("邀请失败:" + msg);
                                    LogUtils.e("sendRoomCustomMsg CODE_ROOM_LINK", msg);
                                }
                            }
                    );
        } else if (view.getId() == R.id.tv_mute) {
            muteOne(item, position);
        } else if (view.getId() == R.id.tv_close) {
            TRTCMeeting.sharedInstance(Utils.getApp())
                    .sendRoomCustomMsg(
                            TCConstants.CODE_ROOM_LINK_CLOSE + "", TimeUtils.getNowMills(),
                            item.id, (code, msg) -> {
                                if (code == 0) {

                                } else {
                                    $.toast("下麦失败:" + msg);
                                    LogUtils.e("sendRoomCustomMsg CODE_ROOM_LINK", msg);
                                }
                            }
                    );
        }

    }

    private void muteOne(RedisList.RedisData.DataBean item, int position) {
        long ShutUpTime = 0;
        if (item.talkStatus == 0) {
            ShutUpTime = 86400;
        } else {
            ShutUpTime = 0;
        }
        BaseApp.api.modifyGroupMemberInfo(groupId + "", item.id, ShutUpTime)
                .enqueue(new JDCallback<RedisList>() {
                    @Override
                    public void onS(Response<RedisList> response, RedisList redisList) {
                        if (item.talkStatus == 0) {
                            //取消禁言
                            item.talkStatus = 1;
                        } else {
                            //禁言
                            item.talkStatus = 0;
                        }
                        roomListAdapter.notifyItemChanged(position);
                    }
                });
    }


    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        roomListAdapter.setNewInstance(null);
        pageInfo.reset();
        switch (tab.getText().toString()) {
            case "班级学员":
                key = "studentMap";
                break;
            case "教师":
                key = "teacherMap";
                break;
            case "游客":
                key = "guestMap";
                break;
        }
        roomListAdapter.setKey(key);
        getData();
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onLoadMore() {
        getData();
    }

    public static ArrayList<String> getList(String... groupId) {
        ArrayList<String> al = new ArrayList<>();
        for (String s : groupId) {
            al.add(s);
        }
        return al;
    }


}