package com.module.backstage.adapter

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter4.BaseMultiItemAdapter
import com.module.backstage.R
import com.module.backstage.databinding.BackstageItemErrorCheckBinding
import com.module.backstage.model.ErrorCheckTask
import com.quyunshuo.androidbaseframemvvm.common.listener.AdapterClickListener
import com.quyunshuo.androidbaseframemvvm.common.util.XLogUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class ErrorCheckAdapter(var productList: List<ErrorCheckTask>) :
    BaseMultiItemAdapter<ErrorCheckTask>(productList) {

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


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

            override fun onBind(holder: ItemVH, position: Int, item: ErrorCheckTask?) {
                itemListener?.onClickListener(holder.itemView, position, null)
                // 绑定 item 数据
                holder.viewBinding.run {
                    tvName.text = item?.description
                    CoroutineScope(Dispatchers.Main).launch {
                        var run :Boolean?
                        withContext(Dispatchers.IO){
                             run = item?.run()
                        }
                        if (run == true){
                            ivStatus.setImageResource(R.drawable.icon_right)
                        }else{
                            ivStatus.setImageResource(R.drawable.pic_shurucuowu)
                        }
                    }

                    XLogUtil.d("item?.description："+item?.description)
                }


            }
        }).onItemViewType { position, list -> // 根据数据，返回对应的 ItemViewType
            ITEM_TYPE
        }
    }

    companion object {
        private const val ITEM_TYPE = 1//开关

    }

    private var itemListener: AdapterClickListener? = null

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

    fun setData(productList: List<ErrorCheckTask>) {
        this.productList = productList
    }
}