package com.module.backstage.fragment.product

import android.util.Log
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.hboxs.serialport.plc.DialogClickListener
import com.hboxs.serialport.plc.message.MqttMessageBean
import com.module.backstage.R
import com.module.backstage.adapter.ProductAdapter
import com.module.backstage.databinding.BackstageFragmentShowProductBinding
import com.module.backstage.dialog.OKCancelDialog
import com.module.backstage.vm.ShowProductFragmentVM
import com.quyunshuo.androidbaseframemvvm.base.utils.SpUtils
import com.quyunshuo.androidbaseframemvvm.common.bean.ProductDataBean
import com.quyunshuo.androidbaseframemvvm.common.constant.Heartbeat
import com.quyunshuo.androidbaseframemvvm.common.constant.MMKVName
import com.quyunshuo.androidbaseframemvvm.common.constant.MqName
import com.quyunshuo.androidbaseframemvvm.common.listener.AdapterClickListener
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.util.ToastUtil
import com.quyunshuo.androidbaseframemvvm.common.util.UiUtil
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus

/**
 * 显示花型Fragment
 *
 * @author Qu Yunshuo
 * @since 2021/8/1 11:46 下午
 */
@AndroidEntryPoint
class ShowProductFragment : BaseFragment<BackstageFragmentShowProductBinding, ShowProductFragmentVM>() {
    private val TAG = "ShowProductFragment"
    private var productAdapter: ProductAdapter? = null
    override val mViewModel: ShowProductFragmentVM by viewModels()
    override fun createVB() = BackstageFragmentShowProductBinding.inflate(layoutInflater)
    var okCancelDialog: OKCancelDialog? = null


    override fun BackstageFragmentShowProductBinding.initView() {
        with(priceRvProduct) {
            //设置布局排列方式，默认垂直排列
            val gridLayoutManager: GridLayoutManager =
                GridLayoutManager(this@ShowProductFragment.context, 3, GridLayoutManager.VERTICAL, false)
            layoutManager = gridLayoutManager

            productAdapter = ProductAdapter(mViewModel.getPriceData())
            productAdapter!!.setItemListener(object : AdapterClickListener {
                override fun onClickListener(view: View?, position: Int, data: String?) {
//                    if (data == "MAKE") {
//                        开始制作的逻辑
//                        showOkCancelDialog(data)
//                    }else if(data =="PIC"){
//                        切换图片
                        showOkCancelDialog(data!!)
//                    }
                }
            })
            adapter = productAdapter
        }
        tvConfirm.setOnClickListener {
            for (i in 0 until mBinding.priceRvProduct.getLayoutManager()!!.getChildCount()) {
                val holder = mBinding.priceRvProduct.findViewHolderForAdapterPosition(i) as ProductAdapter.MyViewHolder
                Log.d(TAG, "holder.mBinding.rbClose.isChecked initView: "+holder.mBinding.rbClose.isChecked)
                //显示和隐藏
                if (holder.mBinding.rbClose.isChecked) {
                    productAdapter?.productList!![i].isSelected =true
                }else{
                    productAdapter?.productList!![i].isSelected =false
                }
                //是否自定义名字 ：需要上传到服务器。要做好处理。超过10个请求，就要分批。
                val customName = holder.mBinding.etSugarprice.text.toString().trim()
                    productAdapter?.productList!![i].customName = customName
                //自定义图片

            }

            val toJson = Gson().toJson(productAdapter?.productList)
            productAdapter?.productList?.let { it1 -> updateDate(it1) }
            Log.d(TAG, "toJson : "+toJson)
            SpUtils.putString(MMKVName.PRODUCT_DATA, toJson)
            ToastUtil.switchToastStyleToSuccess(UiUtil.getStringRes(R.string.base_backstage_update_success))
        }
    }

    override fun initObserve() {
    }
    fun updateDate(priceBeans: List<ProductDataBean>) {

        var name = ""
        val orderPriceBeans: ArrayList<OrderPriceBean> = ArrayList<OrderPriceBean>()
        for (i in priceBeans.indices) {
            val priceBean: ProductDataBean = priceBeans[i]

            name = if ((priceBean.customName == null) or ("" == priceBean.customName)) {
                priceBean.nameChinese
            } else {
                priceBean.customName
            }
            val bean: OrderPriceBean = OrderPriceBean(
                Heartbeat.deviceId,
                java.lang.String.valueOf(priceBean.price),
                priceBean.productNo,
                name,
                java.lang.String.valueOf(priceBean.price),
                true
            )
            orderPriceBeans.add(bean)
        }
        val gson = Gson()
        val json = gson.toJson(orderPriceBeans)
        Log.d("backnfo", "sssssssssssssssss:+" + json)
        EventBus.getDefault().post(MqttMessageBean(MqName.updatePrice, MqName.SENDPRICE, json))

    }

    override fun initRequestData() {
    }
    private fun showOkCancelDialog(data: String) {
        if (okCancelDialog == null) {
            okCancelDialog = this@ShowProductFragment.context?.let { OKCancelDialog(it) }
        }
        okCancelDialog?.setListener(object: DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {
                when (type) {
                    okCancelDialog?.type1-> {
                        okCancelDialog?.dismiss()
                        //是否确认操作
                        if (data == "MAKE") {
                            //开始制作的逻辑
                        }else if(data =="PIC"){
                            //切换图片
                        }
                    }
                    else -> {}
                }
            }

        })

        okCancelDialog?.show()
    }

    override fun onDestroyView() {
        mBinding.priceRvProduct.adapter = null
        super.onDestroyView()
    }
}