package com.renrenliao.im.ui.activity

import android.view.MotionEvent
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.gyf.immersionbar.ktx.immersionBar
import com.renrenliao.im.R
import com.renrenliao.im.base.BaseVMActivity
import com.renrenliao.im.ext.gone
import com.renrenliao.im.ext.visible
import com.renrenliao.im.model.repository.LocalDataSource
import com.renrenliao.im.provider.ClarityPotion
import com.renrenliao.im.ui.fragment.AlarmFragment
import com.renrenliao.im.ui.fragment.DiscoverFragment
import com.renrenliao.im.ui.fragment.MineFragment
import com.renrenliao.im.ui.fragment.RrlFriendFragment
import com.renrenliao.im.utils.KeepLiveUtils
import com.renrenliao.im.utils.MDateUtils
import com.renrenliao.im.viewmodel.MainViewModel
import kotlinx.android.synthetic.main.layout_main_footbar.*
import kotlinx.coroutines.flow.collect
import net.openmob.mobileimsdk.android.core.AutoReLoginDaemon
import net.openmob.mobileimsdk.android.core.QoS4SendDaemon
import org.koin.androidx.viewmodel.ext.android.getViewModel

/**
 * token登陆验证  后 获取好友 群 写入数据库
 */

class MainActivity : BaseVMActivity<MainViewModel>() {

    private val fragmentList = mutableListOf<Fragment>()
    private var currentFragment: Fragment? = null//要显示的Fragment
    private var hideFragment: Fragment? = null//要隐藏的Fragment
    private var lastPosition: Int = 0
    private var mPosition: Int = 0

    init {
        fragmentList.run {
            add(AlarmFragment())
            add(RrlFriendFragment())
            add(DiscoverFragment())
            add(MineFragment())
        }
    }

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

    override fun initVM(): MainViewModel = getViewModel()

    override fun initView() {

        setSelectedFragment(0)
        for (i in 0 until tab_total.childCount) {
            tab_total.getChildAt(i).setOnClickListener {
                setSelectedFragment(i)
            }
        }
        //登陆IM
        QoS4SendDaemon.getInstance().startup(true)
        AutoReLoginDaemon.getInstance().start(true)

        //启动保活服务
        try {
            KeepLiveUtils.initKeepLive()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        //启动离线消息service
        //  val offlineService = Intent(this,OffLineMsgService::class.java)
        //   startService(offlineService)

    }

    override fun initData() {
        mViewModel.getData()
    }

    private fun tabStatus(tabId: Int) {
        for (i in 0 until tab_total.childCount) {
            val childAt: View = tab_total.getChildAt(i)
            childAt.isSelected = childAt.id == tabId
        }
    }

    private fun setSelectedFragment(position: Int) {
        if (position == 3) {
            immersionBar {
                statusBarColor(R.color.white)
                navigationBarColor(R.color.white)
                statusBarDarkFont(true, 0.2f)
            }
        } else {
            immersionBar {
                statusBarColor(R.color.main_theme_color)
                navigationBarColor(R.color.white)
                statusBarDarkFont(false)
            }
        }

        when (position) {
            0 -> {
                tabStatus(R.id.tab_alarm)
            }
            1 -> {
                tabStatus(R.id.tab_friend)
            }
            2 -> {
                tabStatus(R.id.tab_group)
            }
            3 -> {
                tabStatus(R.id.tab_more)
            }
        }

        val fragmentManager = supportFragmentManager
        val transaction = fragmentManager.beginTransaction()
        //要显示的fragment(解决了activity重建时新建实例的问题)
        currentFragment = fragmentManager.findFragmentByTag("fragment$position")
        hideFragment = fragmentManager.findFragmentByTag("fragment$lastPosition")

        if (position == lastPosition) {//如果位置相同
            if (currentFragment == null) {//如果fragment不存在(第一次启动应用的时候)
                currentFragment = fragmentList[position]
                transaction.add(R.id.main_content, currentFragment!!, "fragment$position")
            }//如果位置相同，且fragment存在，则不作任何操作
        }
        if (position != lastPosition) {//如果位置不同
            //如果要隐藏的fragment存在，则隐藏
            hideFragment?.let { transaction.hide(it) }
            if (currentFragment == null) {//如果要显示的fragment不存在，则新加并提交事务
                currentFragment = fragmentList[position]
                transaction.add(R.id.main_content, currentFragment!!, "fragment$position")
            } else {//如果要显示的存在则直接显示
                currentFragment?.let { transaction.show(it) }

            }
        }
        transaction.commit()//提交事务
        lastPosition = position//更新要隐藏的fragment的位置
        mPosition = position
    }


    override fun startObserve() {
//        mViewModel.friendLiveData.observe(this@MainActivity) {
//            LogUtils.error(it)
//        }

        lifecycleScope.launchWhenResumed {
            mViewModel.userInfo.collect {
                //mTvAbout.text = it
                //  LogUtils.error(it?.nickname)
                //   LogUtils.error(DataCacheUtils.getUserInfo()?.nickname)
            }
//            mViewModel.friendLiveData.collect {
//                LogUtils.error(it)
//            }
        }
        mViewModel.unReadLiveData.observe(this@MainActivity){
            it?.let {
                if (it>99){
                    tv_news.visible()
                    tv_news.text = "99"
                }else if (it in 1..99){
                    tv_news.visible()
                    tv_news.text = it.toString()
                }else{
                    tv_news.gone()
                }
            }

        }
    }

    private var lastTime: Long = 0

    override fun onBackPressed() {
        back()
    }

    private fun back() {
        if (MDateUtils.currentTimMillis() - lastTime < 2000) {
            ClarityPotion.exitApp()
        } else {
            //toast(getString(R.string.press_again_exit))

        }
        lastTime = System.currentTimeMillis()
    }



    interface MyTouchListener {
        fun onTouchEvent(event: MotionEvent)
    }

    private val myTouchListeners = mutableListOf<MyTouchListener>()

    fun registerMyTouchListener(listener: MyTouchListener) {
        myTouchListeners.add(listener)
    }

    fun unRegisterMyTouchListener(listener: MyTouchListener) {
        myTouchListeners.remove(listener)
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        for (listener in myTouchListeners) {
            listener.onTouchEvent(ev)
        }
        return super.dispatchTouchEvent(ev)
    }


}