package com.develop.main.init.ui

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat.getSystemService
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
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.event.RecipesEvent
import com.develop.food.base.event.RefreshDataEvent
import com.develop.food.base.event.RefreshLikeDataEvent
import com.develop.food.base.event.RefreshStarDataEvent
import com.develop.food.base.repo.FoodDataProvider.getResourcePath
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.utils.resId2Dimension
import com.develop.food.base.widgets.CancelConfirmDialog
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.CategoryTabProvider
import com.develop.main.init.ui.provider.CommonSearchProvider
import com.develop.main.init.ui.provider.FunctionProvider
import com.develop.main.init.ui.provider.HomeBannerProvider
import com.develop.main.init.ui.provider.RecipesContentProvider
import com.develop.main.init.ui.viewmodel.HomeViewModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File


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

    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 var recyclePosition = 0
    private var recycleBottom = false;
    private var isInitDate = false

    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)
                val triangle: View = view.findViewById(R.id.triangle)
                val param = triangle.layoutParams as RelativeLayout.LayoutParams
                param.marginStart = dp65
                triangle.layoutParams = param
                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)
                val triangle: View = view.findViewById(R.id.triangle)
                val param = triangle.layoutParams as RelativeLayout.LayoutParams
                param.addRule(RelativeLayout.CENTER_HORIZONTAL)
                triangle.layoutParams = param
                filterRecycler.adapter = sortAdapter
            }
            .build<ViewDataBinding>(hostActivity)
    }


    private var currentHotWord = ""

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

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

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

    var scrollY = 0

    override fun onPostCreateView() {
        Log.d("TAG Fragment","000000000000000000000000")

        sortDataList.addAll(DataFactory.genSortNameList(resources))
        categoryAdapter.homeViewModel = homeViewModel
        recipesMainAdapter = null
        recipesMainAdapter = RecipesMainAdapter()
        binding.recycleList.apply { adapter = recipesMainAdapter }

        binding.recycleList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {


                var lastPosition = -1
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //                    if (!hostActivity.isDestroyed){
//                        Glide.with(hostActivity).resumeRequests();//恢复Glide加载图片
//                    }

                    val layoutManager = recyclerView.layoutManager as LinearLayoutManager?
                    // 获取当前显示的第一个Item的位置
                    val firstVisiblePosition = layoutManager!!.findFirstVisibleItemPosition()
                    recyclePosition = firstVisiblePosition+1

                    //时判断界面显示的最后item的position是否等于itemCount总数-1也就是最后一个item的position
                    //如果相等则说明已经滑动到最后了
                    recycleBottom = lastPosition == recyclerView.layoutManager?.itemCount!!  -1
                }else {
                    //2024.01.19由于客户说，滑动图片加载慢的问题，所以把禁止方法去掉
//                    if (!hostActivity.isDestroyed){
//                        Glide.with(hostActivity).pauseRequests();//禁止Glide加载图片
//                    }
                }

            }
        })
