package com.common.im.presenter;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.common.im.api.IMApi;
import com.common.im.bean.GroupApplyBean;
import com.common.im.bean.GroupMemberBean;
import com.common.im.bean.MusicSheetListBean;
import com.common.im.bean.RongIMGroupInfo;
import com.common.im.contract.ChatGroupSettingContract;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.presenter.BasePresenter;
import com.cooleshow.base.rx.BaseObserver;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.RequestBodyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.rong.imkit.IMCenter;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;

/**
 * 创建日期：2022/6/11 14:42
 *
 * @author Ryan
 * 类说明：
 */
public class ChatGroupSettingPresenter extends BasePresenter<ChatGroupSettingContract.ChatGroupSettingView> implements ChatGroupSettingContract.Presenter {
    public void conversationGet(Conversation.ConversationType conversationType, final String targetId) {
        RongIM.getInstance().getConversationNotificationStatus(conversationType, targetId, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
            @Override
            public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                if (getView() != null) {
                    getView().onConversation(conversationNotificationStatus.getValue() == 0 ? true : false);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });

    }

    public void conversationMute(Conversation.ConversationType conversationType, String targetId, Conversation.ConversationNotificationStatus notificationStatus) {
        RongIM.getInstance().setConversationNotificationStatus(conversationType, targetId, notificationStatus, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
            @Override
            public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                if (getView() != null) {
                    getView().onConversation(true);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    public void conversationGetUnmute(Conversation.ConversationType conversationType, String targetId, Conversation.ConversationNotificationStatus notificationStatus) {
        RongIM.getInstance().setConversationNotificationStatus(conversationType, targetId, notificationStatus, new RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
            @Override
            public void onSuccess(Conversation.ConversationNotificationStatus conversationNotificationStatus) {
                if (getView() != null) {
                    getView().onConversation(false);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    public void queryGroupMembers(String groupId) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("groupId", groupId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!BaseApplication.Companion.isTeacherClient()) {
            addSubscribe(create(IMApi.class).queryStuGroupMembers(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<List<GroupMemberBean>>(getView()) {
                @Override
                protected void onSuccess(List<GroupMemberBean> data) {
                    if (getView() != null) {
                        getView().onGroupUsers(data, groupId);
                    }
                }

                @Override
                public void onComplete() {
                    super.onComplete();
                    if (getView() != null) {
                        getView().hideLoading();
                    }
                }
            });
        } else {
            addSubscribe(create(IMApi.class).queryTeaGroupMembers(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<List<GroupMemberBean>>(getView()) {
                @Override
                protected void onSuccess(List<GroupMemberBean> data) {
                    if (getView() != null) {
                        getView().onGroupUsers(data, groupId);
                    }
                }

                @Override
                public void onComplete() {
                    super.onComplete();
                    if (getView() != null) {
                        getView().hideLoading();
                    }
                }
            });
        }
    }

    //查询群详情
    public void queryGroupDetail(String groupId) {
        if (!BaseApplication.Companion.isTeacherClient()) {
            addSubscribe(create(IMApi.class).queryStuGroupDetail(groupId), new BaseObserver<RongIMGroupInfo>() {
                @Override
                protected void onSuccess(RongIMGroupInfo data) {
                    if (isViewAttached()) {
                        getView().onQueryGroupDetail(data);
                    }
                    if (data != null) {
                        String id = data.getId() + "";
                        String name = data.getName();
                        if (!TextUtils.isEmpty(id)) {
                            RongIM.getInstance().refreshGroupInfoCache(new Group(id, name, Uri.parse(TextUtils.isEmpty(data.getImg()) ? "" : data.getImg())));
                        }
                    }
                }

            });
        } else {
            addSubscribe(create(IMApi.class).queryTeaGroupDetail(groupId), new BaseObserver<RongIMGroupInfo>() {
                @Override
                protected void onSuccess(RongIMGroupInfo data) {
                    if (isViewAttached()) {
                        getView().onQueryGroupDetail(data);
                    }
                    if (data != null) {
                        String id = data.getId() + "";
                        String name = data.getName();
                        if (!TextUtils.isEmpty(id)) {
                            RongIM.getInstance().refreshGroupInfoCache(new Group(id, name, Uri.parse(TextUtils.isEmpty(data.getImg()) ? "" : data.getImg())));
                        }
                    }
                }

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                }
            });
        }
    }

    /**
     * 解散群组
     *
     * @param groupId
     */
    public void dissolveChatGroup(String groupId) {
        addSubscribe(create(IMApi.class).dissolveChatGroup(groupId), new BaseObserver<Object>() {
            @Override
            protected void onSuccess(Object data) {
                delLocalConversation(groupId);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }


    public void delLocalConversation(String targetId) {
        IMCenter.getInstance().removeConversation(Conversation.ConversationType.GROUP, targetId, new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                if (getView() != null && aBoolean) {
                    getView().dissolveChatGroupSuccess(targetId);
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode e) {
                LogUtils.i("pq", "errorMsg:" + e.msg + "\n" + "errorCode:" + e.code);
            }
        });
    }

    public void groupApplyList(String groupId) {
        if (getView() != null) {
            getView().showLoading();
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.putOpt("auditStatus", "AUDITING");
            jsonObject.putOpt("groupId", groupId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        addSubscribe(create(IMApi.class).groupApplyList(RequestBodyUtil.convertToRequestBodyJson(jsonObject.toString())), new BaseObserver<List<GroupApplyBean>>(getView()) {
            @Override
            protected void onSuccess(List<GroupApplyBean> data) {
                if (getView() != null) {
                    getView().groupApplyListSuccess(data);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
                if (getView() != null) {
                    getView().hideLoading();
                }
            }
        });
    }
}
