package com.bc_chat.contacts.ui.friend

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
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.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.contract.SetUserInfoContract
import com.bc_chat.bc_base.entity.User
import com.bc_chat.bc_base.presenter.SetUserInfoPresenter
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.databinding.ActivityUserDetailsInfoBinding
import com.zhaohaoting.framework.abs.BaseActivity
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.contactcard.message.ContactMessage
import io.rong.imkit.RongIM
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message

/**
 * author：Created by zhaohaoting on 2019/3/1
 * email：526309416@qq.com
 * desc：他人用户信息
 */
@Route(path = RouteConfig.USER_INFO_DETAILS_ACTIVITY)
class UserInfoDetailsActivity : BaseActivity<SetUserInfoPresenter>(), SetUserInfoContract.View, Observer<String> {

    companion object {
        const val REQUEST_CODE_FILE = 2251
        const val REQUEST_CODE_CHAT_RECORD = 2252
        const val REQUEST_CODE_REMARK = 2253
        const val REQUEST_CODE_ADDFRIEND = 2254

    }

    @Autowired
    @JvmField
    var userId: String? = null
    var user: User? = null

    private val binding by lazy {
        rootDataBinding as ActivityUserDetailsInfoBinding
    }

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

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

    @SuppressLint("WrongConstant")
    override fun initialize() {
        ARouter.getInstance().inject(this)
        binding.btnSendMessage.setOnClickListener {
            if (user == null) return@setOnClickListener
            ARouter.getInstance().navigation(ImRongService::class.java).startConversation(
                this, Conversation.ConversationType.PRIVATE, userId!!, user?.remark
                    ?: user?.nickname!!, null
            )
        }
        binding.tvShareCard.setOnClickListener {
            if (user == null) return@setOnClickListener
            val sendUserInfo = RongUserInfoManager.getInstance().getUserInfo(RongIMClient.getInstance().currentUserId)
            val sendUserName = if (sendUserInfo == null) "" else sendUserInfo.name
            val contactMessage = ContactMessage.obtain(
                userId,
                user?.nickname,
                user?.photo,
                RongIMClient.getInstance().currentUserId,
                sendUserName,
                ""
            )
            ARouter.getInstance().build(RouteConfig.FORWARD_ACTIVITY).withParcelableArrayList(
                "selectList",
                arrayListOf(Message.obtain(sendUserInfo.userId, Conversation.ConversationType.PRIVATE, contactMessage))
            ).navigation()

        }
//        binding.rlSystemNotice.setOnClickListener {
////            if (user == null) return@setOnClickListener
////            val messageReminderDialog = MessageReminderDialog()
////            messageReminderDialog.show(fragmentManager)
////            messageReminderDialog.setMessageReminderResultListener {
////                presenter.setUserNotice(userId!!, it.toString())
////            }
////        }
        RongIM.getInstance().getConversationNotificationStatus(Conversation.ConversationType.PRIVATE,
            userId, 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.PRIVATE,
                userId,
                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.tvChatFile.setOnClickListener {
            if (user == null) return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.CHAT_PICTURE_ACTIVITY)
                .withString("mTargetId", userId)
                .withString("conversationType", Conversation.ConversationType.PRIVATE.toString())
                .navigation(this, REQUEST_CODE_FILE)
        }
        binding.tvChatRecord.setOnClickListener {
            if (user == null) return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.SEARCH_CHAT_RECORD_ACTIVITY)
                .withString("mTargetId", userId)
                .withString("conversationType", Conversation.ConversationType.PRIVATE.toString())
                .navigation(this, REQUEST_CODE_CHAT_RECORD)
        }
        binding.tvRemark.setOnClickListener {
            if (user == null) return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.USER_REMARK_ACTIVITY)
                .withString("userId", userId)
                .withString("remark", user?.remark)
                .navigation(this, REQUEST_CODE_REMARK)
        }
        binding.btnAddFriend.setOnClickListener {
            if (user == null) return@setOnClickListener
            ARouter.getInstance().build(RouteConfig.ADD_FRIEND_ACTIVITY)
                .withParcelable("userInfo", user)
                .navigation(this, REQUEST_CODE_ADDFRIEND)
        }
        presenter.userInfoTask(userId!!)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.DELETE_FRIEND_LIST, this)
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.BLACK_SETTING, this)
    }

    override fun onEvent(key: String?, var1: String?) {
        when (key) {
            Const.ObserverKey.DELETE_FRIEND_LIST -> {
                if (var1.equals(userId)) {
                    finish()
                }
            }
            Const.ObserverKey.BLACK_SETTING -> {
                if (var1.equals(userId)) {
                    presenter.userInfoTask(userId!!, false)
                }
            }
        }
    }

    override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
        menu?.clear()
        if (user != null && user?.is_myFriend == 1 && !Const.SERVICE_ID.contains(user?.userId!!)) {
            menu?.add("")!!.setIcon(R.mipmap.top_bar_white_more).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        }
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        ARouter.getInstance().build(RouteConfig.MORE_SETTING_ACTIVITY).withString("userId", userId!!)
            .withInt("is_report", user?.is_report!!).withInt("is_block", user?.is_block!!).navigation()
        return true
    }

    override fun userInfoSuccess(user: User?) {
        if (user == null) return
        this.user = user
        invalidateOptionsMenu()
        if (user.is_myFriend == 0) {
            binding.btnAddFriend.visible()
            binding.btnSendMessage.gone()
            binding.llFriendLayout.gone()
        } else {
            binding.btnAddFriend.gone()
            binding.btnSendMessage.visible()
            binding.llFriendLayout.visible()
        }
        if (Const.SERVICE_ID.contains(user.userId)) {
            binding.btnAddFriend.gone()
        }
        GlideUtils.loadCircleImage(this, user.photo, binding.ivHeader)
        binding.tvName.text = user.remark ?: user.nickname
        binding.tvDesc.text = user.introduction
        binding.systemNoticeState.text = when (user.type) {
            2 -> if (user.endTime?.toLong()!! > System.currentTimeMillis() / 1000) "关闭1小时" else "开"
            3 -> if (user.endTime?.toLong()!! > System.currentTimeMillis() / 1000) "关闭8小时" else "开"
            4 -> if (user.endTime?.toLong()!! > System.currentTimeMillis() / 1000) "关闭2天" else "开"
            5 -> "关闭"
            else -> "开"
        }
    }

    override fun userInfoFailure(e: Exception) {
    }

    override fun userNoticeSuccess() {
        ToastUtils.show("设置成功")
        presenter.userInfoTask(userId!!, false)
    }

    override fun userNoticeFailure(e: Exception) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (REQUEST_CODE_REMARK == requestCode) {
            presenter.userInfoTask(userId!!, false)
        }
        if (REQUEST_CODE_ADDFRIEND == requestCode) {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.DELETE_FRIEND_LIST, this)
        ObserverManager.getInstance().unregisterObserver(Const.ObserverKey.BLACK_SETTING, this)
    }
}
