package com.bc_chat.contacts.ui.choose

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.text.Editable
import android.text.TextWatcher
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.config.RouteConfig
import com.bc_chat.bc_base.entity.UserInfo
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.contacts.R
import com.bc_chat.contacts.contract.ChooseMemberContact
import com.bc_chat.contacts.databinding.ActivityChooseFriendBinding
import com.bc_chat.contacts.presenter.ChooseMemberPresenter
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.Utils
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imkit.mention.RongMentionManager
import org.jetbrains.anko.bundleOf
import java.lang.StringBuilder

/**
 * author：Created by zhaohaoting on 2019/2/28
 * email：526309416@qq.com
 * desc：选择好友
 */
@Route(path = RouteConfig.CHOOSE_FRIEND_ACTIVITY)
class ChooseFriendActivity : BaseActivity<ChooseMemberPresenter<*>>(), ChooseFriendFragment.OnSelectListener, TextWatcher, ChooseMemberContact.View {

    private val binding by lazy {
        rootDataBinding as ActivityChooseFriendBinding
    }

    companion object {
        const val CODE_CREATE_GROUP = 211
    }

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

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

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

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

    private var chooseFriendFragment: ChooseFriendFragment? = null
    private var selectList: ArrayList<UserInfo>? = null

    override fun initPresenter(): ChooseMemberPresenter<*> = ChooseMemberPresenter(this)

    override fun initialize() {
        ARouter.getInstance().inject(this)
        var singSelect = false
        chooseFriendFragment = ChooseFriendFragment()
        chooseFriendFragment?.setSelectListener(this)
        addFragment(chooseFriendFragment, R.id.fl_container)
        when (action) {
            Const.Action.CREATE_GROUP -> {
                title = "发起群聊"
                singSelect = false
            }
            Const.Action.INVITE_GROUP_MEMBER -> {
                title = "邀请"
                singSelect = false
            }
            Const.Action.KICK_GROUP_MEMBER -> {
                title = "踢出群成员"
                singSelect = false
            }
            Const.Action.GROUP_ASSIGNMENT -> {
                title = "转让群"
                singSelect = true
            }
            Const.Action.SET_GROUP_ADMIN -> {
                title = "设置管理"
                singSelect = false
            }
            Const.Action.ALTER_GROUP_MEMBER -> {
                title = "选择群成员"
                singSelect = true
            }
        }
        chooseFriendFragment?.arguments = bundleOf("action" to action, "groupId" to groupId, ChooseFriendFragment.IS_SING_SELECT to singSelect)
        binding.etAutoSearch.addTextChangedListener(this)
    }

    override fun onItemSelect(contacts: UserInfo) {
        when (action) {
            Const.Action.GROUP_ASSIGNMENT -> {
                CustomDialog.Builder(this)
                        .setTitle("转让群")
                        .setMessage("确定要将该群转让给该成员吗？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定") { dialog, which ->
                            presenter.assignmentGroup(groupId!!, contacts.userId!!,contacts.nickname!!)
                        }.create().show()
            }
            Const.Action.ALTER_GROUP_MEMBER -> {
                RongMentionManager.getInstance().mentionMember(io.rong.imlib.model.UserInfo(contacts.userId, contacts.nickname, Uri.parse(contacts?.photo)));
                finish()
            }
            else -> {
                //如果是单选点击则直接回传  多选则选择
                setResult(Activity.RESULT_OK, Intent().putExtra("contacts", contacts))
                finish()
            }
        }
    }

    override fun onItemSelectList(contactList: ArrayList<UserInfo>) {
        selectList = contactList
    }

    override fun afterTextChanged(s: Editable?) {
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (chooseFriendFragment != null && chooseFriendFragment!!.isAdded) {
            chooseFriendFragment!!.filter(s)
        }
    }

    override fun addGroupMemberSuccess() {
        ToastUtils.show("添加成功")
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun addGroupMemberFailure(exception: Exception) {
    }

    override fun kickoutGroupMemberSuccess() {
        ToastUtils.show("移除成功")
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun kickoutGroupMemberFailure(exception: Exception) {
    }

    override fun assignmentGroupSuccess() {
        ToastUtils.show("群转让成功")
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun assignmentGroupFailure(exception: Exception) {
    }

    override fun addGroupAdminSuccess() {
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.REFRESH_GROUP_MEMBER, groupId)
        ToastUtils.show("设置成功")
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun addGroupAdminFailure(exception: Exception) {
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        when (action) {
            Const.Action.CREATE_GROUP -> menu.add("下一步").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
            Const.Action.INVITE_GROUP_MEMBER -> menu.add("确定").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
            Const.Action.KICK_GROUP_MEMBER -> menu.add("确定").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
            Const.Action.SET_GROUP_ADMIN -> menu.add("确定").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (action) {
            Const.Action.CREATE_GROUP -> {
                if (Utils.listIsEmpty(selectList)) {
                    ToastUtils.show("请选择好友")
                } else {
                    ARouter.getInstance().build(RouteConfig.CREATE_GROUP_ACTIVITY).withParcelableArrayList("contactList", selectList)
                            .navigation(this, CODE_CREATE_GROUP)
                }
            }
            Const.Action.INVITE_GROUP_MEMBER -> {
                if (Utils.listIsEmpty(selectList)) {
                    ToastUtils.show("请选择好友")
                } else {
                    CustomDialog.Builder(this)
                            .setTitle("邀请好友")
                            .setMessage("确定要邀请选中好友进入该群吗？")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定") { dialog, which ->
                                presenter.addGroupMember(groupId!!, groupName!!, getSeletName(), userName!!, getSeletIds())
                            }.create().show()

                }
            }
            Const.Action.KICK_GROUP_MEMBER -> {
                if (Utils.listIsEmpty(selectList)) {
                    ToastUtils.show("请选择群成员")
                } else {
                    CustomDialog.Builder(this)
                            .setTitle("踢出群成员")
                            .setMessage("确定要踢出选中的成员吗？")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定") { dialog, which ->
                                presenter.kickoutGroupMember(groupId!!, userName, getSeletName(), getSeletIds())
                            }.create().show()

                }
            }
            Const.Action.SET_GROUP_ADMIN -> {
                if (Utils.listIsEmpty(selectList)) {
                    ToastUtils.show("请选择群成员")
                } else {
                    CustomDialog.Builder(this)
                            .setTitle("设置群管理")
                            .setMessage("确定要将选中的成员设置为管理员吗？")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定") { dialog, which ->
                                presenter.addGroupAdmin(groupId!!, getSeletName(), userName!!, getSeletIds())
                            }.create().show()

                }
            }

        }
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == CODE_CREATE_GROUP) {
            finish()
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_choose_friend
    }

    private fun getSeletIds(): String {
        val sb = StringBuilder()
        selectList?.forEach {
            sb.append(it.userId).append(",")
        }
        if (sb.length > 1) {
            sb.delete(sb.length - 1, sb.length)
        }
        return sb.toString()
    }

    private fun getSeletName(): String {
        val sb = StringBuilder()
        selectList?.forEach {
            sb.append(it.nickname).append(",")
        }
        if (sb.length > 1) {
            sb.delete(sb.length - 1, sb.length)
        }
        return sb.toString()
    }

}
