package io.rong.imkit.conversation;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.data.net.ApiException;
import com.cooleshow.base.data.net.BaseResponse;
import com.cooleshow.base.data.net.RetrofitFactory;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.rx.BaseObserver;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.widgets.dialog.CommonDialog;

import java.util.List;
import java.util.Locale;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import io.rong.imkit.IMCenter;
import io.rong.imkit.R;
import io.rong.imkit.RongIM;
import io.rong.imkit.activity.RongBaseActivity;
import io.rong.imkit.api.APIService;
import io.rong.imkit.model.GroupInfoBean;
import io.rong.imkit.model.TypingInfo;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.userinfo.db.model.User;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.widget.TitleBar;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

//学生端消息交互界面
public class RongConversationActivity extends RongBaseActivity {
    protected String mTargetId;
    protected Conversation.ConversationType mConversationType;
    protected ConversationFragmentSEC mConversationFragment;
    private ConversationViewModel conversationViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() != null) {
            mTargetId = getIntent().getStringExtra(RouteUtils.TARGET_ID);
            String type = getIntent().getStringExtra(RouteUtils.CONVERSATION_TYPE);
            if (!TextUtils.isEmpty(type)) {
                mConversationType = Conversation.ConversationType.valueOf(type.toUpperCase(Locale.US));
            } else {
                return;
            }
        }
        setContentView(R.layout.rc_conversation_activity);
        setTitle();
        mConversationFragment = (ConversationFragmentSEC) getSupportFragmentManager().findFragmentById(R.id.conversation);
        mTitleBar.setOnBackClickListener(new TitleBar.OnBackClickListener() {
            @Override
            public void onBackClick() {
                if (mConversationFragment != null && !mConversationFragment.onBackPressed()) {
                    finish();
                }
            }
        });
