package com.bc_chat.contacts

import android.view.View
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.ListModel
import com.bc_chat.bc_base.entity.contact.Contacts
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.AddFriendDialogFragment
import com.bc_chat.contacts.adapter.ContactListAdapter
import com.bc_chat.contacts.dataSource.ContactDataSource
import com.zhaohaoting.framework.abs.BaseIndexBarFragment
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.utils.DensityUtil
import com.zhaohaoting.framework.utils.Preferences
import com.zhaohaoting.framework.utils.observer.Observer
import com.zhaohaoting.framework.utils.observer.ObserverManager
import io.rong.imlib.model.Conversation
import kotlinx.android.synthetic.main.head_layout_contact.view.*

/**
 * author：Created by zhaohaoting on 2019/2/27
 * email：526309416@qq.com
 * desc：联系人
 */
class ContactListFragment : BaseIndexBarFragment<Contacts, ListModel<Contacts>>(), Observer<Any>,
        OnRefreshEndListener<ListModel<Contacts>> {

    companion object {
        const val tips_message_add: String = "add"
        const val tips_message_clear: String = "clear"
    }

    override fun getAdapter(): AbsRecyclerAdapter<Contacts, ListModel<Contacts>> = ContactListAdapter(activity)

    override fun getDataSource(): IAsyncDataSource<ListModel<Contacts>> = ContactDataSource()

    override fun onInit() {
        ObserverManager.getInstance().registerObserver(Const.ObserverKey.UPDATE_FRIEND_LIST, this)
        setOnStateChangeListener(this)
        recyclerView.setPadding(0, DensityUtil.dip2px(context, 10f), 0, 0)
        recyclerView.clipToPadding = false
    }

    override fun onEndRefresh(adapter: IDataAdapter<ListModel<Contacts>>?, result: ListModel<Contacts>?) {
        indexBar.setLetters(result?.index)
        if (result != null) {
            loadDoneListener?.onloadDone(result.list)
        }
    }

    override fun filter(data: Contacts?): Boolean {
        data?.let {
            return !it.userId.equals(Const.SYSTEM_NOTICE_ID)
        }
        return true
    }

    override fun getListData(): List<Contacts>? {
        return adapter.data?.list
    }

    override fun addHeadViews(adapter: AbsRecyclerAdapter<Contacts, ListModel<Contacts>>) {
        val headView = View.inflate(activity, R.layout.head_layout_contact, null)
        adapter.addHeaderView(headView)
        headView.tv_invite_friend.setOnClickListener {
            AddFriendDialogFragment().show(fragmentManager)
        }
        headView.tv_group_contact.setOnClickListener {
            ARouter.getInstance().build(RouteConfig.GROUP_LIST_ACTIVITY).navigation()
        }
        headView.tv_new_friend.setOnClickListener {
            ObserverManager.getInstance().notifyObserver(Const.ObserverKey.NEW_FRIEND, tips_message_clear)

            ARouter.getInstance().build(RouteConfig.FRIEND_APPLY_RECORD_ACTIVITY).navigation()
        }

        ObserverManager.getInstance().registerObserver(Const.ObserverKey.NEW_FRIEND, newFriendObserver)

        setNewMsgTxt(headView.tv_new_msg)

        if (Preferences.getBoolean("isShow", false)) {
            headView.tv_new_msg.visible()
        }

    }

    override fun itemClicked(vh: AbsRecyclerAdapter.BaseViewHolder<*>?, position: Int) {
        val contacts = adapter.data.list[position]
        ARouter.getInstance().navigation(ImRongService::class.java).startConversation(
                activity, Conversation.ConversationType.PRIVATE, contacts.userId!!, contacts.remark
                ?: contacts.nickname!!, null
        )
    }

    override fun onEvent(key: String?, var1: Any?) {
        when (key) {
            Const.ObserverKey.UPDATE_FRIEND_LIST -> refresh()
        }
    }

    fun setLoadDoneListener(loadDoneListener: OnLoadDoneListener) {
        this.loadDoneListener = loadDoneListener
    }

    private var loadDoneListener: OnLoadDoneListener? = null

    interface OnLoadDoneListener {
        fun onloadDone(contactList: List<Contacts>)
    }

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

    private val newFriendObserver = Observer<String> { key, var1 ->
        getActivity()?.runOnUiThread {
            if (var1.equals(tips_message_add)) {
                tvNewMsg.visible()
            } else if (var1.equals(tips_message_clear)) {
                tvNewMsg.gone()
            } else {
                tvNewMsg.gone()
            }
        }
    }

}
