package com.module.backstage.adapter

import ZtlApi.ZtlManager
import android.annotation.SuppressLint
import android.app.XzjhSystemManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.AudioManager
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.ActionBar.LayoutParams
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseMultiItemAdapter
import com.google.gson.Gson
import com.module.backstage.R
import com.module.backstage.databinding.BackstageItemButtonBinding
import com.module.backstage.databinding.BackstageItemInputBinding
import com.module.backstage.databinding.BackstageItemSliderBinding
import com.module.backstage.databinding.BackstageItemSpinnerBinding
import com.module.backstage.databinding.BackstageItemSystemSettingsBinding
import com.module.backstage.databinding.BackstageItemTextBinding
import com.module.backstage.databinding.BackstageListItemBinding
import com.module.backstage.listener.UpdateClickListener
import com.module.pay.common.OtherEnum
import com.module.pay.common.PriceUnit
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.base.utils.XzjhSystemManagerUtlis
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.listener.AdapterClickListener
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil

class TestAdapter(var productList: MutableList<OtherEnum>) :
    BaseMultiItemAdapter<OtherEnum>(productList) {


    // 类型 1 的 viewholder
    class ItemVH(val viewBinding: BackstageItemSystemSettingsBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    // 类型 2 的 viewholder 输入项
    class HeaderVH(val viewBinding: BackstageItemInputBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    // 类型 3 的 viewholder
    class SpinnerVH(val viewBinding: BackstageItemSpinnerBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    // 类型 4 的 viewholder 滑块
    class SliderVH(val viewBinding: BackstageItemSliderBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    // 类型 5 的 viewholder 文本
    class TextVH(val viewBinding: BackstageItemTextBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    // 类型 6 的 viewholder 按钮
    class ButtonVH(val viewBinding: BackstageItemButtonBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    class PriceUnitVH(val viewBinding: BackstageListItemBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    var type3Position: Int = 0 //记录多选值的position

    // 在 init 初始化的时候，添加多类型
    init {
        addItemType(ITEM_TYPE, object : OnMultiItemAdapterListener<OtherEnum, ItemVH> { // 类型 1
            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemVH {
                // 创建 viewholder
                val viewBinding = BackstageItemSystemSettingsBinding.inflate(
                    LayoutInflater.from(context), parent, false
                )
                return ItemVH(viewBinding)
            }

            override fun onBind(holder: ItemVH, position: Int, item: OtherEnum?) {

                itemListener?.onClickListener(holder.itemView, position, null)
                // 绑定 item 数据
                holder.viewBinding.run {
                    tvName.text = UiUtil.getStringRes(item!!.nameId)
                    tvName.setOnLongClickListener(object : OnLongClickListener {
                        override fun onLongClick(v: View?): Boolean {
                            if (item.mmkvName == MMKVName.PROMOTION_CODE) {
                                if (updateClickListener != null) {
                                    if (SpUtils.getBoolean(
                                            MMKVName.IS_SHOW_CHANGLOGE, false
                                        ) == true
                                    ) {
                                        SpUtils.putBoolean(MMKVName.IS_SHOW_CHANGLOGE, false)
                                    } else {
                                        SpUtils.putBoolean(MMKVName.IS_SHOW_CHANGLOGE, true)

                                    }
                                    updateClickListener?.setOnLongClickListener(
                                        item.type, position, ""
                                    )
                                }
                            }
                            return false
                        }

                    })
                    rgSwitch.setOnCheckedChangeListener { group, checkedId ->
                        when (checkedId) {
                            R.id.rb_close -> {
                                SpUtils.putBoolean(item.mmkvName, false)
                                if (item.mmkvName == MMKVName.WIFI_HOTSPOT) {
                                    //关闭热点
                                    ZtlManager.GetInstance().closeAp();
                                }
                            }

                            R.id.rb_open -> {
                                SpUtils.putBoolean(item.mmkvName, true)
                                if (item.mmkvName == MMKVName.WIFI_HOTSPOT) {
                                    //打开热点
                                    ZtlManager.GetInstance().openAp(
                                        SpUtils.getString(
                                            MMKVName.NAME_HOTSPOT, "sunzee"
                                        ), SpUtils.getString(MMKVName.PWD_HOTSPOT, "66666666")
                                    );
                                }
                            }

                            else -> {}
                        }
                    }
                    var flag = SpUtils.getBoolean(item.mmkvName, item.drfault as Boolean)
                    if (flag == true) {
                        rbOpen.isChecked = true
                    } else {
                        rbClose.isChecked = true
                    }
                }


            }
        }).addItemType(SECTION_TYPE,
            object : OnMultiItemAdapterListener<OtherEnum, HeaderVH> { // 类型 2
                override fun onCreate(
                    context: Context,
                    parent: ViewGroup,
                    viewType: Int,
                ): HeaderVH {
                    // 创建 viewholder
                    val viewBinding = BackstageItemInputBinding.inflate(
                        LayoutInflater.from(context), parent, false
                    )
                    return HeaderVH(viewBinding)
                }

                override fun onBind(holder: HeaderVH, position: Int, item: OtherEnum?) {
                    // 绑定 item 数据
                    itemListener?.onClickListener(holder.itemView, position, null)
                    holder.viewBinding.run {

                        tvName.text = UiUtil.getStringRes(item!!.nameId)

                        var defaultValue = SpUtils.getString(item.mmkvName, item.drfault as String)
                        etValue.setText(defaultValue)
                        btnUpdate.setOnClickListener {
                            val value = etValue.text.trim().toString()
                            if (value == "") {
                                ToastUtil.switchToastStyleToWarn("输入为空")
                                return@setOnClickListener
                            }
                            SpUtils.putString(item.mmkvName, value)
                            ToastUtil.switchToastStyleToSuccess("更新成功:" + item.mmkvName)
                        }
//                btnUpdate.setOnClickListener {
//                    itemListener?.onClickListener(it,layoutPosition,etValue.text.trim().toString())
//                }
//                val value = generalParamData?.get(layoutPosition)
//                etValue.setText(value)
                    }
                }

                override fun isFullSpanItem(itemType: Int): Boolean {
                    // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                    return true;
                }

            }).addItemType(MULTIPLE_CHOICE_TYPE,
            object : OnMultiItemAdapterListener<OtherEnum, SpinnerVH> { // 类型 3
                override fun onBind(holder: SpinnerVH, position: Int, item: OtherEnum?) {
                    holder.viewBinding.run {
                        tvName.text = UiUtil.getStringRes(item!!.nameId)
                        initSpinner(this, item)
                        btnUpdate.setOnClickListener {
                            SpUtils.putInt(item.mmkvName, this@TestAdapter.type3Position)
                            ToastUtil.switchToastStyleToSuccess("更新成功:" + item.mmkvName)
                        }
                    }
                }

                private fun initSpinner(mBinding: BackstageItemSpinnerBinding, item: OtherEnum) {
                    //需要进行比较特殊的处理。比如语言的不同。
                    var language2ArrayAdapter =
                        ArrayAdapter<String>(this@TestAdapter.context, R.layout.spinner_text)
                    language2ArrayAdapter.addAll(item.drfault as ArrayList<String>)
                    mBinding.spMultiple.adapter = language2ArrayAdapter
                    mBinding.spMultiple.setOnItemSelectedListener(object : OnItemSelectedListener {
                        override fun onItemSelected(
                            parent: AdapterView<*>?,
                            view: View?,
                            position: Int,
                            id: Long,
                        ) {
                            this@TestAdapter.type3Position = position

                        }

                        override fun onNothingSelected(parent: AdapterView<*>?) {
                        }
                    })
                    mBinding.spMultiple.setSelection(SpUtils.getInt(item.mmkvName, 0)!!)
                }

                override fun onCreate(
                    context: Context,
                    parent: ViewGroup,
                    viewType: Int,
                ): SpinnerVH {
                    // 创建 viewholder
                    val viewBinding = BackstageItemSpinnerBinding.inflate(
                        LayoutInflater.from(context), parent, false
                    )
                    return SpinnerVH(viewBinding)
                }
            }).addItemType(SLIDER_TYPE,
            object : OnMultiItemAdapterListener<OtherEnum, SliderVH> { // 类型 2
                override fun onCreate(
                    context: Context,
                    parent: ViewGroup,
                    viewType: Int,
                ): SliderVH {
                    // 创建 viewholder
                    val viewBinding = BackstageItemSliderBinding.inflate(
                        LayoutInflater.from(context), parent, false
                    )
                    return SliderVH(viewBinding)
                }

                override fun onBind(holder: SliderVH, position: Int, item: OtherEnum?) {
                    // 绑定 item 数据
                    itemListener?.onClickListener(holder.itemView, position, null)
                    holder.viewBinding.run {
                        tvName.text = UiUtil.getStringRes(item!!.nameId)
                        when (item.mmkvName) {
                            MMKVName.VOLUME -> {
                                XLogUtil.d("音量:" + ZtlManager.GetInstance().systemMaxVolume + ":" + ZtlManager.GetInstance().systemCurrenVolume)
                                sbLight.max =
                                    XzjhSystemManagerUtlis.getInstance().getStreamMaxVolume(
                                        AudioManager.STREAM_MUSIC
                                    )//maxVolume 为获取到的 Android 系统最大媒体音量值
                                sbLight.progress = XzjhSystemManagerUtlis.getInstance()
                                    .getVolumePercentage(AudioManager.STREAM_MUSIC)
                                    .toInt();//currenVolume 为获取到的 Android 系统当前媒体音量值
                            }

                            MMKVName.LUMINANCE -> {
                                XLogUtil.d("亮度:" + ZtlManager.GetInstance().systemMaxBrightness + ":" + ZtlManager.GetInstance().systemBrightness)
                                sbLight.max = 255//maxBrightness 为 Android 系统最大亮度
                                sbLight.progress =
                                    XzjhSystemManagerUtlis.getInstance()
                                        .xzjhGetBacklight(); //systemBri 为 Android 系统当前亮度
                            }
                        }

                        sbLight.setOnSeekBarChangeListener(object :
                            SeekBar.OnSeekBarChangeListener {
                            override fun onProgressChanged(
                                seekBar: SeekBar?,
                                progress: Int,
                                fromUser: Boolean,
                            ) {
                                //设置进度
                                setPro(seekBar, progress);
                            }

                            private fun setPro(seekBar: SeekBar?, progress: Int) {
                                when (item.mmkvName) {
                                    MMKVName.VOLUME -> {

                                        XzjhSystemManagerUtlis.getInstance().setVolume(AudioManager.STREAM_MUSIC,progress)
                                        XzjhSystemManagerUtlis.getInstance().showVolumePanel(AudioManager.STREAM_MUSIC)
                                        //设置 Android 系统媒体音量值为 10
                                       // ZtlManager.GetInstance().setSystemVolumeIndex(progress);
                                    }

                                    MMKVName.LUMINANCE -> {
                                        //设置 Android 系统亮度为 200
                                        Log.e("backinfo", "progress:" + progress)
                                        XzjhSystemManagerUtlis.getInstance()
                                            .xzjhSetBacklight(progress)
                                        //ZtlManager.GetInstance().setBrightness(progress);
                                        //BrightnessUtils.setSystemBrightness(BaseApplication.context,progress)
                                    }
                                }

                            }

                            override fun onStartTrackingTouch(seekBar: SeekBar?) {

                            }

                            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                            }

                        });
                    }

                }

                override fun isFullSpanItem(itemType: Int): Boolean {
                    // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                    return true;
                }

            })
            .addItemType(TEXT_TYPE, object : OnMultiItemAdapterListener<OtherEnum, TextVH> { // 类型 5
                override fun onCreate(
                    context: Context,
                    parent: ViewGroup,
                    viewType: Int,
                ): TextVH {
                    // 创建 viewholder
                    val viewBinding = BackstageItemTextBinding.inflate(
                        LayoutInflater.from(context), parent, false
                    )
                    return TextVH(viewBinding)
                }

                @SuppressLint("MissingPermission")
                override fun onBind(holder: TextVH, position: Int, item: OtherEnum?) {
                    // 绑定 item 数据
                    itemListener?.onClickListener(holder.itemView, position, null)
                    holder.viewBinding.run {
                        tvName.text = UiUtil.getStringRes(item!!.nameId)
                        var defaultValue = SpUtils.getString(item.mmkvName, item.drfault as String)
                        when (item.mmkvName) {
                            MMKVName.SIM -> {
                                try {
                                    tvValue.text =
                                        ZtlManager.GetInstance().simTel //simtel 为获取到的 Android 系统 SIM 卡的号码信息
                                } catch (e: Exception) {
                                    //  throw e
                                }


                            }

                            MMKVName.SIM_IMEI -> {
                                try {
                                    tvValue.text = ZtlManager.GetInstance().imei
                                } catch (E: Exception) {
                                    //  throw E
                                }


                            }
                        }

                    }
                }

                override fun isFullSpanItem(itemType: Int): Boolean {
                    // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                    return true;
                }

            }).addItemType(BUTTON_TYPE,
                object : OnMultiItemAdapterListener<OtherEnum, ButtonVH> { // 类型 2
                    override fun onCreate(
                        context: Context,
                        parent: ViewGroup,
                        viewType: Int,
                    ): ButtonVH {
                        // 创建 viewholder
                        val viewBinding = BackstageItemButtonBinding.inflate(
                            LayoutInflater.from(context), parent, false
                        )
                        return ButtonVH(viewBinding)
                    }

                    override fun onBind(holder: ButtonVH, position: Int, item: OtherEnum?) {
                        // 绑定 item 数据
                        itemListener?.onClickListener(holder.itemView, position, null)
                        holder.viewBinding.run {

                            tvName.text = UiUtil.getStringRes(item!!.nameId)

                            var defaultValue =
                                SpUtils.getString(item.mmkvName, item.drfault as String)
//                        btnUpdate.text = defaultValue
                            btnUpdate.setOnClickListener {
                                if (item.mmkvName == MMKVName.CUT_SYSTEM_SET) {
                                    //打开系统设置界面
                                    startActivity(
                                        this@TestAdapter.context,
                                        Intent(Settings.ACTION_SETTINGS),
                                        null
                                    )
                                    ToastUtil.switchToastStyleToSuccess("打开系统设置界面")
                                }
                            }
                        }
                    }

                    override fun isFullSpanItem(itemType: Int): Boolean {
                        // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                        return true;
                    }

                }).addItemType(PRICEUNIT_TYPE,
                object : OnMultiItemAdapterListener<OtherEnum, PriceUnitVH> {
                    override fun onBind(holder: PriceUnitVH, position: Int, item: OtherEnum?) {
                        var selectedPosition = -1 // -1 表示未选中任何项
                        val list = item?.drfault as ArrayList<PriceUnit>
                        for (pricePosition in list.indices) {
                            val textView = TextView(context).apply {
                                text = list[pricePosition].unit
                                background = ContextCompat.getDrawable(
                                    context,
                                    R.drawable.unselected_text_bg
                                ) // 默认背景
                                textSize = 32f
                                setTextColor(Color.parseColor("#ffffff"))
                                setPadding(18, 10, 18, 10) // 调整内边距（需要 dpToPx 扩展函数）
                                gravity = Gravity.CENTER
                            }

                            // 点击事件
                            textView.setOnClickListener {
                                if (selectedPosition != pricePosition) {
                                    // 更新选中位置
                                    val previousSelected = selectedPosition
                                    selectedPosition = pricePosition
                                    // 更新当前选中项的背景
                                    textView.background = ContextCompat.getDrawable(
                                        context,
                                        R.drawable.selected_text_bg
                                    )
                                    // 恢复上一个选中项的默认背景
                                    if (previousSelected != -1) {
                                        (holder.viewBinding.addText.getChildAt(previousSelected) as? TextView)?.background =
                                            ContextCompat.getDrawable(
                                                context,
                                                R.drawable.unselected_text_bg
                                            )
                                    }
                                    if (selectedPosition == 0) {
                                        SpUtils.putString(MMKVName.PRICE_UNIT, "")
                                    } else {
                                        SpUtils.putString(
                                            MMKVName.PRICE_UNIT,
                                            Gson().toJson(list.get(selectedPosition))
                                        )

                                    }

                                    // 显示提示（可选）

                                }
                            }

                            // 添加布局参数
                            val layoutParams = LayoutParams(
                                LayoutParams.WRAP_CONTENT,
                                LayoutParams.WRAP_CONTENT
                            ).apply {
                                setMargins(10, 10, 10, 10)
                            }

                            holder.viewBinding.addText.addView(textView, layoutParams)
                        }
                    } // 类型 7

                    override fun onCreate(
                        context: Context,
                        parent: ViewGroup,
                        viewType: Int,
                    ): PriceUnitVH {
                        // 创建 viewholder
                        val viewBinding = BackstageListItemBinding.inflate(
                            LayoutInflater.from(context), parent, false
                        )
                        return PriceUnitVH(viewBinding)
                    }


                })

            .onItemViewType { position, list -> // 根据数据，返回对应的 ItemViewType
                when (list[position].type) {
                    SECTION_TYPE -> {
                        SECTION_TYPE
                    }

                    MULTIPLE_CHOICE_TYPE -> {
                        MULTIPLE_CHOICE_TYPE
                    }

                    SLIDER_TYPE -> {
                        SLIDER_TYPE
                    }

                    TEXT_TYPE -> {
                        TEXT_TYPE
                    }

                    BUTTON_TYPE -> {
                        BUTTON_TYPE
                    }

                    PRICEUNIT_TYPE -> {
                        PRICEUNIT_TYPE
                    }

                    else -> {
                        ITEM_TYPE
                    }
                }
            }
    }


    companion object {
        private const val ITEM_TYPE = 1//开关
        private const val SECTION_TYPE = 2//输入值
        private const val MULTIPLE_CHOICE_TYPE = 3//多选值
        private const val SLIDER_TYPE = 4//滑块
        private const val TEXT_TYPE = 5//文本
        private const val BUTTON_TYPE = 6//按钮
        private const val PRICEUNIT_TYPE = 7

    }

    private var itemListener: AdapterClickListener? = null
    private var updateClickListener: UpdateClickListener? = null
    fun setOnLongClickListener(monLongClickListener: UpdateClickListener?) {
        this.updateClickListener = monLongClickListener
    }

    fun setItemListener(itemListener: AdapterClickListener?) {
        this.itemListener = itemListener
    }


    fun setData(productList: MutableList<OtherEnum>) {
        this.productList = productList
        notifyDataSetChanged()
        Log.d("backinfo", "数据：" + Gson().toJson(productList))
    }
}