package com.gh.gamecenter.energy.view

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gh.gamecenter.common.baselist.ListFragment
import com.gh.gamecenter.common.baselist.LoadType
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.dip2px
import com.gh.gamecenter.common.utils.toColor
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.NumberUtils.findMax
import com.gh.gamecenter.energy.R
import com.gh.gamecenter.energy.databinding.FragmentCommodityListBinding
import com.gh.gamecenter.energy.databinding.ItemFilterCommodityCategoryBinding
import com.gh.gamecenter.energy.databinding.LayoutFilterCategoryBinding
import com.gh.gamecenter.energy.entity.CommodityCategoryEntity
import com.gh.gamecenter.energy.entity.CommodityEntity
import com.gh.gamecenter.energy.entity.Size
import com.gh.gamecenter.energy.utils.IntegralLogHelper
import com.google.android.flexbox.FlexboxLayout

class CommodityFragment : ListFragment<CommodityEntity, CommodityViewModel>() {

    private var mAdapter: CommodityAdapter? = null
    private lateinit var mBinding: FragmentCommodityListBinding
    private var mCategoryList: ArrayList<CommodityCategoryEntity>? = null
    private var mCategory: CommodityCategoryEntity? = null
    private var mLastPositions: IntArray? = null
    private var mLastVisibleItemPosition = 0
    private var mHaveLoad = false
    private var mCurrentIndex = 0
    private var mCategoryItemWidth = 0
    private var mPopupWindow: PopupWindow? = null

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentCommodityListBinding.inflate(layoutInflater).apply { mBinding = this }.root

    override fun provideListViewModel(): CommodityViewModel {
        mEntrance = requireArguments().getString(EntranceConsts.KEY_ENTRANCE) ?: ""
        mCategory = requireArguments().getParcelable(EntranceConsts.KEY_CATEGORY)
        val factory = CommodityViewModel.Factory(mCategory?.id ?: "", mEntrance)
        return viewModelProvider(factory)
    }

    override fun provideListAdapter() = mAdapter
        ?: CommodityAdapter(
            requireContext(),
            mEntrance,
            mCategory ?: CommodityCategoryEntity()
        ).apply { mAdapter = this }

    override fun getItemDecoration() = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mListRv?.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mListRv?.layoutParams = (mListRv?.layoutParams as ViewGroup.MarginLayoutParams).apply {
            leftMargin = 12F.dip2px()
            rightMargin = 12F.dip2px()
        }

        requireArguments().getParcelableArrayList<CommodityCategoryEntity>(EntranceConsts.KEY_CATEGORY_LIST)?.run {
            mCategoryList = this

            mCategoryItemWidth = (resources.displayMetrics.widthPixels - ((14F * 2 + 8F * 4 + 28F).dip2px())) / 4

            mBinding.run {
                header.visibility = View.VISIBLE
                run outside@{
                    mCategoryList?.forEachIndexed { index, entity ->
                        if (index > 3) return@outside

                        val binding = ItemFilterCommodityCategoryBinding.inflate(layoutInflater).apply {
                            val params = LinearLayout.LayoutParams(mCategoryItemWidth, 28F.dip2px())
                            params.setMargins(8F.dip2px(), 0, 0, 0)
                            root.layoutParams = params

                            sizeTv.text = entity.name

                            if (index == mCurrentIndex) {
                                sizeTv.setTextColor(R.color.white.toColor())
                                sizeTv.setBackgroundResource(R.drawable.button_round_00dba4)
                            } else {
                                sizeTv.setTextColor(R.color.text_title.toColor())
                                sizeTv.setBackgroundResource(R.drawable.button_round_ebf9fa)
                            }

                            root.setOnClickListener {
                                if (index != mCurrentIndex) {
                                    IntegralLogHelper.logCommodityCategory(
                                        "click_tab_goods_catalog",
                                        "光能中心",
                                        "光能中心-商品分类",
                                        entity.id,
                                        entity.name
                                    )
                                    updateCategory(entity.id)
                                    mCurrentIndex = index
                                    updateCategoryBg()
                                }
                            }
                        }

                        categoryContainer.addView(binding.root)
                    }
                }

                openContainer.run {
                    if (mCategoryList?.size ?: 0 > 3) {
                        visibility = View.VISIBLE
                        setOnClickListener {
                            (parentFragment as? EnergyCenterFragment)?.openBottomSheet {
                                showCategoryPopWindow()
                            }
                        }
                    } else {
                        visibility = View.GONE
                        val binding = ItemFilterCommodityCategoryBinding.inflate(layoutInflater).apply {
                            val params = LinearLayout.LayoutParams(mCategoryItemWidth, 28F.dip2px())
                            params.setMargins(8F.dip2px(), 0, 0, 0)
                            root.layoutParams = params

                            sizeTv.text = "更多 >"
                            sizeTv.setTextColor(R.color.text_title.toColor())
                            sizeTv.setBackgroundResource(R.drawable.button_round_ebf9fa)

                            root.setOnClickListener {
                                IntegralLogHelper.run {
                                    log("click_energy_store", "光能中心", "光能中心-商品更多")
                                    log("click_more", "光能中心", "光能中心-右上角更多")
                                    log("view_energy_store", "光能屋")
                                }

                                startActivity(EnergyHouseActivity.getIntent(requireContext()))
                            }
                        }

                        categoryContainer.addView(binding.root)
                    }
                }
            }
        }

