package com.bc_chat.contacts.ui.group

import android.app.Activity
import android.content.Intent
import android.databinding.DataBindingUtil
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.contract.GroupInfoContract
import com.bc_chat.bc_base.entity.ListModel
import com.bc_chat.bc_base.entity.group.Group
import com.bc_chat.bc_base.entity.group.MemberBean
import com.bc_chat.bc_base.http.Api
import com.bc_chat.bc_base.task.GroupMemberDataSource
import com.bc_chat.bc_base.utils.AppConfig
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.bc_base.view.GroupMenuDialogFragment
import com.bc_chat.bc_base.view.PictureDialogFragment
import com.bc_chat.bc_base.view.QrCodeDialogFragment
import com.bc_chat.contacts.R
import com.bc_chat.contacts.adapter.GroupContactListAdapter
import com.bc_chat.contacts.contract.SetGroupInfoContract
import com.bc_chat.contacts.databinding.ActivityGroupInfoBinding
import com.bc_chat.contacts.presenter.SetGroupInfoPresenter
import com.zhaohaoting.framework.abs.BaseRecyclerActivity
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.mvchelper.mvc.IAsyncDataSource
import com.zhaohaoting.framework.mvchelper.mvc.IDataAdapter
import com.zhaohaoting.framework.mvchelper.mvc.OnRefreshEndListener
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.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.RongIM
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import org.jetbrains.anko.bundleOf

/**
 * author：Created by zhaohaoting on 2019/3/1
 * email：526309416@qq.com
 * desc：群详情
 */
