package com.bc_chat.contacts.ui.group

import android.app.Activity
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
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.entity.UserInfo
import com.bc_chat.bc_base.utils.AppConfig
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.bc_base.view.PictureDialogFragment
import com.bc_chat.contacts.R
import com.bc_chat.contacts.adapter.MemberListAdapter
import com.bc_chat.contacts.contract.CreateGroupContract
import com.bc_chat.contacts.presenter.CreateGroupPresenter
import com.zhaohaoting.framework.abs.NoRefreshRecyclerActivity
import com.zhaohaoting.framework.abs.adapter.AbsRecyclerAdapter
import com.zhaohaoting.framework.utils.ToastUtils
import com.zhaohaoting.framework.utils.glid.GlideUtils
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imlib.model.Conversation
import org.jetbrains.anko.bundleOf

/**
 * author：Created by zhaohaoting on 2019/3/7
 * email：526309416@qq.com
 * desc：创建群
 */
@Route(path = RouteConfig.CREATE_GROUP_ACTIVITY)
class CreateGroupActivity : NoRefreshRecyclerActivity<UserInfo, List<UserInfo>>(), CreateGroupContract.View {

    private var createGroupPresenter: CreateGroupPresenter? = null

    var contactList: ArrayList<UserInfo>? = null

    var tvGroupName: EditText? = null
    var ivGroupHead: ImageView? = null
    var tvMemberCount: TextView? = null
    var photoPath: String? = ""
    var groupName: String? = ""

    override fun onInit() {
        ARouter.getInstance().inject(this)
        createGroupPresenter = presenter as CreateGroupPresenter
        contactList = intent.getParcelableArrayListExtra("contactList")
    }

    override fun getAdapter(): AbsRecyclerAdapter<UserInfo, List<UserInfo>> {
        return MemberListAdapter(this, contactList!!)
    }

    override fun addHeadViews(adapter: AbsRecyclerAdapter<UserInfo, List<UserInfo>>?) {
        val headView = View.inflate(this, R.layout.activity_create_group, null)
        tvGroupName = headView.findViewById(R.id.et_nick_name)
        ivGroupHead = headView.findViewById(R.id.iv_head)
        tvMemberCount = headView.findViewById(R.id.tv_group_count)
        tvMemberCount?.text = getString(R.string._count_group_member,contactList?.size)
        ivGroupHead?.setOnClickListener {
            val pictureDialogFragment = PictureDialogFragment()
            pictureDialogFragment.arguments = bundleOf("isCrop" to true, "aspectX" to 1000, "aspectY" to 1000, "width" to 300, "height" to 300)
            pictureDialogFragment.setPicturePhotoPathLinstener {
                photoPath = it
                GlideUtils.loadCircleImage(this, "file://$photoPath", ivGroupHead)
            }
            pictureDialogFragment.show(fragmentManager)
        }
        adapter?.addHeaderView(headView)
    }

    override fun initPresenter(): CreateGroupPresenter = CreateGroupPresenter(this)


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menu?.add("完成")?.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        groupName = tvGroupName?.text.toString().trim()
        if (groupName.isNullOrEmpty()) {
            ToastUtils.show("请输入群名称")
            return true
        }
        if (TextUtils.isEmpty(photoPath)) {
            createGroupPresenter?.upload(arrayListOf())
        } else {
            createGroupPresenter?.upload(arrayListOf(photoPath))
        }
        return true
    }

    private fun getIdList(): String {
        val sb = StringBuilder()
        contactList?.forEach {
            sb.append(it.userId).append(",")
        }
        sb.append(AppConfig.instance.getUser().userId)
        return sb.toString()
    }

    override fun createGroupSuccess(groupId: String) {
        ARouter.getInstance().navigation(ImRongService::class.java).startConversation(this, Conversation.ConversationType.GROUP, groupId, groupName!!, null)
        ObserverManager.getInstance().notifyObserver(Const.ObserverKey.CREATE_GROUP,groupId)
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun createGroupFailure(exception: Exception) {
    }

    override fun uploadSuccess(paths: MutableList<String>) {
        val user = AppConfig.instance.getUser()
        if (paths.size > 0) {
            createGroupPresenter?.createGroup(groupName!!, user.nickname!!, getIdList(), paths[0])
        } else {
            createGroupPresenter?.createGroup(groupName!!, user.nickname!!, getIdList())
        }
    }

    override fun uploadFailure(e: Exception?) {
    }
}