        mBinding.bottom.run {
            if (mEntrance == "光能中心") {
                setOnClickListener {
                    IntegralLogHelper.run {
                        log("click_energy_store", "光能中心", "光能中心-底部更多")
                        log("click_more", "光能中心", "光能中心-底部更多")
                        log("view_energy_store", "光能屋")
                    }

                    requireContext().startActivity(EnergyHouseActivity.getIntent(requireContext()))
                }
            } else {
                visibility = View.GONE
            }
        }

        mListRv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (mEntrance == "光能中心" && mListRv?.layoutManager?.itemCount ?: 0 == 11) {
                    mListRv?.layoutManager?.run {
                        if (childCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItemPosition >= itemCount - 1) {
                            mBinding.bottom.visibility = View.VISIBLE
                        } else {
                            mBinding.bottom.visibility = View.GONE
                        }
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (mEntrance == "光能中心" && mListRv?.layoutManager?.itemCount ?: 0 == 11) {
                    mListRv?.layoutManager?.run {
                        if (mLastPositions == null) {
                            mLastPositions = IntArray((this as StaggeredGridLayoutManager).spanCount)
                        }
                        (this as StaggeredGridLayoutManager).findLastVisibleItemPositions(mLastPositions)
                        mLastVisibleItemPosition = findMax(mLastPositions!!)
                    }
                }
            }
        })
    }

    private fun showCategoryPopWindow() {
        mCategoryList?.run {
            mPopupWindow = PopupWindow(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)

            val binding = LayoutFilterCategoryBinding.inflate(layoutInflater).apply {

                closeContainer.setOnClickListener { mPopupWindow?.dismiss() }
                background.setOnClickListener { mPopupWindow?.dismiss() }

                forEachIndexed { index, entity ->
                    val subBinding =
                        ItemFilterCommodityCategoryBinding.inflate(layoutInflater, flexboxLayout, false).apply {
                            val params = FlexboxLayout.LayoutParams(mCategoryItemWidth, 28F.dip2px())
                            var padTop = if (index <= 3) 10F.dip2px() else 8F.dip2px()
                            params.setMargins(8F.dip2px(), padTop, 0, 0)
                            root.layoutParams = params

                            sizeTv.text = entity.name

                            if (index == mCurrentIndex) {
                                sizeTv.setTextColor(R.color.white.toColor())
                                sizeTv.setBackgroundResource(R.drawable.button_round_00dba4)
                            } else {
                                sizeTv.setTextColor(R.color.text_title.toColor())
                                sizeTv.setBackgroundResource(R.drawable.button_round_ebf9fa)
                            }

                            root.setOnClickListener {
                                if (index != mCurrentIndex) {
                                    IntegralLogHelper.logCommodityCategory(
                                        "click_tab_goods_catalog",
                                        "光能中心",
                                        "光能中心-商品分类",
                                        entity.id,
                                        entity.name
                                    )
                                    mPopupWindow?.dismiss()
                                    updateCategory(entity.id)
                                    mCurrentIndex = index
                                    updateCategoryBg()
                                }
                            }
                        }

                    flexboxLayout.addView(subBinding.root)
                }

                val moreBinding =
                    ItemFilterCommodityCategoryBinding.inflate(layoutInflater, flexboxLayout, false).apply {
                        val params = FlexboxLayout.LayoutParams(mCategoryItemWidth, 28F.dip2px())
                        params.setMargins(8F.dip2px(), 8F.dip2px(), 0, 0)
                        root.layoutParams = params

                        sizeTv.text = "更多 >"
                        sizeTv.setTextColor(R.color.text_title.toColor())
                        sizeTv.setBackgroundResource(R.drawable.button_round_ebf9fa)

                        root.setOnClickListener {
                            IntegralLogHelper.run {
                                log("click_energy_store", "光能中心", "光能中心-商品更多")
                                log("click_more", "光能中心", "光能中心-右上角更多")
                                log("view_energy_store", "光能屋")
                            }

                            mPopupWindow?.dismiss()
                            startActivity(EnergyHouseActivity.getIntent(requireContext()))
                        }
                    }

                flexboxLayout.addView(moreBinding.root)
            }

            mPopupWindow?.run {
                contentView = binding.root
                isFocusable = true
                isOutsideTouchable = true
                animationStyle = 0
                showAsDropDown(mBinding.emptyView, 0, 0)
            }
        }

    }

    private fun updateCategoryBg() {
        mBinding.run {
            for (index in 0 until categoryContainer.childCount) {
                val sizeTv = categoryContainer.getChildAt(index) as TextView
                if (index == mCurrentIndex) {
                    sizeTv.setTextColor(R.color.white.toColor())
                    sizeTv.setBackgroundResource(R.drawable.button_round_00dba4)
                } else {
                    sizeTv.setTextColor(R.color.text_title.toColor())
                    sizeTv.setBackgroundResource(R.drawable.button_round_ebf9fa)
                }
            }
        }
    }

    override fun isAutomaticLoad(): Boolean {
        return if (mEntrance == "光能屋")
            false
        else
            super.isAutomaticLoad()
    }

    override fun onResume() {
        super.onResume()
        if (mEntrance == "光能屋") {
            if (parentFragment is EnergyHouseFragment) {
                (parentFragment as EnergyHouseFragment).run {
                    if (mHaveLoad) {
                        refreshPage(getCurrentSize())
                    } else {
                        mListViewModel.sortSize = getCurrentSize()
                        mListViewModel.load(LoadType.NORMAL)
                        mHaveLoad = true
                    }
                }
            }
        }
    }

    fun updateCategory(id: String) {
        mBinding.bottom.visibility = View.GONE
        mListViewModel.categoryId = id
        onLoadRefresh()
    }

    fun refreshPage(size: Size) {
        if (size != mListViewModel.sortSize) {
            mListViewModel.sortSize = size
            onRefresh()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        if (mEntrance == "光能中心") {
        mListRefresh?.isNestedScrollingEnabled = false
//        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mAdapter?.run {
            disposeAllTimer()
        }
    }

    override fun onLoadDone() {
        super.onLoadDone()
        mListRefresh?.isEnabled = false
    }

    override fun onLoadEmpty() {
        super.onLoadEmpty()
        // RecyclerView 被隐藏的话会导致不能 AppBar 不能滑动
        mListRv?.visibility = View.VISIBLE
    }

    override fun onLoadError() {
        super.onLoadError()
        mListRv?.visibility = View.VISIBLE
    }

    fun setNestedScrollingEnabled(enable: Boolean) {
        mListRv?.isNestedScrollingEnabled = enable
    }

    override fun onDarkModeChanged() {
        // 此页面暂不需要实现深色模式
    }
}