package com.bc_chat.contacts.ui.group

import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.TipsMessage
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.entity.User
import com.bc_chat.bc_base.entity.dao.GroupMemberDao
import com.bc_chat.bc_base.entity.dao.group.TGroupMember
import com.bc_chat.bc_base.entity.group.Forbidden
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.utils.gone
import com.bc_chat.bc_base.utils.visible
import com.bc_chat.contacts.R
import com.bc_chat.contacts.contract.GroupMemberManagerContract
import com.bc_chat.contacts.databinding.ActivityGroupUserinfoBinding
import com.bc_chat.contacts.presenter.GroupMemberManagerPresenter
import com.bc_chat.contacts.view.ForbiddenFragmentDialog
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.imagepicker.camera.util.LogUtil
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.glid.GlideUtils
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.RongIM
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.IRongCallback
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message

/**
 * author：Created by zhaohaoting on 2019/3/18
 * email：526309416@qq.com
 * desc：
 */
@Route(path = RouteConfig.GROUP_MEMBER_ACTIVITY)
class GroupUserInfoActivity : BaseActivity<GroupMemberManagerPresenter>(), GroupMemberManagerContract.View {

    private val binding by lazy {
        rootDataBinding as ActivityGroupUserinfoBinding
    }

    @JvmField
    @Autowired
    var userId: String? = ""

    @JvmField
    @Autowired
    var groupId: String? = ""

    private var userGroupMember: TGroupMember? = null

    override fun initPresenter(): GroupMemberManagerPresenter? = GroupMemberManagerPresenter(this)

    override fun getLayoutResId(): Int = R.layout.activity_group_userinfo

    override fun initialize() {
        ARouter.getInstance().inject(this)
        presenter.userInfoTask(userId!!)
        userGroupMember = GroupMemberDao.instance.findGroupMemberById(groupId!!, userId!!)
        val mineGroupMember = GroupMemberDao.instance.findGroupMemberById(groupId!!, RongIM.getInstance().currentUserId!!)
        title = userGroupMember?.groupUserName
        binding.tvName.text = userGroupMember?.groupUserName
        GlideUtils.loadCircleImage(this, userGroupMember?.groupUserPhoto, binding.ivHeader)
        if (userGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_LORDE) {  //此用户为群主 不可做任何操作
            binding.llForbidden.gone()
            binding.tvRemoveGroup.gone()
            binding.tvRevokeAdmin.gone()
        }
        if (userGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_ADMIN && mineGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_LORDE) {//此用户为管理 我为群主 可做任何操作
            binding.llForbidden.visible()
            binding.tvRemoveGroup.visible()
            binding.tvRevokeAdmin.visible()
        }
        if (userGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_ADMIN && mineGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_ADMIN) {//此用户和我都是管理 为群主 不可做任何操作
            binding.llForbidden.gone()
            binding.tvRemoveGroup.gone()
            binding.tvRevokeAdmin.gone()
        }
        if (userGroupMember?.role == Const.GROUP_ROLE.ROLE_GROUP_ORDINARY) {
            binding.llForbidden.visible()
            binding.tvRemoveGroup.visible()
            binding.tvRevokeAdmin.gone()
        }
        binding.llForbidden.setOnClickListener {
            val forbiddenFragmentDialog = ForbiddenFragmentDialog()
            forbiddenFragmentDialog.show(fragmentManager)
            forbiddenFragmentDialog.setForbiddenResultListener {
                if (it == 0) {
                    presenter.delForbidden(groupId!!, userId!!)
                } else {
                    presenter.forbidden(groupId!!, userId!!, userGroupMember?.groupUserName!!, it.toString())
                }
            }
        }
        binding.tvRevokeAdmin.setOnClickListener {
            CustomDialog.Builder(this)
                    .setTitle("移除管理员")
                    .setMessage("确定要移除该管理员吗？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        presenter.deleteAdmin(groupId!!, userId!!, userGroupMember?.groupUserName!!)
                    }.create().show()

        }
        binding.tvRemoveGroup.setOnClickListener {
            CustomDialog.Builder(this)
                    .setTitle("踢出群成员")
                    .setMessage("确定要踢出选中的成员吗？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        val currentUserId = RongIM.getInstance().currentUserId
                        val userInfo = RongUserInfoManager.getInstance().getUserInfo(currentUserId)
                        presenter.kickout(groupId!!, userInfo.name, userGroupMember?.groupUserName!!, userId!!)

                        val tipsMessage = TipsMessage.obtain(userId, "2", groupId)
                        RongIM.getInstance().sendMessage(Message.obtain(userId, Conversation.ConversationType.PUSH_SERVICE, tipsMessage),
                                "踢出群组", null, object : IRongCallback.ISendMessageCallback {
                            override fun onAttached(message: Message) {
                                LogUtil.d(message.toString())
                            }

                            override fun onSuccess(message: Message) {
                                LogUtil.d(message.toString())
                            }

                            override fun onError(message: Message, errorCode: RongIMClient.ErrorCode) {
                                LogUtil.d(message.toString())
                            }
                        })

                    }.create().show()
        }
        presenter.forbiddenState(groupId!!)
    }

    override fun userInfoSuccess(user: User?) {
        title = user?.remark ?: user?.nickname
        binding.tvName.text = user?.remark ?: user?.nickname
        GlideUtils.loadCircleImage(this, user?.photo, binding.ivHeader)
        binding.tvDesc.text = user?.introduction
    }

    override fun userInfoFailure(e: Exception) {
    }

    override fun deleteAdminSuccess() {
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.REFRESH_GROUP_MEMBER, groupId)
        ToastUtils.show("移除成功")
        finish()
    }

    override fun kickoutSuccess() {
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.REFRESH_GROUP_MEMBER, groupId)
        ToastUtils.show("移除成功")
        finish()
    }

    override fun forbiddenSuccess() {
        ToastUtils.show("设置成功")
        binding.tvForbiddenState.text = "禁言中"
    }

    override fun delForbiddenSuccess() {
        ToastUtils.show("设置成功")
    }

    override fun forbiddenListSuccess(data: List<Forbidden>?) {
        data?.let { list ->
            data.forEach {
                if (it.userId?.equals(userId)!!) {
                    if (it.time?.toLong()!! > System.currentTimeMillis() / 1000) {
                        binding.tvForbiddenState.text = "禁言中"
                    }
                }
            }
        }
    }
}
