package com.module.backstage.fragment.product

import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
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.PriceAdapter
import com.module.backstage.databinding.BackstageFragmentPriceBinding
import com.module.backstage.dialog.NormalDialog
import com.module.backstage.vm.PriceFragmentVM
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 PriceFragment : BaseFragment<BackstageFragmentPriceBinding, PriceFragmentVM>() {

    private val TAG = "PriceFragment"
    private var priceAdapter: PriceAdapter? = null
    override val mViewModel: PriceFragmentVM by viewModels()
    override fun createVB() = BackstageFragmentPriceBinding.inflate(layoutInflater)


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

            priceAdapter = PriceAdapter(mViewModel.getPriceData())
            priceAdapter!!.setItemListener(object : AdapterClickListener {
                override fun onClickListener(view: View?, position: Int, data: String?) {
                    addAllKeyboardView(view)
                }
            })
            adapter = priceAdapter
        }
        tvConfirm.setOnClickListener {
            val unifyPrice = mBinding.etSugarprice.text.toString()
            val iscompliance = checkPrice()
            Log.d(TAG, "iscompliance : " + iscompliance)
            if (!unifyPrice.isNullOrBlank()) {
                for (i in 0 until mBinding.priceRvProduct.getLayoutManager()!!.getChildCount()) {
                    val holder =
                        mBinding.priceRvProduct.findViewHolderForAdapterPosition(i) as PriceAdapter.MyViewHolder
                    val editText: EditText =
                        holder.mBinding.etSugarprice // 替换yourEditText为你的EditText变量名
                    val unifyPrice = mBinding.etSugarprice.text.toString()
                    priceAdapter?.productList!![i].price = unifyPrice.toDouble()

                }
                val toJson = Gson().toJson(priceAdapter?.productList)
                SpUtils.putString(MMKVName.PRODUCT_DATA, toJson)
                ToastUtil.switchToastStyleToSuccess(UiUtil.getStringRes(R.string.base_backstage_update_success))
                priceAdapter?.notifyDataSetChanged()
                priceAdapter?.productList?.let { it1 -> updateDate(it1) }
            } else {
                if (iscompliance != -1) {
                    showReminderDialog(
                        UiUtil.getStringRes(R.string.base_ospf) + (iscompliance + 1) + UiUtil.getStringRes(
                            R.string.base_price_zero_tips
                        )
                    )

                } else {
                    for (i in 0 until mBinding.priceRvProduct.getLayoutManager()!!
                        .getChildCount()) {
                        val holder =
                            mBinding.priceRvProduct.findViewHolderForAdapterPosition(i) as PriceAdapter.MyViewHolder
                        val editText: EditText =
                            holder.mBinding.etSugarprice // 替换yourEditText为你的EditText变量名
                        priceAdapter?.productList!![i].price = editText.text.toString().toDouble()

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

            }


            /*  SpUtils.putString(MMKVName.PRODUCT_DATA, toJson)
              ToastUtil.switchToastStyleToSuccess(UiUtil.getStringRes(R.string.backstage_update_success))
              priceAdapter?.notifyDataSetChanged()*/
        }

    }


    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.updatePrice, json))

    }

    var reminderDialog: NormalDialog? = null

    /**
     * 提醒框
     */
    private fun showReminderDialog(text: String) {
        if (reminderDialog == null) {
            reminderDialog = context?.let { NormalDialog(it) }
        }
        reminderDialog?.setContent(text)
        reminderDialog?.setListener(object : DialogClickListener {
            override fun onClickListener(type: Int, text: String?) {

            }

        })
        reminderDialog?.show()
    }

    fun checkPrice(): Int {
        var compliance = -1
        for (i in 0 until mBinding.priceRvProduct.getLayoutManager()!!.getChildCount()) {
            val holder =
                mBinding.priceRvProduct.findViewHolderForAdapterPosition(i) as PriceAdapter.MyViewHolder
            val editText: EditText =
                holder.mBinding.etSugarprice // 替换yourEditText为你的EditText变量名

            val unifyPrice = editText.text.toString()
            if (TextUtils.isEmpty(unifyPrice)) {
                compliance = i
                break
            } else if (unifyPrice.toDouble() <= 0) {
                compliance = i
                break
            }
        }
        return compliance
    }


    override fun initObserve() {
    }

    override fun initRequestData() {
        mViewModel.getArticleData()
    }

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

}