//        mTitleBar.getRightView().setVisibility(View.GONE);
        initViewModel();
    }

    private void setTitle() {
        if (!TextUtils.isEmpty(mTargetId) && mConversationType.equals(Conversation.ConversationType.GROUP)) {
            Group group = RongUserInfoManager.getInstance().getGroupInfo(mTargetId);
            String title = mTargetId;
            if (group != null) {
                title = group.getName();
            } else {
                Bundle extras = getIntent().getExtras();
                if (extras != null) {
                    title = (String) extras.get(RouteUtils.TITLE);
                }
            }
            mTitleBar.setTitle(title);
            mTitleBar.getRightImageView().setVisibility(View.VISIBLE);
            mTitleBar.getRightImageView().setImageResource(com.cooleshow.base.R.drawable.icon_group_setting);
            mTitleBar.getRightImageView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (group == null) {
                        return;
                    }
                    ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_SETTING)
                            .withString("targetId", mTargetId)
                            .withString("name", group.getName())
                            .navigation();
                }
            });
        } else {
            mTitleBar.getRightView().setText("举报");
            mTitleBar.getRightView().setVisibility(View.VISIBLE);
            mTitleBar.getRightView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_IM_APPEAL)
                            .withString("targetId", mTargetId)
                            .withString("name", "")
                            .withString("type", "PERSON")
                            .navigation();
                }
            });
            UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(mTargetId);
            String title = mTargetId;
            if (userInfo != null) {
                title = userInfo.getName();
            } else {
                Bundle extras = getIntent().getExtras();
                if (extras != null) {
                    title = (String) extras.get(RouteUtils.TITLE);
                }
            }
            mTitleBar.setTitle(title);
            mTitleBar.getRightImageView().setVisibility(View.GONE);
        }
        if (mConversationType.equals(Conversation.ConversationType.CUSTOMER_SERVICE)
                || mConversationType.equals(Conversation.ConversationType.CHATROOM)) {
            mTitleBar.setRightVisible(false);
        }
    }

    private void initViewModel() {
        conversationViewModel = new ViewModelProvider(this).get(ConversationViewModel.class);
        conversationViewModel.getTypingStatusInfo().observe(this, new Observer<TypingInfo>() {
            @Override
            public void onChanged(TypingInfo typingInfo) {
                if (typingInfo == null) {
                    return;
                }
                if (typingInfo.conversationType == mConversationType && mTargetId.equals(typingInfo.targetId)) {
                    if (typingInfo.typingList == null) {
                        mTitleBar.getMiddleView().setVisibility(View.VISIBLE);
                        mTitleBar.getTypingView().setVisibility(View.GONE);
                    } else {
                        mTitleBar.getMiddleView().setVisibility(View.GONE);
                        mTitleBar.getTypingView().setVisibility(View.VISIBLE);
                        TypingInfo.TypingUserInfo typing = typingInfo.typingList.get(typingInfo.typingList.size() - 1);
                        if (typing.type == TypingInfo.TypingUserInfo.Type.text) {
                            mTitleBar.setTyping(R.string.rc_conversation_remote_side_is_typing);
                        } else if (typing.type == TypingInfo.TypingUserInfo.Type.voice) {
                            mTitleBar.setTyping(R.string.rc_conversation_remote_side_speaking);
                        }
                    }
                }
            }
        });
        RongUserInfoManager.getInstance().getAllUsersLiveData().observe(this, new Observer<List<User>>() {
            @Override
            public void onChanged(List<User> users) {
                if (users == null) {
                    return;
                }
                for (int i = 0; i < users.size(); i++) {
                    User user = users.get(i);
                    if (TextUtils.equals(mTargetId, user.id)) {
                        setTitle();
                    }
                }
            }
        });

        RongUserInfoManager.getInstance().getAllGroupsLiveData().observe(this, new Observer<List<io.rong.imkit.userinfo.db.model.Group>>() {
            @Override
            public void onChanged(List<io.rong.imkit.userinfo.db.model.Group> groups) {
                if (groups != null) {
                    for (int i = 0; i < groups.size(); i++) {
                        io.rong.imkit.userinfo.db.model.Group group = groups.get(i);
                        if (TextUtils.equals(mTargetId, group.id)) {
                            setTitle();
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        queryGroupInfo();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode()) {
            if (mConversationFragment != null && !mConversationFragment.onBackPressed()) {
                finish();
            }
        }
        return false;
    }


    private void queryGroupInfo() {
        if (BaseApplication.Companion.isTeacherClient()) {
            return;
        }
        if (TextUtils.isEmpty(mTargetId)) {
            return;
        }
        if (!mConversationType.equals(Conversation.ConversationType.GROUP)) {
            return;
        }
        LogUtils.i("pq", "queryGroupInfo");
        RetrofitFactory.Companion.getInstance()
                .create(APIService.class)
                .queryStuGroupDetail(mTargetId)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.rxjava3.core.Observer<BaseResponse<GroupInfoBean>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResponse<GroupInfoBean> rongIMGroupInfoBaseResponse) {
                        int responseCode = rongIMGroupInfoBaseResponse.getErrorCode();
                        if (responseCode == 200) {
                            if (rongIMGroupInfoBaseResponse.getData() != null) {
                                GroupInfoBean data = rongIMGroupInfoBaseResponse.getData();
                                RongIM.getInstance().refreshGroupInfoCache(new Group(data.getId(), data.getName(), Uri.parse(TextUtils.isEmpty(data.getImg()) ? "" : data.getImg())));
                            }
                        } else {
                            if (responseCode == 204) {
                                //群不存在,提示
                                showGroupNotExitDialog();
                            }
                        }

                    }

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

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void showGroupNotExitDialog() {
        CommonDialog commonDialog = new CommonDialog(this);
        commonDialog.show();
        commonDialog.setCancelable(false);
        commonDialog.setCanceledOnTouchOutside(false);
        commonDialog.setTitle("提示");
        commonDialog.setContent("当前群组已被解散，是否删除聊天记录?");
        commonDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null) {
                    commonDialog.dismiss();
                }
                delLocalConversation(mTargetId);
            }
        });
        commonDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null) {
                    commonDialog.dismiss();
                }
            }
        });
    }

    public void delLocalConversation(String targetId) {
        IMCenter.getInstance().removeConversation(Conversation.ConversationType.GROUP, targetId, new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {
                finish();
            }

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