package com.develop.main.ui

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.develop.common.bean.WorkMode
import com.develop.base.ext.load
import com.develop.base.ext.navigateTo
import com.develop.base.ext.resId2Dimension
import com.develop.base.ext.updateText
import com.develop.base.util.TopResumedAtyHolder
import com.develop.common.data_repo.db.ModesType
import com.develop.common.dialog.CancelConfirmDialog
import com.develop.common.router.Screens
import com.develop.common.tag.MODE_TYPE
import com.develop.common.ui.CommonBVMFragment
import com.develop.common.utils.ConfigUtils
import com.develop.main.R
import com.develop.main.databinding.FragmentModesBinding
import com.develop.main.viewmodel.HomeViewModel
import com.drake.brv.utils.linear
import com.drake.brv.utils.setup
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevModes
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset
import kotlin.math.abs

/**
 * 烹饪模式入口
 */
class ModesFragment : CommonBVMFragment<FragmentModesBinding, HomeViewModel>() {

    private var isGrid = false

    private var modeTypeList = mutableListOf<ModesType>()

    override fun createViewModel(): HomeViewModel {
        return getViewModelOfActivity(HomeViewModel::class.java)
    }


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

    override fun onPostCreateView() {
        super.onPostCreateView()
        initView()
    }











    private fun initView() {

        val configJson = ConfigUtils.loadConfig()
        var modes = configJson?.workModes?.filter { it.devMode == CofarSDK.devInfo().devMode }


        binding.galleryRecycle.apply {
            linear(RecyclerView.HORIZONTAL)
            setup {
                addType<WorkMode>(R.layout.item_mode_card_view)
                onBind {
                    val model = getModel<WorkMode>()
                    findView<ImageView>(R.id.iv_icon).load(resources.getIdentifier(model.icon,"drawable","com.develop.foodcooking"))
                    model.name?.let { it1 ->
                        findView<AppCompatTextView>(R.id.tv_mode_name).updateText(
                            resources.getString(resources.getIdentifier(it1,"string","com.develop.foodcooking"))
                        )
                    }
                }
                R.id.card_view.onClick {


                    val devInfo = CofarSDK.devInfo();

                    if( devInfo.status != DevStatus.STOP.toInt() && devInfo.runningInstId != modes?.get(absoluteAdapterPosition)?.type){
                        runningWeightTips()
                        return@onClick
                    }

                    navigateTo(Screens.Cook.COOK_MODES) {



                        val bundle = Bundle()
                        bundle.putString(MODE_TYPE, modes?.get(absoluteAdapterPosition)?.type)
                        with(bundle)
                    }
                }
            }.models = modes
            // 让item居中显示
            val snapHelper = LinearSnapHelper()
            // 绑定到 mRecyclerView
            snapHelper.attachToRecyclerView(this)
            scrollToPosition(1)
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)

                    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.scaleX = scale
                        child.alpha = alpha
                    }
                }
            })

        }
    }
    private  val runningTipsDialog: CancelConfirmDialog = CancelConfirmDialog()



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

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

    companion object {
        var dp60 = (com.develop.base.R.dimen.convert_60px).resId2Dimension().toInt()
        var dp74 = (com.develop.base.R.dimen.convert_74px).resId2Dimension().toInt()
        var dp30 = (com.develop.base.R.dimen.convert_30px).resId2Dimension().toInt()
        var dp28 = (com.develop.base.R.dimen.convert_28px).resId2Dimension().toInt()
        const val MIN_SCALE = 0.75f
        const val MIN_ALPHA = 0.6f
        const val MAX_SCALE = 1.0f
        const val MAX_ALPHA = 1.0f
    }
}