package com.cheng.bole.ui.fragment.home

import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.RecyclerView.HORIZONTAL
import com.cheng.bole.R
import com.cheng.bole.bean.BidItemEntity
import com.cheng.bole.bean.MenuEntity
import com.cheng.bole.common.Constants
import com.cheng.bole.common.EventConstants
import com.cheng.bole.databinding.FragmentHomeBinding
import com.cheng.bole.event.HomeRefreshEvent
import com.cheng.bole.manager.EventReportManager
import com.cheng.bole.manager.SearchHistoryManager
import com.cheng.bole.manager.UserConfigManager
import com.cheng.bole.ui.activity.PublicActivity
import com.cheng.bole.ui.fragment.bid.BidAdapter
import com.cheng.bole.ui.fragment.bid.detail.BidDetailFragment
import com.cheng.bole.ui.fragment.home.bszz.BSZZFragment
import com.cheng.bole.ui.fragment.home.dljz.DLJZFragment
import com.cheng.bole.ui.fragment.home.qyzc.QYZCFragment
import com.cheng.bole.ui.fragment.home.zzdb.ZZDBFragment
import com.cheng.bole.ui.fragment.mine.vip.VipFragment
import com.cheng.bole.ui.fragment.search.SearchFragment
import com.cheng.bole.ui.fragment.search.list.SearchListFragment
import com.example.base.common.RxBus
import com.example.base.decoration.GridSpaceItemDecoration
import com.example.base.decoration.SpacesItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.onClick
import com.example.base.ui.list.ListFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.SpanUtils
import java.text.DecimalFormat
import kotlin.math.abs


/**
 * 首页
 */
class HomeFragment : ListFragment<FragmentHomeBinding, HomeViewModel, BidItemEntity>() {
    private val menuAdapter by lazy { HomeMenuAdapter() }

    private val keywordAdapter by lazy { HomeKeywordAdapter() }

    override fun noDataClick() {}

    override fun bindAdapter() = BidAdapter()

    private var item: BidItemEntity? = null

    override fun initView() {
        super.initView()
        binding.tvTitle.typeface = Constants.pmzdbt
        binding.tvHotTitle.typeface = Constants.pmzdbt
        binding.tvBidTitleNew.typeface = Constants.pmzdbt
        binding.tvBidTitle.typeface = Constants.pmzdbt

        binding.rvMenu.adapter = menuAdapter
        binding.rvMenu.addItemDecoration(GridSpaceItemDecoration(4, DensityUtils.dp2px(16f), 0))

        binding.rvHotKeyword.adapter = keywordAdapter
        binding.rvHotKeyword.addItemDecoration(SpacesItemDecoration(DensityUtils.dp2px(8f), HORIZONTAL))
    }

    override fun initData() {
        super.initData()
        if (UserConfigManager.getBidTypes().isEmpty()) {
            mViewModel.getBidTypeList(true)
        } else {
            menuAdapter.setList(MenuEntity.getHomeMenu())
        }
        mViewModel.getHotKeywordList("")
        firstLoad()
    }

    override fun initListener() {
        super.initListener()
        binding.appBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            val lp = binding.layoutContent.layoutParams as CoordinatorLayout.LayoutParams
            lp.topMargin = (-DensityUtils.dp2px(45f) * (1f - abs(verticalOffset).toFloat() / appBarLayout.totalScrollRange)).toInt()
            binding.layoutContent.layoutParams = lp
        }

        binding.tvSearch.onClick {
            PublicActivity.start(requireContext(), SearchFragment::class.java)
            EventReportManager.eventReport(EventConstants.JUMP_TO_BID_SEARCH)
        }

        binding.ivRefresh.onClick {
            if (keywordAdapter.data.isNotEmpty()) {
                mViewModel.getHotKeywordList(keywordAdapter.data.last())
            } else {
                mViewModel.getHotKeywordList("")
            }
        }

        mAdapter.setOnItemClickListener { _, _, i ->
            item = mAdapter.getItem(i)
            mViewModel.checkAuth()
        }

        keywordAdapter.setOnItemClickListener { _, _, i ->
            val item = keywordAdapter.getItem(i)
            PublicActivity.start(requireContext(), SearchListFragment::class.java,Pair("keyword", item))
            SearchHistoryManager.addHistory(item)
        }

        menuAdapter.setOnItemClickListener { _, _, i ->
            val item = menuAdapter.getItem(i)
            when(item.id) {
                "dljz" -> {
                    PublicActivity.start(requireContext(), DLJZFragment::class.java)
                    EventReportManager.eventReport(EventConstants.JUMP_TO_TOOLS, item.title)
                }
                "qyzc" -> {
                    PublicActivity.start(requireContext(), QYZCFragment::class.java)
                    EventReportManager.eventReport(EventConstants.JUMP_TO_TOOLS, item.title)
                }
                "bszz" -> {
                    PublicActivity.start(requireContext(), BSZZFragment::class.java)
                    EventReportManager.eventReport(EventConstants.JUMP_TO_TOOLS, item.title)
                }
                "zzdb" -> {
                    PublicActivity.start(requireContext(), ZZDBFragment::class.java)
                    EventReportManager.eventReport(EventConstants.JUMP_TO_TOOLS, item.title)
                }
                else -> {
                    PublicActivity.start(requireContext(), SearchListFragment::class.java, Pair("typeId", item.id))
                    EventReportManager.eventReport(EventConstants.JUMP_TO_BID_SEARCH, item.title)
                }
            }

        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.typeLiveData.observe(this) {
            UserConfigManager.saveBidTypes(it)
            menuAdapter.setList(MenuEntity.getHomeMenu())
        }

        mViewModel.recommendLiveData.observe(this) {
            keywordAdapter.setList(it)
        }

        mViewModel.totalLiveData.observe(this) {
            val total = it.toInt()
            SpanUtils.with(binding.tvUpdateCount)
                .append("已更新")
                .append(if (total < 10000) "$total" else "${DecimalFormat("0.#").format(total / 10000f)}万")
                .setForegroundColor(getColor(R.color.color_ff2222))
                .append("条")
                .create()
        }

        mViewModel.authLiveData.observe(this) {
            if (it.auth) {
                PublicActivity.start(
                    requireContext(),
                    BidDetailFragment::class.java,
                    Pair("id", item!!.id),
                    Pair("info_source", item!!.info_source)
                )
            } else {
                PublicActivity.start(requireContext(), VipFragment::class.java, Pair("origin", "view_bid"))
            }
        }

        val homeRefreshEvent = RxBus.defaultInstance.toObservable(HomeRefreshEvent::class.java).subscribe {
            firstLoad()
        }
        addDisposable(homeRefreshEvent)
    }
}