@Route(path = RouteConfig.GROUP_INFO_ACTIVITY)
class GroupInfoActivity : BaseRecyclerActivity<MemberBean, ListModel<MemberBean>>(), GroupInfoContract.View,
    SetGroupInfoContract.View, OnRefreshEndListener<ListModel<MemberBean>>, Observer<String> {

    companion object {
        const val REQUEST_CODE_NOTICE = 2321
        const val REQUEST_CODE_INTRODUCE = 2322
        const val REQUEST_CODE_INVITE = 2323
        const val REQUEST_CODE_FILE = 2324
        const val REQUEST_CODE_CHAT_RECORD = 2325
        const val REQUEST_CODE_NAME = 2326
    }

    private var binding: ActivityGroupInfoBinding? = null
    private var userId: String? = null
    private var groupInfo: Group? = null
    private var groupMemberList: List<MemberBean>? = null
    private var currentMember: MemberBean? = null

    private val groupId by lazy {
        intent.getStringExtra("groupId")
    }

    private val mPresenter by lazy {
        presenter as SetGroupInfoPresenter
    }

    override fun getAdapter(): AbsRecyclerAdapter<MemberBean, ListModel<MemberBean>> =
        GroupContactListAdapter(this, GroupContactListAdapter.FROM_GROUP_INFO)

    override fun getDataSource(): IAsyncDataSource<ListModel<MemberBean>> = GroupMemberDataSource(groupId)

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

    override fun addHeadViews(adapter: AbsRecyclerAdapter<MemberBean, ListModel<MemberBean>>?) {
        binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_group_info, recyclerView, false)
        initEvent()
        adapter?.addHeaderView(binding?.root)
    }

    override fun onInit() {
        setOnStateChangeListener(this)
        userId = AppConfig.instance.getUser().userId
        mPresenter.groupinfoTask(groupId, false)

        ObserverManager.getInstance().registerObserver(Const.ObserverKey.REFRESH_GROUP_MEMBER, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.DISSOLUTION_GROUP, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.REFRESH_GROUP_INFO, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.EXIT_GROUP, this)
    }

    override fun onEvent(key: String?, var1: String?) {
        when (key) {
            Const.ObserverKey.REFRESH_GROUP_MEMBER -> refresh()
            Const.ObserverKey.DISSOLUTION_GROUP -> finish()
            Const.ObserverKey.REFRESH_GROUP_INFO -> mPresenter.groupinfoTask(groupId, false)
            Const.ObserverKey.FORWARD_MESSAGE -> finish()
            Const.ObserverKey.EXIT_GROUP -> finish()
        }
    }

    private fun initEvent() {
//        binding?.rlSystemNotice?.setOnClickListener {
//            currentMember ?: return@setOnClickListener
//            val messageReminderDialog = MessageReminderDialog()
//            messageReminderDialog.show(fragmentManager)
//            messageReminderDialog.setMessageReminderResultListener {
//                currentMember ?: return@setMessageReminderResultListener
//                mPresenter.setGroupInfo(groupId, getIds(), currentMember?.remark
//                        ?: currentMember?.nickname!!, type = it.toString())
//            }
//        }
        RongIM.getInstance().getConversationNotificationStatus(Conversation.ConversationType.GROUP,
            groupId, object : RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                override fun onSuccess(p0: Conversation.ConversationNotificationStatus?) {
                    binding?.cbNoticeState?.isSelected = (p0 != Conversation.ConversationNotificationStatus.DO_NOT_DISTURB)
                }

                override fun onError(p0: RongIMClient.ErrorCode?) {
                }
            })

        binding?.cbNoticeState?.setOnClickListener {
            val isSelect = it.isSelected
            showLoading()
            RongIM.getInstance().setConversationNotificationStatus(
                Conversation.ConversationType.GROUP,
                groupId,
                if (isSelect) Conversation.ConversationNotificationStatus.DO_NOT_DISTURB else Conversation.ConversationNotificationStatus.NOTIFY,
                object : RongIMClient.ResultCallback<Conversation.ConversationNotificationStatus>() {
                    override fun onSuccess(p0: Conversation.ConversationNotificationStatus?) {
                        it.isSelected = (p0 != Conversation.ConversationNotificationStatus.DO_NOT_DISTURB)
                        dismissLoading()
                    }

                    override fun onError(p0: RongIMClient.ErrorCode?) {
                        dismissLoading()
                    }
                })
        }
        binding?.rlGroupNotice?.setOnClickListener {
            currentMember ?: return@setOnClickListener
            if (currentMember?.type!! == Const.GROUP_ROLE.ROLE_GROUP_ORDINARY && groupInfo?.notice.isNullOrEmpty()) return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.GROUP_NOTICE_ACTIVITY)
                .withString("type", "notice")
                .withString("content", groupInfo?.notice)
                .withString("ids", getIds())
                .withString("groupId", groupId)
                .withInt("role", currentMember?.type!!)
                .withString("userName", currentMember?.remark ?: currentMember?.nickname!!)
                .navigation(this, REQUEST_CODE_NOTICE)
        }

        binding?.rlGroupIntroduce?.setOnClickListener {
            currentMember ?: return@setOnClickListener
            if (currentMember?.type!! == Const.GROUP_ROLE.ROLE_GROUP_ORDINARY && groupInfo?.introduction.isNullOrEmpty()) return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.GROUP_NOTICE_ACTIVITY)
                .withString("type", "introduce")
                .withString("content", groupInfo?.introduction)
                .withString("ids", getIds())
                .withString("groupId", groupId)
                .withInt("role", currentMember?.type!!)
                .withString("userName", currentMember?.remark ?: currentMember?.nickname!!)
                .navigation(this, REQUEST_CODE_INTRODUCE)
        }
        binding?.rlGroupAdmin?.setOnClickListener {
            currentMember ?: return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.GROUP_MANAGER_ACTIVITY)
                .withString("groupId", groupId)
                .withString("userName", currentMember?.nickname)
                .withString("groupName", groupInfo?.group_name)
                .withString("ordNoticeTop", groupInfo?.is_top)
                .withString("forbidden", groupInfo?.is_banned)
                .navigation(this, REQUEST_CODE_INVITE)
        }
        binding?.rlGroupQrCode?.setOnClickListener {
            currentMember ?: return@setOnClickListener
            val qrCodeDialogFragment = QrCodeDialogFragment()
            qrCodeDialogFragment.arguments = bundleOf(
                "photo" to groupInfo?.photo,
                "qrCodeName" to "user_${groupId}_qr_code",
                "url" to "${Api.SHARE_PATH}?source=bc_chat&type=${Const.QrType.GROUP_TYPE}&id=$groupId&name=${currentMember?.nickname}"
            )
            qrCodeDialogFragment.show(supportFragmentManager)
        }
        binding?.llInviteFriend?.setOnClickListener {
            currentMember ?: return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.CHOOSE_FRIEND_ACTIVITY)
                .withString("action", Const.Action.INVITE_GROUP_MEMBER)
                .withString("groupId", groupId)
                .withString("userName", currentMember?.nickname)
                .withString("groupName", groupInfo?.group_name)
                .navigation(this, REQUEST_CODE_INVITE)
        }
        binding?.rlChatFile?.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.CHAT_PICTURE_ACTIVITY)
                .withString("mTargetId", groupId)
                .withString("conversationType", Conversation.ConversationType.GROUP.toString())
                .navigation(this, REQUEST_CODE_FILE)
        }
        binding?.rlChatRecord?.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.SEARCH_CHAT_RECORD_ACTIVITY)
                .withString("mTargetId", groupId)
                .withString("conversationType", Conversation.ConversationType.GROUP.toString())
                .navigation(this, REQUEST_CODE_CHAT_RECORD)
        }
        binding?.rlUpdateHead?.setOnClickListener {
            judgePermission(Const.Permission.Key.STORAGE_CAMERA, *Const.Permission.Value.STORAGE_CAMERA)
        }
        binding?.llNickName?.setOnClickListener {
            currentMember ?: return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.GROUP_NAME_ACTIVITY)
                .withString("content", groupInfo?.group_name)
                .withString("ids", getIds())
                .withString("groupId", groupId)
                .withString("userName", currentMember?.remark ?: currentMember?.nickname!!)
                .navigation(this, REQUEST_CODE_NAME)
        }
    }

    override fun requestPermissionSuccess(requestCode: Int) {
        val pictureDialogFragment = PictureDialogFragment()
        pictureDialogFragment.arguments =
            bundleOf("isCrop" to true, "aspectX" to 1000, "aspectY" to 1000, "width" to 300, "height" to 300)
        pictureDialogFragment.setPicturePhotoPathLinstener {
            GlideUtils.loadCircleImage(this, "file://$it", binding?.ivGroupHead)
            mPresenter.upload(arrayListOf(it))
        }
        pictureDialogFragment.show(supportFragmentManager, "pictureDialogFragment")
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menu.add("").setIcon(R.mipmap.top_bar_more).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        val menuDialogFragment = GroupMenuDialogFragment()
        menuDialogFragment.arguments = bundleOf("role" to getMemberById(userId!!)?.type)
        menuDialogFragment.setOnGroupMenuListener {
            if (it == 1) {
                CustomDialog.Builder(this)
                    .setTitle("清除聊天记录")
                    .setMessage("清除聊天记录后无法恢复,您确定要清除吗？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        ARouter.getInstance().navigation(ImRongService::class.java)
                            .clearMessages(Conversation.ConversationType.GROUP, groupId) {
                                if (it) {
                                    ToastUtils.show("清除成功")
                                } else {
                                    ToastUtils.show("清除失败")
                                }
                            }
                    }.create().show()
            } else {
                CustomDialog.Builder(this)
                    .setTitle("退出群组")
                    .setMessage("您确定要退出该群组吗？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确定") { dialog, which ->
                        mPresenter.exitGroup(groupId, getNames(), getMemberById(userId!!)?.nickname, userId!!)
                    }.create().show()

            }
        }
        menuDialogFragment.show(fragmentManager)
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            REQUEST_CODE_NOTICE -> {
                val groupNotice = data?.getStringExtra("content")
                binding?.tvGroupNotice?.text = groupNotice
                groupInfo?.notice = groupNotice
            }

            REQUEST_CODE_INTRODUCE -> {
                val groupIntroduce = data?.getStringExtra("content")
                binding?.tvGroupIntroduce?.text = groupIntroduce
                groupInfo?.introduction = groupIntroduce
            }

            REQUEST_CODE_INVITE -> refresh()

            REQUEST_CODE_NAME -> binding?.tvGroupName?.text = data?.getStringExtra("content")
        }
    }

    override fun onEndRefresh(adapter: IDataAdapter<ListModel<MemberBean>>?, result: ListModel<MemberBean>?) {
        result?.let {
            groupMemberList = it.list
            binding?.tvGroupNum?.text = groupMemberList?.size.toString()
            currentMember = getMemberById(userId!!)
            if (currentMember?.type != Const.GROUP_ROLE.ROLE_GROUP_LORDE) {
                binding?.rlGroupAdmin.gone()
                binding?.rlGroupQrCode.gone()
                if (currentMember?.type == Const.GROUP_ROLE.ROLE_GROUP_ADMIN) { //管理员
                    binding?.llInviteFriend.visible()
                    binding?.llNickName?.isEnabled = true
                    binding?.rlUpdateHead?.visible()
                    binding?.ivUpdateName?.visible()
//                    binding?.rlGroupIntroduce?.isEnabled = true
//                    binding?.rlGroupNotice?.isEnabled = true
//                    binding?.ivGroupIntroduce.visible()
//                    binding?.ivGroupNotice.visible()
                } else {      //普通成员
                    binding?.llInviteFriend.gone()
                    binding?.llNickName?.isEnabled = false
                    binding?.rlUpdateHead?.gone()
                    binding?.ivUpdateName?.gone()
//                    binding?.rlGroupIntroduce?.isEnabled = false
//                    binding?.rlGroupNotice?.isEnabled = false
//                    binding?.ivGroupIntroduce.gone()
//                    binding?.ivGroupNotice.gone()
                }
            } else {//群主
                binding?.rlGroupQrCode.visible()
                binding?.llInviteFriend.visible()
                binding?.rlGroupAdmin.visible()
                binding?.llNickName?.isEnabled = true
                binding?.rlUpdateHead?.visible()
                binding?.ivUpdateName?.visible()
//                binding?.rlGroupIntroduce?.isEnabled = true
//                binding?.rlGroupNotice?.isEnabled = true
//                binding?.ivGroupIntroduce.visible()
//                binding?.ivGroupNotice.visible()
            }
        }
    }

    override fun onItemClick(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        if (currentMember == null) return
        val memberBean = adapter.data.list[position]
        if (currentMember?.type != Const.GROUP_ROLE.ROLE_GROUP_ORDINARY) {
            ARouter.getInstance().build(RouteConfig.GROUP_MEMBER_ACTIVITY).withString("userId", memberBean?.userId)
                .withString("groupId", groupId).navigation()
        }
    }

    override fun setGroupInfoSuccess() {
        mPresenter.groupinfoTask(groupId, false)
    }

    override fun setGroupInfoFailure(exception: Exception) {
    }

    override fun groupinfoSuccess(groupInfo: Group) {
        this.groupInfo = groupInfo
        binding?.let {
            GlideUtils.loadCircleImage(this, groupInfo.photo, it.ivGroupHead)
            it.tvGroupName.text = groupInfo.group_name
            it.tvGroupIntroduce.text = groupInfo.introduction
            it.tvGroupNotice.text = groupInfo.notice
            it.systemNoticeState.text = when (groupInfo.type) {
                2 -> if (groupInfo.endTime?.toLong()!! > System.currentTimeMillis() / 1000) "关闭1小时" else "开"
                3 -> if (groupInfo.endTime?.toLong()!! > System.currentTimeMillis() / 1000) "关闭8小时" else "开"
                4 -> if (groupInfo.endTime?.toLong()!! > System.currentTimeMillis() / 1000) "关闭2天" else "开"
                5 -> "关闭"
                else -> "开"
            }
        }
    }

    override fun groupinfoFailure(exception: Exception) {

    }

    override fun exitGroupSuccess() {
        ToastUtils.show("退出成功")
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.EXIT_GROUP, groupId)
    }

    override fun exitGroupFailure(exception: Exception) {
    }

    override fun uploadSuccess(paths: MutableList<String>?) {
        if (paths?.size!! > 0) {
            mPresenter.setGroupInfo(
                groupId, getIds(), currentMember?.remark
                    ?: currentMember?.nickname!!, photo = paths[0]
            )
        }
    }

    override fun uploadFailure(e: java.lang.Exception?) {
    }

    private fun getIds(): String {
        val builder = StringBuilder()
        adapter.data.list.forEach {
            builder.append(it.userId).append(",")
        }
        if (builder.length > 1)
            builder.delete(builder.length - 1, builder.length)
        return builder.toString()
    }

    private fun getNames(): String {
        val builder = StringBuilder()
        adapter.data.list.forEach {
            builder.append(it.nickname).append(",")
        }
        if (builder.length > 1)
            builder.delete(builder.length - 1, builder.length)
        return builder.toString()
    }

    private fun getMemberById(userId: String): MemberBean? {
        groupMemberList?.forEach {
            if (it.userId.equals(userId)) {
                return it
            }
        }
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.REFRESH_GROUP_MEMBER, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.DISSOLUTION_GROUP, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.REFRESH_GROUP_INFO, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.FORWARD_MESSAGE, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.EXIT_GROUP, this)
    }
}