package com.common.im.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.im.adapter.MessageSettingGroupMemberAdapter;
import com.common.im.bean.GroupApplyBean;
import com.common.im.bean.GroupMemberBean;
import com.common.im.bean.RongIMGroupInfo;
import com.common.im.contract.ChatGroupSettingContract;
import com.common.im_ui.R;
import com.common.im.presenter.ChatGroupSettingPresenter;
import com.common.im_ui.databinding.ActivityChatGroupSettingBinding;
import com.cooleshow.base.common.BaseApplication;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.JumpUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.base.widgets.dialog.CommonConfirmDialog;
import com.cooleshow.base.widgets.dialog.CommonDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.RongIM;
import io.rong.imkit.userinfo.model.GroupUserInfo;
import io.rong.imkit.utils.helper.ChatGroupHelper;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * 创建日期：2022/6/11 14:29
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.ChatCenter.CHAT_GROUP_SETTING)
public class ChatGroupSettingActivity extends BaseMVPActivity<ActivityChatGroupSettingBinding, ChatGroupSettingPresenter> implements ChatGroupSettingContract.ChatGroupSettingView, View.OnClickListener {
    private final int REQUEST_GROUP_REMARKS_CODE = 100;

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.ll_history_message) {
            //查看历史消息内容
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_SEARCH_HISTORY)
                    .withString("targetId", targetId)
                    .navigation();
        } else if (view.getId() == R.id.tv_group_name_remarks) {
            //设置群名称
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_SET_REMARK)
                    .withString("targetId", targetId)
                    .withString("remarks", tv_group_name_remarks.getText().toString().trim())
                    .navigation(this, REQUEST_GROUP_REMARKS_CODE);
        } else if (view.getId() == R.id.tv_group_member_list) {
            //查看联系人
            if (data != null) {
                ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_MEMBER)
                        .withSerializable("list", (Serializable) data)
                        .navigation();
            }
        } else if (view.getId() == R.id.tv_group_apply_count) {
            //查看入群申请
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_JOIN_APPLY)
                    .withString("targetId", targetId)
                    .navigation();
        } else if (view.getId() == R.id.tv_feedback) {
            //反馈
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_IM_APPEAL)
                    .withString("targetId", targetId)
                    .withString("name", name)
                    .withString("type", "GROUP")
                    .navigation();
        } else if (view.getId() == R.id.tv_notice) {
            //群公告
            ARouter.getInstance().build(RouterPath.ChatCenter.CHAT_GROUP_NOTICE)
                    .withString("targetId", targetId)
                    .navigation();
        } else if (view.getId() == R.id.btn_confirm) {
//            finish();
            if (BaseApplication.Companion.isTeacherClient()) {
                //老师端解散群组
                showConfirmDialog();
            } else {
                //发消息
                finish();
            }
        }

    }

    private void showConfirmDialog() {
        CommonDialog commonDialog = new CommonDialog(this);
        commonDialog.show();
        commonDialog.setTitle("提示");
        commonDialog.setContent("确认解散群组吗?");
        commonDialog.setOnConfirmClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null) {
                    commonDialog.dismiss();
                }
                presenter.dissolveChatGroup(targetId);
            }
        });
        commonDialog.setOnCancelClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (commonDialog != null) {
                    commonDialog.dismiss();
                }
            }
        });
    }

    private ImageView iv_portrait;
    private TextView tv_group_name;
    private TextView tv_class_num;
    private TextView tv_group_member_list;
    private RecyclerView recyclerView;
    private TextView tv_group_apply_count;
    private TextView tv_group_name_remarks;
    private CheckBox cb_message;
    List<GroupMemberBean> data = new ArrayList<>();
    MessageSettingGroupMemberAdapter adapter;

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

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "群设置");
        iv_portrait = viewBinding.ivPortrait;
        tv_group_name = viewBinding.tvGroupName;
        tv_class_num = viewBinding.tvClassNum;
        tv_group_member_list = viewBinding.tvGroupMemberList;
        tv_group_member_list.setOnClickListener(this);
        recyclerView = viewBinding.recyclerView;

        Button btnConfirm = viewBinding.btnConfirm;
        if (BaseApplication.Companion.isTeacherClient()) {
            btnConfirm.setText("解散群组");
            viewBinding.llChatJoinApply.setVisibility(View.VISIBLE);
        } else {
            btnConfirm.setText("发消息");
            viewBinding.llChatJoinApply.setVisibility(View.GONE);
        }
        tv_group_apply_count = viewBinding.tvGroupApplyCount;
        tv_group_apply_count.setOnClickListener(this);
        tv_group_name_remarks = viewBinding.tvGroupNameRemarks;
        tv_group_name_remarks.setOnClickListener(this);
        viewBinding.llHistoryMessage.setOnClickListener(this);
        cb_message = viewBinding.cbMessage;
        viewBinding.tvNotice.setOnClickListener(this);
        viewBinding.tvFeedback.setOnClickListener(this);
        viewBinding.btnConfirm.setOnClickListener(this);

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MessageSettingGroupMemberAdapter(data);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                GroupMemberBean groupMemberBean = (GroupMemberBean) adapter.getItem(position);
                RongIM.getInstance().startPrivateChat(ChatGroupSettingActivity.this, groupMemberBean.getUserId() + "", data.get(position).getNickname());

            }
        });

    }

    private String targetId;
    private String name;

    @Override
    public void initData() {
        super.initData();
        targetId = getIntent().getStringExtra("targetId");
        name = getIntent().getStringExtra("name");

        presenter.conversationGet(Conversation.ConversationType.GROUP, targetId);

        cb_message.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (buttonView.isPressed()) {
                    if (isChecked) {
                        presenter.conversationMute(Conversation.ConversationType.GROUP, targetId, Conversation.ConversationNotificationStatus.DO_NOT_DISTURB);
                    } else {
                        presenter.conversationGetUnmute(Conversation.ConversationType.GROUP, targetId, Conversation.ConversationNotificationStatus.NOTIFY);

                    }
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.queryGroupDetail(targetId);
        presenter.queryGroupMembers(targetId);
        presenter.groupApplyList(targetId);
    }

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

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

    @Override
    public void onConversation(boolean b) {
        cb_message.setChecked(b);
    }

    @Override
    public void onGroupUsers(List<GroupMemberBean> data, String groupId) {
        this.data.clear();
        this.data.addAll(data);
        tv_group_member_list.setText("查看全部" + data.size() + "名群成员");
        for (int i = 0; i < data.size(); i++) {
            try {
                GroupMemberBean usersBean = data.get(i);
                String id = usersBean.getUserId() + "";
                String name = usersBean.getNickname();
                String title = usersBean.getRoleType();
                String nameStr = TextUtils.isEmpty(title) ? name : name + "(" + title + ")";
                if (!TextUtils.isEmpty(id)) {
                    RongIM.getInstance().refreshGroupUserInfoCache(new GroupUserInfo(groupId, id, nameStr));
                }
            } catch (Exception e) {
            }

        }
    }

    @Override
    public void onQueryGroupDetail(RongIMGroupInfo data) {
        if (null != data) {
            iv_portrait.setImageResource(ChatGroupHelper.getChatGroupAvatarFromId(data.getId()));
            if (!TextUtils.isEmpty(data.getMemberNum())) {
                tv_class_num.setVisibility(View.VISIBLE);
                tv_class_num.setText(data.getMemberNum() + "/500");
            } else {
                tv_class_num.setVisibility(View.GONE);
            }
            tv_group_name.setText(data.getName());
            tv_group_name_remarks.setText(data.getName());
        }
    }

    @Override
    public void dissolveChatGroupSuccess(String targetId) {
        ToastUtil.getInstance().showShort("解散成功");
        JumpUtils.jumpMain(2);
    }

    @Override
    public void groupApplyListSuccess(List<GroupApplyBean> data) {
        if (!checkActivityExist()) {
            return;
        }
        if (tv_group_apply_count == null) {
            return;
        }
        if (data != null && data.size() > 0) {
            tv_group_apply_count.setText(data.size() + "人");
        } else {
            tv_group_apply_count.setText("0人");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_GROUP_REMARKS_CODE) {
                tv_group_name_remarks.setText(data.getStringExtra("remarks"));
                tv_group_name.setText(data.getStringExtra("remarks"));
            }
        }
    }
}
