package com.develop.main.init.ui

import android.graphics.Rect
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.develop.food.base.common.MODE_TYPE
import com.develop.food.base.data.DataFactory
import com.develop.food.base.data.model.ModelsModel
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.TopResumedActivityHolder
import com.develop.food.base.widgets.CancelConfirmDialog
import com.develop.main.R
import com.develop.main.databinding.FragmentModesBinding
import com.develop.main.init.ui.adapter.ModesGalleryAdapter
import com.develop.main.init.ui.adapter.ModesGridAdapter
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import kotlin.math.abs

class ModesFragment : ViewBindingFragment<FragmentModesBinding>() {
    private var modesGridAdapter = ModesGridAdapter()
    private var modesGalleryAdapter = ModesGalleryAdapter()
    private var isGrid = false
    private var dataList = mutableListOf<ModelsModel>()
    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentModesBinding {
        return FragmentModesBinding.inflate(inflater, container, false)
    }

    override fun onPostCreateView() {
        binding.listMode.setOnClickListener {
            isGrid = !isGrid
            if (isGrid) {
                binding.listName.text = getString(R.string.list_view)
                binding.gridRecycle.visibility = View.VISIBLE
                binding.galleryRecycle.visibility = View.GONE
            } else {
                binding.listName.text = getString(R.string.grid_view)
                binding.gridRecycle.visibility = View.GONE
                binding.galleryRecycle.visibility = View.VISIBLE
            }
        }
        val manager = GridLayoutManager(context, 2)
        binding.gridRecycle.apply {
            adapter = modesGridAdapter
            layoutManager = manager
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    val srcPosition = parent.getChildAdapterPosition(view)
                    if (srcPosition == 0 || srcPosition == 1) {
                        outRect.top = ResDimension(R.dimen.convert_74px).toInt()
                    }
                    when (srcPosition % 2) {
                        0 -> {
                            outRect.left = ResDimension(R.dimen.convert_60px).toInt()
                            outRect.right = ResDimension(R.dimen.convert_30px).toInt()
                        }
                        1 -> {
                            outRect.left = ResDimension(R.dimen.convert_30px).toInt()
                            outRect.right = ResDimension(R.dimen.convert_60px).toInt()
                        }
                    }
                    outRect.bottom = ResDimension(R.dimen.convert_74px).toInt()
                }
            })
        }
        dataList = DataFactory.genGridModesList(resources)
        modesGridAdapter.setList(dataList)

        binding.galleryRecycle.apply {
            adapter = modesGalleryAdapter
            // 让item居中显示
            val snapHelper = LinearSnapHelper()
            // 绑定到 mRecyclerView
            snapHelper.attachToRecyclerView(this)
            scrollToPosition(1)
            addItemDecoration(object : RecyclerView.ItemDecoration() {
                override fun getItemOffsets(
                    outRect: Rect,
                    view: View,
                    parent: RecyclerView,
                    state: RecyclerView.State
                ) {
                    super.getItemOffsets(outRect, view, parent, state)
                    outRect.right = ResDimension(R.dimen.convert_28px).toInt()
                }
            })
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val MIN_SCALE = 0.65f
                    val MIN_ALPHA = 0.5f
                    val MAX_SCALE = 1.0f
                    val MAX_ALPHA = 1.0f
                    val childCount = recyclerView.childCount
                    for (i in 0 until childCount) {
                        val child = recyclerView.getChildAt(i)
                        val left = child.left
                        val paddingStart = recyclerView.paddingStart
                        // 遍历recyclerView子项，以中间项左侧偏移量为基准进行缩放
                        val bl = 1f.coerceAtMost(
                            abs(left - paddingStart)
                                    * 1f / child.width
                        )
                        val scale = MAX_SCALE - bl * (MAX_SCALE - MIN_SCALE)
                        val alpha = MAX_ALPHA - bl * (MAX_ALPHA - MIN_ALPHA)
                        child.scaleY = scale
                        child.alpha = alpha
                    }
                }
            })
        }
        modesGalleryAdapter.setList(DataFactory.genGalleryModesList(resources))

        modesGridAdapter.setOnItemClickListener { adapter, view, position ->
            run {


                if(CofarSDK.devInfo().status != DevStatus.STOP.toInt()){
                    runningWeightTips()
                    return@run
                }

                navigateTo(Screens.Cook.COOK_MODES) {
                    val bundle = Bundle()
                    bundle.putString(MODE_TYPE, dataList[position].modesType.name)
                    with(bundle)
                }
            }
        }
        modesGalleryAdapter.setOnItemClickListener { adapter, view, position ->
            run {

                val devInfo = CofarSDK.devInfo();


                if( devInfo.status != DevStatus.STOP.toInt() && devInfo.runningInstId != dataList[position].modesType.name){
                    runningWeightTips()
                    return@run
                }

                navigateTo(Screens.Cook.COOK_MODES) {
                    val bundle = Bundle()
                    bundle.putString(MODE_TYPE, dataList[position].modesType.name)
                    with(bundle)
                }
            }
        }

    }
    private  val runningTipsDialog: CancelConfirmDialog = CancelConfirmDialog()

    fun runningWeightTips(){
        runningTipsDialog.dialog?.hide()
        runningTipsDialog.showCancel = false
        runningTipsDialog.title =  getString(R.string.running_block_tips)
        runningTipsDialog.confirmStr = getString(R.string.ok)

        TopResumedActivityHolder.getCurrentActivity()?.supportFragmentManager?.let {
            runningTipsDialog.showDialog(
                it,"running_block_tips")
        }
    }

}