package com.cheng.blzb.ui.fragment.home

import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.recyclerview.widget.RecyclerView.HORIZONTAL
import com.cheng.blzb.R
import com.cheng.blzb.bean.BidItemEntity
import com.cheng.blzb.bean.MenuEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentHomeBinding
import com.cheng.blzb.event.HomeRefreshEvent
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.NotificationHelper
import com.cheng.blzb.manager.SearchHistoryManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.bid.BidAdapter
import com.cheng.blzb.ui.fragment.bid.detail.BidDetailFragment
import com.cheng.blzb.ui.fragment.home.bszz.BSZZFragment
import com.cheng.blzb.ui.fragment.home.dljz.DLJZFragment
import com.cheng.blzb.ui.fragment.home.qyzc.QYZCFragment
import com.cheng.blzb.ui.fragment.home.zzdb.ZZDBFragment
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.ui.fragment.search.SearchFragment
import com.cheng.blzb.ui.fragment.search.list.SearchListFragment
import com.cheng.blzb.utils.PermissionUtils
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.MMKVUtils
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(true)

    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))

        NotificationHelper.createDefaultChannel()
        if (MMKVUtils.getBoolean("request_notification_permission", true)) {
            PermissionUtils.checkNotificationPermission(requireActivity()) { isGranted ->
                if (!isGranted) NotificationHelper.showDisabledTip(requireActivity(), childFragmentManager)
                MMKVUtils.put("request_notification_permission", false)
            }
        }
    }

    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.00").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)
    }
}