package com.develop.main.init.ui

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.develop.base.databinding.FragmentCommeListBinding
import com.develop.food.base.data.CategoryType
import com.develop.food.base.data.DataFactory
import com.develop.food.base.data.SortedType
import com.develop.food.base.data.model.FilterSortModel
import com.develop.food.base.data.model.FoodContentModel
import com.develop.food.base.data.model.HomeBannerModel
import com.develop.food.base.repo.entity.DevRecipeCategory
import com.develop.food.base.router.Screens
import com.develop.food.base.router.navigateTo
import com.develop.food.base.ui.ViewBindingFragment
import com.develop.food.base.utils.ResDimension
import com.develop.food.base.widgets.CommonPopupWindow
import com.develop.food.base.widgets.FilterSortViewLayout
import com.develop.main.R
import com.develop.main.init.ui.adapter.CategoryAdapter
import com.develop.main.init.ui.adapter.RecipesMainAdapter
import com.develop.main.init.ui.adapter.SortAdapter
import com.develop.main.init.ui.provider.*
import com.develop.main.init.ui.viewmodel.HomeViewModel


class RecipesFragment : ViewBindingFragment<FragmentCommeListBinding>() {
    private var recipesMainAdapter = RecipesMainAdapter()

    private var categoryAdapter = CategoryAdapter()
    private var sortAdapter = SortAdapter()

    private var categoryDataList = mutableListOf<DevRecipeCategory>()
    private var sortDataList = mutableListOf<FilterSortModel>()

    private val homeViewModel by activityViewModels<HomeViewModel>()

    private var categoryCode: String = ""
    private var lastPos = 0

    private val filterPopupWindow by lazy {
        CommonPopupWindow.ViewBuilder<FilterSortViewLayout>()
            .width(ResDimension(R.dimen.convert_626px).toInt())
            .height(ResDimension(R.dimen.convert_768px).toInt())
            .outsideTouchable(true)
            .focusable(true)
            .alpha(0.5f)
            .clippingEnabled(false)
            .view(FilterSortViewLayout(hostActivity))
            .intercept { popupWindow, view ->

            }
            .onShowBefore { popupWindow, view ->
                val filterRecycler = view.findViewById<RecyclerView>(R.id.filter_recycle)
                filterRecycler.adapter = categoryAdapter
            }
            .build<ViewDataBinding>(hostActivity)
    }

    private val sortPopupWindow by lazy {
        CommonPopupWindow.ViewBuilder<FilterSortViewLayout>()
            .width(ResDimension(R.dimen.convert_626px).toInt())
            .height(RelativeLayout.LayoutParams.WRAP_CONTENT)
            .outsideTouchable(true)
            .focusable(true)
            .alpha(0.5f)
            .clippingEnabled(false)
            .view(FilterSortViewLayout(hostActivity))
            .intercept { popupWindow, view ->

            }
            .onShowBefore { popupWindow, view ->
                val filterRecycler = view.findViewById<RecyclerView>(R.id.filter_recycle)
                filterRecycler.adapter = sortAdapter
            }
            .build<ViewDataBinding>(hostActivity)
    }


    private var currentHotWord = ""

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentCommeListBinding {
        return FragmentCommeListBinding.inflate(inflater, container, false)
    }

    var scrollY = 0

    override fun onPostCreateView() {
        sortDataList.addAll(DataFactory.genSortNameList(resources))

        binding.recycleList.apply { adapter = recipesMainAdapter }
        binding.recycleList.addOnScrollListener(object : RecyclerView.OnScrollListener() {


            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                Log.i("ZM","onScrollStateChanged: " + recyclerView.computeVerticalScrollOffset())
                scrollY = recyclerView.computeVerticalScrollOffset();
                super.onScrollStateChanged(recyclerView, newState)
            }
        })

