package com.ypsx.yppos.ui.popup

import android.content.Context
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import com.ypsx.base.base.appContext
import com.ypsx.base.ext.util.screenWidth
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.PopupChangeQuantityBinding
import com.ypsx.yppos.http.data.bean.InsertOrderProductDTO
import com.ypsx.yppos.http.data.entity.PosProductStyle
import com.ypsx.yppos.room.entity.PosProduct
import com.ypsx.yppos.utils.filter.NumberInputFilter
import com.ypsx.yppos.utils.filter.WeighInputFilter
import com.ypsx.yppos.utils.toast
import com.ypsx.yppos.viewmodel.state.ChangeQuantityViewModel
import razerdp.basepopup.BasePopupWindow
import java.math.BigDecimal
import java.text.DecimalFormat

class ChangeQuantityPopupWindow(context: Context) : BasePopupWindow(context) {
    lateinit var bind: PopupChangeQuantityBinding
    private var type: Int = 0
    var onChangeClick: OnChangeClick? =null
    private var posProduct: PosProduct? = null
    private var insertOrderProductDTO: InsertOrderProductDTO?=null
    private var decimalFormat: DecimalFormat = DecimalFormat("###################.###########")



    init {
        setContentView(R.layout.popup_change_quantity)
        width = appContext.screenWidth / 4 * 3
        popupGravity = Gravity.CENTER
        isOutSideTouchable = false
        setOutSideDismiss(false)
    }

    override fun onViewCreated(contentView: View) {

        //  透出应付金额，应付金额四舍五入到分位（记录舍分金额）
        bind = PopupChangeQuantityBinding.bind(contentView)
        bind.vm = ChangeQuantityViewModel()
        bind.click = ProxyClick()
        setAutoShowKeyboard(bind.etPurchaseQuantity, true)
        setKeyboardAdaptive(true)
        setKeyboardAdaptionMode(
            bind.textView23,
            FLAG_KEYBOARD_ALIGN_TO_ROOT or FLAG_KEYBOARD_ANIMATE_ALIGN
        )
        bind.etPurchaseQuantity.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                val imm: InputMethodManager =
                    context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(
                    bind.etPurchaseQuantity.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    @JvmName("setOnChangeClick1")
    fun setOnChangeClick(onChangeClick: OnChangeClick) {
        this.onChangeClick = onChangeClick
    }

    fun setPosProduct(posProduct: PosProduct) {
        this.type = 0
        this.posProduct = posProduct
        bind.vm?.productName?.set(posProduct.name)
        var purchaseQuantityName :String
        var spec = ""
        when (posProduct.style) {
            PosProductStyle.WEIGHT.name -> {
                purchaseQuantityName = "购买重量"
                spec = posProduct.spec
                bind.vm?.productBarCode?.set("PLU：" + posProduct.mnemonicCode)
                bind.etPurchaseQuantity.filters = arrayOf(WeighInputFilter())
            }
            PosProductStyle.SINGLE.name -> {
                purchaseQuantityName = "购买数量"
                spec = posProduct.spec.toInt().toString()
                bind.vm?.productBarCode?.set("条码：" + posProduct.barCode)
                bind.etPurchaseQuantity.filters = arrayOf(NumberInputFilter())
            }
            else -> {
                purchaseQuantityName = ""
            }
        }
        bind.vm?.purchaseQuantityName?.set(purchaseQuantityName)
        bind.vm?.purchaseQuantity?.set(spec)
//        bind.etPurchaseQuantity.setText(spec)
//        val length = bind.etPurchaseQuantity.text.toString().length
//        bind.etPurchaseQuantity.setSelection(length)
        bind.etPurchaseQuantity.isFocusable = true;
        bind.etPurchaseQuantity.isFocusableInTouchMode = true;
        bind.etPurchaseQuantity.requestFocus()   //获取焦点

    }
    fun setOrderProduct(insertOrderProductDTO: InsertOrderProductDTO) {
        this.type = 1
        this.insertOrderProductDTO = insertOrderProductDTO
        bind.vm?.productName?.set(insertOrderProductDTO.name)
        var purchaseQuantityName :String
        var spec = ""
        when (insertOrderProductDTO.style) {
            PosProductStyle.WEIGHT.name -> {
                purchaseQuantityName = "修改重量"
                spec = decimalFormat.format(insertOrderProductDTO.quantity)
//                spec = insertOrderProductDTO.quantity.toString()
                bind.vm?.productBarCode?.set("PLU：" + insertOrderProductDTO.mnemonicCode)
                bind.etPurchaseQuantity.filters = arrayOf(WeighInputFilter())
            }
            PosProductStyle.SINGLE.name -> {
                purchaseQuantityName = "修改数量"
                spec = insertOrderProductDTO.quantity.toInt().toString()
                bind.vm?.productBarCode?.set("条码：" + insertOrderProductDTO.barCode)
                bind.etPurchaseQuantity.filters = arrayOf(NumberInputFilter())
            }
            else -> {
                purchaseQuantityName = ""
            }
        }
        bind.vm?.purchaseQuantityName?.set(purchaseQuantityName)
        bind.vm?.purchaseQuantity?.set(spec)
//        bind.etPurchaseQuantity.setText(spec)
//        val length = bind.etPurchaseQuantity.text.toString().length
//        bind.etPurchaseQuantity.setSelection(length)
//        bind.etPurchaseQuantity.isFocusable = true;
//        bind.etPurchaseQuantity.isFocusableInTouchMode = true;
        bind.etPurchaseQuantity.requestFocus()   //获取焦点
    }


    inner class ProxyClick {
        fun cancel() {
            dismiss()
            onChangeClick?.cancel()
        }

        fun confirm() {
            val purchaseQuantity: String = bind.etPurchaseQuantity.text.toString()
            var purchaseQuantityHint = bind.etPurchaseQuantity.hint.toString()
            if (purchaseQuantity.isEmpty()) {
                dismiss()
                if (type == 0) {
                    posProduct?.spec = purchaseQuantityHint
                    onChangeClick?.confirm(posProduct!!,null)
                }else{
                    insertOrderProductDTO?.quantity = purchaseQuantityHint.toDouble()
                    onChangeClick?.confirm(null,insertOrderProductDTO!!)
                }
                return
            }
            if (BigDecimal(purchaseQuantity) == BigDecimal.ZERO) {
                "重量/数据不能为空".toast()
                return
            }
                dismiss()
            if (type == 0) {
                posProduct?.spec = purchaseQuantity
                onChangeClick?.confirm(posProduct!!,null)
            }else{
                insertOrderProductDTO?.quantity = purchaseQuantity.toDouble()
                onChangeClick?.confirm(null,insertOrderProductDTO!!)
            }


        }
    }

}

interface OnChangeClick{
    fun cancel()

    fun confirm(posProduct: PosProduct?,insertOrderProductDTO: InsertOrderProductDTO?)
}