package cn.muchinfo.rma.view.base.future.markets

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING
import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.account.loginQeruy.ExternalExchanges
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsGroups
import cn.muchinfo.rma.global.data.account.loginQeruy.GoodsInfo
import cn.muchinfo.rma.global.database.AppDatabase
import cn.muchinfo.rma.global.room.Builder
import cn.muchinfo.rma.view.base.BaseFragment
import cn.muchinfo.rma.view.eventbus.QuoteMessageEvent
import com.blankj.utilcode.util.LogUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 报价牌的通用fragment
 */
class MarketFragment(data: ExternalExchanges) : BaseFragment<MarketBaseModel>() {

    var data: ExternalExchanges? = data

    companion object {
        fun getInstance(data: ExternalExchanges) = MarketFragment(data)
    }

    //此页面是否在显示，true行情下发可刷新列表 false则不刷新
    var canrefrashQuote: Boolean = false

    //region views
    private var _view: View? = null
    private var idMarketList: RecyclerView? = null // 列表

    val thisTag by lazy {
        this.tag
    }

    var fistShow: Int = 0
    var lastShow: Int = 0
//endregion

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _view = inflater.inflate(R.layout.market_fragment, container, false)
        viewModel.type = data?.exexchangename
        initViews()
        return _view
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onQuoteMessageEvent(quoteMessageEvent: QuoteMessageEvent) {
        /** 是否可刷新ui **/
        if (canrefrashQuote) {
            /** 行情推送过来的goodsid **/
            quoteMessageEvent.goodsid.forEach { goodid ->
                //找到相应商品信息
                val goodsInfo = viewModel.list?.find { it.goodsid == goodid }
                viewModel.list?.indexOf(goodsInfo)?.let {
                    if (it != -1) {//刷新相应item
                        idMarketList?.adapter?.notifyItemChanged(it)
                    }
                }
            }
        }
    }

    //注册eventbus
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    //加锁在显示时行情推送刷新ui
    override fun onResume() {
        super.onResume()
        canrefrashQuote = true
    }

    //加锁在不显示时行情推送不刷新ui且remove订阅信息
    override fun onPause() {
        super.onPause()
        thisTag?.let { viewModel.removeSubscriptQuote(tag = it) }
        canrefrashQuote = false
    }


    private fun initViews() {
        idMarketList = _view?.findViewById(R.id.id_market_list)

        val goodsGroupData = GlobalDataCollection.instance?.loginQueryData?.goodsgroups?.find {
            it.exexchangeid == data?.autoid
        }
        val list = Builder.getDatabase<AppDatabase>().goodsInfoDao.getGoodsGroups(
            goodsGroupData?.goodsgroupid ?: 0
        )
        if (list.size > 10) {
            lastShow = 10
        } else {
            if (list.size > 0) {
                lastShow = list.size
            }
        }

        val layoutManager = LinearLayoutManager(context)
        idMarketList?.layoutManager = layoutManager
        viewModel.list = list
        val adapter = viewModel.getAdapter()
        idMarketList?.adapter = adapter
        if (fistShow != -1 && lastShow != -1) {
            viewModel.queryQuoteDay(
                tag = thisTag ?: "",
                first = fistShow,
                last = lastShow
            ) { isCompleted, err ->
                if (isCompleted) {
                    adapter.notifyItemRangeChanged(fistShow, lastShow)
                }
            }
        }


        idMarketList?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                // DES: 找出当前可视Item位置
                val linearLayoutManager = idMarketList!!.layoutManager as LinearLayoutManager
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {// 这个判断是当recyclerview不滚动时
                    fistShow = linearLayoutManager.findFirstVisibleItemPosition()//获取第一个显示条目
                    lastShow = linearLayoutManager.findLastVisibleItemPosition()//获取最后一个显示条目
                    if (fistShow != -1 && lastShow != -1) {
                        viewModel.queryQuoteDay(
                            tag = thisTag ?: "",
                            first = fistShow,
                            last = lastShow
                        ) { isCompleted, err ->
                            if (isCompleted) {
                                adapter.notifyItemRangeChanged(fistShow, lastShow)
                            }
                        }
                    }

                }
            }
        })
    }

//region 函数

//endregion
}