package com.common.im.ui.activity;

import android.os.Bundle;
import android.util.Base64;
import android.view.View;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.common.im.helper.ConversationHelper;
import com.common.im_ui.R;
import com.common.im_ui.databinding.ActivitySelectScoreChatBinding;
import com.common.im.bean.MusicSheetListBean;
import com.cooleshow.base.constanst.Constants;
import com.common.im.contract.SelectScoreChatContract;
import com.common.im.presenter.SelectScoreChatPresenter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.common.im.adapter.MineScoreAdapter;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.widgets.EmptyViewLayout;
import com.rong.io.live.manager.RCChatRoomMessageManager;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

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

import io.rong.imkit.RongIM;
import io.rong.imkit.widget.RCChatShareMusicMessage;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.MessageTag;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;

/**
 * 创建日期：2022/6/10 15:28
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.ChatCenter.CHAT_SELECT_SCORE)
public class SelectScoreChatActivity extends BaseMVPActivity<ActivitySelectScoreChatBinding, SelectScoreChatPresenter> implements SelectScoreChatContract.SelectScoreChatView, View.OnClickListener {

    private Conversation.ConversationType targetConversationType;//发送对象(单人,群组等等...)

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_search) {
            search = viewBinding.etTargetName.getText().toString().trim();
            currentPage = 1;
            queryScore(true);
        } else if (view.getId() == com.cooleshow.base.R.id.tv_right_text) {
            //发送曲谱到聊天室
            for (MusicSheetListBean.RowsBean rowsBean : mineScoreAdapter.getData()) {
                if (rowsBean.isSelect) {
                    sendMessage(rowsBean);
                    break;
                }
            }

            finish();
        }
    }

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private MineScoreAdapter mineScoreAdapter;
    private String targetId = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    protected void initView() {
        targetId = getIntent().getStringExtra("targetId");
        int conversationValue = getIntent().getIntExtra("conversationType", Conversation.ConversationType.PRIVATE.getValue());
        targetConversationType = ConversationHelper.getConversationType(conversationValue);
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "曲谱");
        viewBinding.tvSearch.setOnClickListener(this);
        viewBinding.toolbarInclude.tvRightText.setText("确定");
        viewBinding.toolbarInclude.tvRightText.setVisibility(View.VISIBLE);
        viewBinding.toolbarInclude.tvRightText.setOnClickListener(this);
        viewBinding.toolbarInclude.tvRightText.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_2dc7aa));
        refreshLayout = viewBinding.refreshLayout;
        recyclerView = viewBinding.recyclerView;
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                queryScore(true);
            }
        });

        mineScoreAdapter = new MineScoreAdapter();
        EmptyViewLayout emptyViewLayout = new EmptyViewLayout(this);
        emptyViewLayout.setContent(R.drawable.icon_empty_content, "暂无曲谱");
        mineScoreAdapter.setEmptyView(emptyViewLayout);
//        mAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
        mineScoreAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                //上拉加载
                if (hasNext) {
                    currentPage++;
                    queryScore(false);
                } else {
                    mineScoreAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mineScoreAdapter);
       /* viewBinding.etTargetName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    //点击搜索要做的操作
                    search = viewBinding.etTargetName.getText().toString().trim();
                    currentPage = 1;
                    queryScore(true);
                    return true;
                }
                return false;
            }
        });*/
        mineScoreAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                MusicSheetListBean.RowsBean item = (MusicSheetListBean.RowsBean) adapter.getItem(position);
                if (!item.isSelect) {
                    for (MusicSheetListBean.RowsBean rowsBean : mineScoreAdapter.getData()) {
                        if (rowsBean.id == item.id) {
                            rowsBean.isSelect = true;
                        } else {
                            rowsBean.isSelect = false;
                        }
                    }
                    mineScoreAdapter.notifyDataSetChanged();
                }

            }
        });

    }

    private void sendMessage(MusicSheetListBean.RowsBean item) {
        RCChatShareMusicMessage rcChatShareMusicMessage = new RCChatShareMusicMessage();

        rcChatShareMusicMessage.setSongName(item.musicSheetName);
        rcChatShareMusicMessage.setSongAuth(item.composer);
        rcChatShareMusicMessage.setMusicTagNames(item.musicSheetName);
        rcChatShareMusicMessage.setTeacherAvatar(item.addUserAvatar);
        rcChatShareMusicMessage.setTeacherName(item.addName);
        rcChatShareMusicMessage.setSongId(item.id + "");
        rcChatShareMusicMessage.setChargeType(item.chargeType);

        Message locationMsg = Message.obtain(targetId, targetConversationType, rcChatShareMusicMessage);
        MessageTag annotation = rcChatShareMusicMessage.getClass().getAnnotation(MessageTag.class);
        if (annotation != null) {
            locationMsg.setObjectName(annotation.value());
        }
        RongIM.getInstance().sendMessage(locationMsg, "曲谱分享", "[曲谱分享]", new IRongCallback.ISendMessageCallback() {
            @Override
            public void onAttached(Message message) {

            }

            @Override
            public void onSuccess(Message message) {
                ToastUtil.getInstance().showShort("发送成功");
            }

            @Override
            public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                ToastUtil.getInstance().showShort("发送失败");
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        currentPage = 1;
        queryScore(false);
    }

    @Override
    protected ActivitySelectScoreChatBinding getLayoutView() {
        return ActivitySelectScoreChatBinding.inflate(getLayoutInflater());
    }

    @Override
    protected SelectScoreChatPresenter createPresenter() {
        return new SelectScoreChatPresenter();
    }

    private int currentPage;
    private boolean hasNext = true;
    private String search = "";

    private void queryScore(boolean isLoading) {
        //根据默认筛选条件查询
        presenter.queryPageCourseGroup(isLoading, currentPage, "PASS", search);
    }

    /**
     * 检查是否还有下一页
     *
     * @param dataSize
     */
    private void checkHasNext(int dataSize) {
        hasNext = dataSize >= Constants.DEFAULT_DATA_SIZE;
    }

    @Override
    public void queryMusicListSuccess(int page, MusicSheetListBean data) {
        if (data != null) {
            if (page == 1) {
                mineScoreAdapter.getData().clear();
                mineScoreAdapter.notifyDataSetChanged();
                viewBinding.refreshLayout.finishRefresh();
                if (data.rows != null && data.rows.size() > 0) {
                    checkHasNext(data.rows.size());
                    mineScoreAdapter.setNewInstance(data.rows);
                }
            } else {
                if (data.rows != null && data.rows.size() > 0) {
                    mineScoreAdapter.addData(data.rows);
                    mineScoreAdapter.getLoadMoreModule().loadMoreComplete();
                    checkHasNext(data.rows.size());
                } else {
                    mineScoreAdapter.getLoadMoreModule().loadMoreEnd();
                }
            }
        }

    }

    @Override
    public void queryMusicListError(int page) {
        if (page == 1) {
            viewBinding.refreshLayout.finishRefresh();
        } else {
            if (mineScoreAdapter != null) {
                currentPage--;
                mineScoreAdapter.getLoadMoreModule().loadMoreFail();
            }
        }
    }
}
