package com.develop.main.init.ui

import android.graphics.Rect
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
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.FragmentRecipesNewBinding
import com.develop.food.base.data.CategoryType
import com.develop.food.base.data.DataFactory
import com.develop.food.base.data.model.CategoryModel
import com.develop.food.base.data.model.FoodContentModel
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.getSN
import com.develop.food.base.widgets.CategoryTabViewLayout
import com.develop.main.R
import com.develop.main.init.ui.adapter.RecipesListAdapter
import com.develop.main.init.ui.adapter.RecipesSearchAdapter
import com.develop.main.init.ui.provider.RecipesContentProvider
import com.develop.main.init.ui.viewmodel.HomeViewModel

class RecipesNewFragment : ViewBindingFragment<FragmentRecipesNewBinding>() {
    private var recipesSearchAdapter = RecipesSearchAdapter()
    private var dataList = mutableListOf<FoodContentModel>()
    private val homeViewModel by activityViewModels<HomeViewModel>()
    private var recyclePosition = 0
    private var recycleBottom = false;
    private var currentHotWord = ""
    private var lastPos = 0
    private var isSelectType = false
    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentRecipesNewBinding {
        return FragmentRecipesNewBinding.inflate(inflater, container, false)
    }

    override fun onPostCreateView() {
//        currentHotWord =  getStringExtra("search")
        if (arguments != null) {
            currentHotWord = arguments?.getString("search") ?: ""
        }

        if (currentHotWord != "") {
            binding.etSearch.setText(currentHotWord)
            if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                homeViewModel.getOnLineRecipeList("", currentHotWord)
            } else {
                homeViewModel.queryRecipesByHotWord(currentHotWord, CategoryType.All)
            }
        }
        binding.searchRecycler.apply {
            adapter = recipesSearchAdapter
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    val pos = parent.getChildAdapterPosition(view)
                    if (pos == 0) {
                        outRect.top = ResDimension(R.dimen.convert_30px).toInt()
                    }
                }
            })

            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    var lastPosition = -1
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        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
                    }
                }
            })
        }
        recipesSearchAdapter.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)
                    }
                }
            }

         binding.searchImage.setOnClickListener {

        }

        //color_F4A12E
        if (!getSN().startsWith("034")){
            binding.tvSearch.setTextColor(resources.getColor(R.color.color_F4A12E))
        }

        //分类点击回调
        binding.searchCategoryTabView.onCategoryTabSelectedListener =
            object : CategoryTabViewLayout.OnCategoryTabSelectedListener {
                override fun onCurrentSelected(categoryType: CategoryType) {
                    isSelectType = true
                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                        homeViewModel.getOnLineRecipeList("", currentHotWord)
                    } else {
                        homeViewModel.queryRecipesByHotWord(currentHotWord, categoryType)
                    }
                }

            }
        binding.tvSearch.setOnClickListener {
            isSelectType = true
            currentHotWord = binding.etSearch.text.toString()
            homeViewModel.saveHistoryWords(currentHotWord)
            if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                homeViewModel.getOnLineRecipeList("", currentHotWord)
            } else {
                homeViewModel.queryRecipesByHotWord(currentHotWord, CategoryType.All)
            }
        }
        binding.ivBack.setOnClickListener {
            homeViewModel.searchContentData.postValue(false)
        }

        homeViewModel.apply {
            //接受查询得内容
            searchContent.observe(viewLifecycleOwner) {
                if (isVisible && isResumed) {
                    currentHotWord = it
                    if (homeViewModel.recipesType == HomeViewModel.RecipesType.ONLINE) {
                        homeViewModel.getOnLineRecipeList("", currentHotWord)
                    } else {
                        homeViewModel.queryRecipesByHotWord(currentHotWord, CategoryType.All)
                    }
                }
            }
            //本地搜索搜索回调
            hotWordSearchRecipesLiveData.observe(viewLifecycleOwner) {
                if (isVisible && isResumed) {
                    binding.searchCategoryTabView.visibility = View.VISIBLE
                    binding.searchCategoryName.visibility = View.GONE
                    dataList.clear()
                    var categoryModel = CategoryModel(0, 0, 0)
                    it.forEach { it1 ->
                        if (it1 is CategoryModel) {
                            categoryModel = it1
                        }
                        if (it1 is FoodContentModel) {
                            dataList.add(it1)
                        }
                    }

                    binding.searchCategoryTabView.updateCategorySize(
                        categoryModel.allSize,
                        categoryModel.recipesSize,
                        categoryModel.ingredientSize
                    )
                    recipesSearchAdapter.setList(dataList)
                    recyclePosition = 0
                    binding.searchRecycler.smoothScrollToPosition(0)
                    if (isSelectType) {
                        isSelectType = false
                        /**
                         * 由于点击分类后，再点击搜索框不会显示软键盘
                         * 设置一个0dp得edittext 做兼容处理
                         * */
                        binding.searchText.requestFocus()
                        binding.searchText.performClick()
//                        searchFocus.postValue(true)
                    }
                }
            }

            //获取搜索线上菜谱列表回调
            onLineRecipesLiveData.observe(viewLifecycleOwner) {
                if (isVisible && isResumed) {
                    binding.searchCategoryTabView.visibility = View.GONE
                    binding.searchCategoryName.visibility = View.VISIBLE

                    (hostActivity as HomeActivity).dismissDialog()
                    dataList.clear()
                    var text = "ALL"
                    it.forEach() { it1 ->
                        if (it1 is String) {
                            text = it1
                        } else if (it1 is FoodContentModel) {
                            dataList.add(it1)
                        } else {

                        }
                    }

                    binding.searchCategoryName.text = text
                    recipesSearchAdapter.setList(dataList)
                    recyclePosition = 0
                    binding.searchRecycler.smoothScrollToPosition(0)
                    if (isSelectType) {
                        isSelectType = false
                        /**
                         * 由于点击分类后，再点击搜索框不会显示软键盘
                         * 设置一个0dp得edittext 做兼容处理
                         * */
                        binding.searchText.requestFocus()
                        binding.searchText.performClick()
//                        searchFocus.postValue(true)
                    }
                }

            }


        }

        /**
         * 旋转物理键
         */
        homeViewModel.positionRecycle.observe(viewLifecycleOwner) {
            if (isVisible && isResumed) {
                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.searchRecycler.smoothScrollToPosition(recyclePosition)
            }
        }


    }
}