//        binding.recycleList

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


            //本地菜谱分类pop
            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) {
                    if (searchContent.length>20){
                        showMsgDialog()
                        return
                    }
                    currentHotWord = searchContent
                    homeViewModel.saveHistoryWords(currentHotWord)
                    /**
                     * 由于多item 中EditText导致导致点不了
                     * 故这里把搜索功能模块抽出来写成Fragment来兼容
                     *
                     * */
//                    homeViewModel.searchContentData.postValue(true)
                    homeViewModel.searchContent.postValue(currentHotWord)

//                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
//                        homeViewModel.getOnLineRecipeList("", currentHotWord)
//                    } else {
//                        homeViewModel.queryRecipesByHotWord(currentHotWord, CategoryType.All)
//                    }

                }

                override fun onBackClick() {
                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                        (hostActivity as HomeActivity).showDialog()
                        homeViewModel.getOnLineCategoryList()
                    } else {
                        categoryAdapter.updateSelectedPosition(0)
                        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) {
                        homeViewModel.saveHistoryWords(currentHotWord)
                        currentHotWord = hotWord

//                        homeViewModel.searchContentData.postValue(true)
                        /**
                         * 由于多item 中EditText导致导致点不了
                         * 故这里把搜索功能模块抽出来写成Fragment来兼容
                         *
                         * */
                        homeViewModel.searchContent.postValue(currentHotWord)
                       //点击历史搜索记录，估现在跳转Fragment


//                        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
//                        var url = getResourcePath(recipesContent.cover.toString())
//                        var file = File(url)
//                        showToast("调试图片：url : $url     ---- 该图片是否存在：${file.exists()}")

                        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) {
                if (!isVisible&&!isResumed){
                    return@observe
                }

                //从网络菜谱切回本地菜谱，更新数据
                recipesMainAdapter?.functionProvider?.filterSortSearchView?.updateHotWord("")
                homeViewModel.queryRecipesCategory()
            }

            //获取本地菜谱分类回调
            localCategoryLiveData.observe(viewLifecycleOwner) {
                if (!isVisible&&!isResumed){
                    return@observe
                }
                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)
                recyclePosition = 0
            }

            //获取对应分类菜谱回调
            localRecipesLiveData.observe(viewLifecycleOwner) {
                if (!isVisible&&!isResumed){
                    return@observe
                }
                recipesMainAdapter?.setList(it)
                binding.recycleList.scrollToPosition(0)
                recyclePosition = 0
            }

            //获取线上菜谱列表回调
            onLineRecipesLiveData.observe(viewLifecycleOwner) {
                if (!isVisible&&!isResumed){
                    return@observe
                }
                (hostActivity as HomeActivity).dismissDialog()
                if (homeViewModel.recipesType != HomeViewModel.RecipesType.ONLINE){
                    return@observe
                }
                recipesMainAdapter?.setList(it)
                if (!loadMore){
                    binding.recycleList.scrollToPosition(0)
                    recyclePosition = 0
                }
            }

            //获取线上分类回调
            onlineCategoryLiveData.observe(viewLifecycleOwner) {
                if (!isVisible&&!isResumed){
                    return@observe
                }

                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)
                recyclePosition = 0
            }
            errorLiveData.observe(viewLifecycleOwner) {
                (hostActivity as HomeActivity).dismissDialog()
            }
            //获取线上热门标签回调
            onLineHotTagsLiveData.observe(viewLifecycleOwner) {
                if (!isVisible&&!isResumed){
                    return@observe
                }
                recipesMainAdapter?.setList(DataFactory.genOnLineHotTags(it))
            }

            //搜索回调
            hotWordSearchRecipesLiveData.observe(viewLifecycleOwner) {
//                if (!isVisible&&!isResumed){
//                    return@observe
//                }
//
//                recipesMainAdapter?.setList(it)
//                binding.recycleList.scrollToPosition(0)
//                recyclePosition = 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()
            }
        }

        /**
         * 旋转物理键
         */
        homeViewModel.positionRecycle.observe(viewLifecycleOwner){

            if (it.equals("TURN_UP_KEY_CODE")){
                if (recycleBottom){
                    recyclePosition = recyclePosition
                }else{
                    recyclePosition++
                }
            }else if (it.equals("TURN_DOWN_KEY_CODE")){
                if (recyclePosition==0){
                    recyclePosition = 0
                }else{
                    recyclePosition--;
                }
            }
            Log.e("TAG recyclePosition","recyclePosition :$recyclePosition")
            binding.recycleList.smoothScrollToPosition(recyclePosition)
        }

    }




    var firstResume = true

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

            firstResume = false
            DataFactory.dataInvalid = 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) {
            1 -> {
                SortedType.Popular
            }

            2 -> {
                SortedType.Newest
            }

            3 -> {
                SortedType.Score
            }

            0 -> {
                SortedType.A2Z
            }

            else -> {
                SortedType.A2Z
            }
        }
        if (needRefresh) {
            if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                homeViewModel.getOnLineRecipeList(categoryCode, "")
            } else {
                homeViewModel.queryLocalRecipes(categoryCode)
            }
        }
    }


    @Subscribe
    fun refreshStarRecipes(event: RefreshStarDataEvent) {
        val dataList = recipesMainAdapter?.data
        for (i in dataList?.indices!!) {
            val data = dataList[i]
            if (data is FoodContentModel) {
                if (data.foodId == event.recipeNumber) {
                    data.starCount = event.starCount
                    data.useNum = event.useNum.toInt()
                    recipesMainAdapter?.setList(dataList)
                    recipesMainAdapter?.notifyItemChanged(i)
                }
            }
        }

    }

    @Subscribe
    fun refreshLikeRecipes(event: RefreshLikeDataEvent) {
        val dataList = recipesMainAdapter?.data
        for (i in dataList?.indices!!) {
            val data = dataList[i]
            if (data is FoodContentModel) {
                if (data.foodId == event.recipeNumber) {
                    data.isLike = event.isLike
                    recipesMainAdapter?.setList(dataList)
                    recipesMainAdapter?.notifyItemChanged(i)
                }
            }
        }

    }

    private var fromRefreshEvent = false

    @Subscribe
    fun refreshRecipes(event: RefreshDataEvent) {
        fromRefreshEvent = true

    }
    @Subscribe
    fun recipesEvent(event: RecipesEvent) {
        recipesMainAdapter?.let {

            recipesMainAdapter?.setList(it.data)
//            it.notifyItemChanged(0)
//            it.notifyItemChanged(1)
//            it.notifyItemChanged(2)
//            it.notifyItemChanged(3)
//            it.notifyItemChanged(4)
//            it.notifyDataSetChanged()
        }

    }
    companion object {
        var dp65 = (R.dimen.convert_65px).resId2Dimension().toInt()
    }
    private fun  showMsgDialog(){
        var deviceStateDialog = CancelConfirmDialog()
        deviceStateDialog.showCancel = false
        deviceStateDialog.showConfirm = true
        deviceStateDialog.confirmStr = getString(R.string.pmpt_confirm)
        deviceStateDialog.title = getString(R.string.search_content_exceed)
        deviceStateDialog.showDialog(childFragmentManager, "confirmCancelDialog")
        deviceStateDialog.onDialogClickListener =
            object : CancelConfirmDialog.OnDialogClickListener {
                override fun onConfirm() {
                    deviceStateDialog.removeSelf();
                }

                override fun onCancel() {
                    deviceStateDialog.removeSelf();
                }

            }


    }

}