        recipesMainAdapter.apply {
            loadMoreModule.setOnLoadMoreListener {
                if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                    if (homeViewModel.currentPage < homeViewModel.totalPageSize) {
                        homeViewModel.getOnLineRecipeList(
                            categoryCode,
                            homeViewModel.currCategoryName,
                            isLoadMore = true
                        )
                    } else {
                        loadMoreModule.loadMoreEnd()
                    }
                } else {
                    loadMoreModule.loadMoreEnd()
                }
            }
            //banner的点击事件
            homeBannerProvider.onBannerItemClickListener =
                object : HomeBannerProvider.OnBannerItemClickListener {
                    override fun onNetRecipesClick(bannerModel: HomeBannerModel) {
                        homeViewModel.recipesType = HomeViewModel.RecipesType.ONLINE
                        homeViewModel.netFoodLiveData.postValue(true)
                        homeViewModel.getOnLineCategoryList()
                    }
                }

            functionProvider.onFunctionCallback = object : FunctionProvider.OnFunctionCallback {
                override fun onFilterClick(filterView: View) {
                    categoryAdapter.setList(categoryDataList)
                    filterPopupWindow.showAsDropDown(
                        filterView,
                        -ResDimension(R.dimen.convert_5px).toInt(),
                        0
                    )
                }

                override fun onSortClick(sortView: View) {
                    sortAdapter.setList(sortDataList)
                    sortPopupWindow.showAsDropDown(
                        sortView,
                        -ResDimension(R.dimen.convert_65px).toInt(),
                        0
                    )
                }

                override fun onSearchClick() {
                    currentHotWord = "" //清空搜索字符


                    //进入搜索页
                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                        homeViewModel.getOnLineHotTags()
                    } else {
                        recipesMainAdapter.setList(DataFactory.genTestSearchDataList())
                    }
                }

