package com.bc_chat.im.activity

import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.FrameLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.im.R
import com.bc_chat.im.adapter.MessageListAdapter
import com.shizhefei.view.coolrefreshview.CoolRefreshView
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener
import com.shizhefei.view.coolrefreshview.header.MaterialHeader
import com.zhaohaoting.framework.abs.contract.BaseContract
import com.zhaohaoting.framework.abs.presenter.AbsActivity
import com.zhaohaoting.framework.utils.RxSchedulers
import com.zhaohaoting.framework.utils.SimpleTextWatcher
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.disposables.Disposable
import io.rong.imkit.model.UIMessage
import io.rong.imkit.userInfoCache.RongUserInfoManager
import io.rong.imlib.RongCommonDefine
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.message.TextMessage
import org.jetbrains.anko.custom.forEachReversed

/**
 * author：Created by zhaohaoting on 2019/3/15
 * email：526309416@qq.com
 * desc：聊天记录
 */
@Route(path = RouteConfig.SEARCH_CHAT_RECORD_ACTIVITY)
class SearchChatRecordActivity : AbsActivity<BaseContract.BasePresenter>() {

    private var coolRefreshView: CoolRefreshView? = null
    private var mAdapter: MessageListAdapter? = null
    private var recyclerView: RecyclerView? = null
    private var flTitle: FrameLayout? = null
    private var flBottom: FrameLayout? = null
    private var searchView: EditText? = null
    private var conversationType: Conversation.ConversationType? = null
    private var mTargetId: String? = null
    private var lastMsgTime = 0L //时间  最后一条
    private var selectIndex = 0 //查询为空最大次数

    private var layoutManager: LinearLayoutManager? = null

    private val objectNames = ArrayList<String>()

    private val adapterMsgList = ArrayList<UIMessage>()

    companion object {
        private const val SELECT_MAX_COUNT = 5 //查询为空最大次数
    }

    init {
        objectNames.add("RC:TxtMsg")
        objectNames.add("RC:VcMsg")
        objectNames.add("RC:ImgMsg")
        objectNames.add("RC:ImgTextMsg")
        objectNames.add("RC:FileMsg")
        objectNames.add("RC:LBSMsg")
        objectNames.add("RC:SightMsg")
        objectNames.add("RC:PSImgTxtMsg")
        objectNames.add("RC:PSMultiImgTxtMsg")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.search_chat_record_layout)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        searchView = findViewById(R.id.et_search)
        coolRefreshView = findViewById(R.id.funnyRefreshView)
        recyclerView = findViewById(R.id.recycler_view)
        flTitle = findViewById(R.id.fl_title)
        flBottom = findViewById(R.id.fl_bottom)
        recyclerView!!.itemAnimator = DefaultItemAnimator()
        layoutManager = LinearLayoutManager(this)
        layoutManager?.orientation = LinearLayoutManager.VERTICAL
        recyclerView!!.layoutManager = layoutManager
        coolRefreshView?.setPullHeader(MaterialHeader(this), true)
        onInit()
        mAdapter = MessageListAdapter(this, adapterMsgList)
        recyclerView?.adapter = mAdapter
        toolbar.setNavigationOnClickListener { v -> closeActivity() }
        searchView?.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                query()
            }
            return@setOnEditorActionListener false
        }
        searchView?.addTextChangedListener(object : SimpleTextWatcher() {
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                query()
            }
        })
        getDataSource(lastMsgTime)
    }

    private var disposable: Disposable? = null

    /**
     * 查询记录 连续五次查询为空 则停止
     */
    private fun getDataSource(oldTime: Long) {
        selectIndex = 0
        disposable = Flowable.create<List<UIMessage>>({ emitter ->
            val mMessages: ArrayList<UIMessage> = ArrayList()
            getHistoryMessages(mMessages, lastMsgTime) {
                emitter.onNext(mMessages)
            }
        }, BackpressureStrategy.BUFFER).compose(RxSchedulers.applyFlowableMainThread()).subscribe {
            coolRefreshView?.isRefreshing = false
            if (oldTime == 0L) {
                adapterMsgList.clear()
            }
            adapterMsgList.addAll(0, it)
            mAdapter?.notifyDataSetChanged()
            if (oldTime == 0L) {
                layoutManager?.scrollToPositionWithOffset(it.size - 1, 0)
            } else {
                layoutManager?.scrollToPositionWithOffset(it.size, 0)
            }
        }
    }

    private fun getHistoryMessages(mMessages: ArrayList<UIMessage>, oldTime: Long, Listener: (message: List<UIMessage>) -> Unit) {
        RongIMClient.getInstance().getHistoryMessages(conversationType, mTargetId, objectNames.toList(), oldTime, 10, RongCommonDefine.GetMessageDirection.FRONT, object : RongIMClient.ResultCallback<List<Message>>() {

            override fun onSuccess(p0: List<Message>?) {
                val query = searchView?.text.toString()
                if (p0 != null && p0.size > 0) {
                    p0.forEachReversed {
                        if (it.content.userInfo == null) {
                            it.content.userInfo = RongUserInfoManager.getInstance().getUserInfo(it.senderUserId)
                        }
                        if (it.content is TextMessage) {
                            if (it.content.userInfo.name.contains(query) || (it.content as TextMessage).content.contains(query)) {
                                mMessages.add(UIMessage.obtain(it))
                            }
                        } else {
                            if (it.content.userInfo.name.contains(query))
                                mMessages.add(UIMessage.obtain(it))
                        }
                    }
                    lastMsgTime = p0[p0.size - 1].receivedTime
                }
                if (mMessages.size > 0) {
                    Listener(mMessages)
                } else {
                    if (selectIndex >= SELECT_MAX_COUNT) {
                        Listener(mMessages)
                    } else {
                        selectIndex++
                        getHistoryMessages(mMessages, lastMsgTime, Listener)
                    }
                }
            }

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

    private fun onInit() {
        conversationType = Conversation.ConversationType.valueOf(intent.getStringExtra("conversationType"))
        mTargetId = intent.getStringExtra("mTargetId")
        coolRefreshView?.addOnPullListener(object : SimpleOnPullListener() {
            override fun onRefreshing(refreshView: CoolRefreshView?) {
                getDataSource(lastMsgTime)
            }
        })
    }

    fun query() {
        lastMsgTime = 0L
        getDataSource(lastMsgTime)
    }

    override fun initPresenter(): BaseContract.BasePresenter? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        if (disposable != null && !disposable?.isDisposed!!) {
            disposable?.dispose()
        }
    }
}