                override fun onInputSearch(searchContent: String) {
                    currentHotWord = searchContent
                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                        homeViewModel.getOnLineRecipeList("", currentHotWord)
                    } else {
                        homeViewModel.queryRecipesByHotWord(currentHotWord, CategoryType.All)
                    }

                }

                override fun onBackClick() {
                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                        homeViewModel.getOnLineCategoryList()
                    } else {
                        homeViewModel.queryLocalRecipes(categoryCode)
                    }
                }
            }

            categoryTabProvider.selectedListener =
                object : CategoryTabProvider.OnCategoryTabSelectedListener {
                    override fun onCurrentSelected(categoryType: CategoryType) {
                        if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                            homeViewModel.getOnLineRecipeList("", currentHotWord)
                        } else {
                            homeViewModel.queryRecipesByHotWord(currentHotWord, categoryType)
                        }
                    }
                }

            commonSearchProvider.hotWordsSelectedListener =
                object : CommonSearchProvider.OnHotWordsSelectedListener {
                    override fun onHotWordsSelected(hotWord: String) {

                        currentHotWord = hotWord
                        if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                            homeViewModel.getOnLineRecipeList("", currentHotWord)
                        } else {
                            homeViewModel.queryRecipesByHotWord(currentHotWord, CategoryType.All)
                            recipesMainAdapter.functionProvider.filterSortSearchView?.updateHotWord(
                                hotWord
                            )
                        }

                    }
                }
            recipesContentProvider.onRecipesContentClickListener =
                object : RecipesContentProvider.OnRecipesContentClickListener {
                    override fun onRecipesContentClick(
                        recipesContent: FoodContentModel,
                        position: Int
                    ) {
                        lastPos = position
                        navigateTo(Screens.Cook.COOK_DETAIL) {
                            withString(
                                "source", if (recipesContent.isNetRecipes) {
                                    "remote"
                                } else {
                                    "local"
                                }
                            )
                            withString("number", recipesContent.foodId)
                            withBoolean("isLike", recipesContent.isLike)
                            withString("recipesEdition", recipesContent.recipesEdition)
                        }
                    }
                }
        }

        homeViewModel.apply {
            refreshRecipesLiveData.observe(viewLifecycleOwner) {
                //从网络菜谱切回本地菜谱，更新数据
                homeViewModel.queryRecipesCategory()
            }

            //获取本地菜谱分类回调
            localCategoryLiveData.observe(viewLifecycleOwner) {
                categoryDataList = it
                //默认All
                categoryDataList.add(
                    0, DevRecipeCategory(
                        "", "", getString(R.string.all),
                        null, null, null
                    )
                )
                //默认All
                updateCategoryName(categoryDataList[0])
                updateSortName(0, false)
                categoryAdapter.setList(categoryDataList)
                binding.recycleList.scrollToPosition(0)
            }

            //获取对应分类菜谱回调
            localRecipesLiveData.observe(viewLifecycleOwner) {
                recipesMainAdapter.setList(it)
                binding.recycleList.scrollToPosition(0)
            }

            //获取线上菜谱列表回调
            onLineRecipesLiveData.observe(viewLifecycleOwner) {
                recipesMainAdapter.setList(it)
                binding.recycleList.scrollToPosition(0)
            }

            //获取线上分类回调
            onlineCategoryLiveData.observe(viewLifecycleOwner) {
                categoryDataList = it
                categoryDataList.add(
                    0, DevRecipeCategory(
                        "", "", getString(R.string.all),
                        null, null, null
                    )
                )
                updateCategoryName(categoryDataList[0])
                updateSortName(0, false)
                categoryAdapter.setList(categoryDataList)
                binding.recycleList.scrollToPosition(0)
            }
            //获取线上热门标签回调
            onLineHotTagsLiveData.observe(viewLifecycleOwner) {
                recipesMainAdapter.setList(DataFactory.genOnLineHotTags(it))
            }

            //搜索回调
            hotWordSearchRecipesLiveData.observe(viewLifecycleOwner) {
                recipesMainAdapter.setList(it)
                binding.recycleList.scrollToPosition(0)
            }
        }

        categoryAdapter.apply {
            setOnItemClickListener { adapter, view, position ->
                updateCategoryName(categoryDataList[position])
                categoryAdapter.updateSelectedPosition(position)
                filterPopupWindow.dismiss()
            }
        }
        sortAdapter.apply {
            setOnItemClickListener { adapter, view, position ->
                updateSortName(position)
                sortAdapter.updateSelectedPosition(position)
                sortPopupWindow.dismiss()
            }
        }


    }

    var firstResume= true;

    override fun onResume() {
        super.onResume()
        if(firstResume){
            if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                homeViewModel.getOnLineCategoryList()
            } else {
                homeViewModel.queryRecipesCategory()
            }
            firstResume = false
        }



    }

    private fun updateCategoryName(devRecipeCategory: DevRecipeCategory) {
        homeViewModel.currCategoryName = devRecipeCategory.name ?: ""

        recipesMainAdapter.functionProvider.filterSortSearchView?.updateFilterName(
            homeViewModel.currCategoryName
        )
        if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
            categoryCode = devRecipeCategory.code
            homeViewModel.getOnLineRecipeList(categoryCode, "")
        } else {
            categoryCode = devRecipeCategory.number.toString()
            homeViewModel.queryLocalRecipes(categoryCode)
        }
    }

    private fun updateSortName(pos: Int, needRefresh: Boolean = true) {
        recipesMainAdapter.functionProvider.filterSortSearchView?.updateSortName(
            sortDataList[pos].name
        )
        homeViewModel.sortedType = when (pos) {
            0 -> {
                SortedType.Popular
            }
            1 -> {
                SortedType.Newest
            }
            2 -> {
                SortedType.Score
            }
            else -> {
                SortedType.Popular
            }
        }
        if (needRefresh) {
            if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                homeViewModel.getOnLineRecipeList(categoryCode, "")
            } else {
                homeViewModel.queryLocalRecipes(categoryCode)
            }
        }
    }


}