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.base.ext.util.toJson
import com.ypsx.base.ext.view.afterTextChange
import com.ypsx.base.util.dXLog
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.PopupCashPayBinding
import com.ypsx.yppos.http.data.entity.PosPayMethod
import com.ypsx.yppos.room.entity.PosConfig
import com.ypsx.yppos.room.repository.PosConfigRepository
import com.ypsx.yppos.utils.filter.CashierInputFilter
import com.ypsx.yppos.utils.toastFailed
import com.ypsx.yppos.viewmodel.state.CashPayViewModel
import kotlinx.coroutines.*
import razerdp.basepopup.BasePopupWindow
import java.math.BigDecimal
import java.math.RoundingMode

class CashPayPopupWindow(context: Context) : BasePopupWindow(context) {
    lateinit var bind: PopupCashPayBinding
    private var roundMoney: Double = 0.0
    lateinit var payMethod: PosPayMethod
    private var loadConfig: PosConfig? = null


    var payAction: (item: PosPayMethod, receivablesMoney: Double, roundMoney: Double, changeMoney: Double, payMoney: Double) -> Unit =
        { _: PosPayMethod, _: Double, _: Double, _: Double, _: Double -> }

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

    }


    override fun onViewCreated(contentView: View) {

        //  透出应付金额，应付金额四舍五入到分位（记录舍分金额）
        bind = PopupCashPayBinding.bind(contentView)
        bind.vm = CashPayViewModel()
        bind.click = ProxyClick()
        loadConfig = PosConfigRepository.getInstance().loadConfig()


        setAutoShowKeyboard(bind.textView20, true)
        setKeyboardAdaptive(true)
        setKeyboardAdaptionMode(
            bind.textView23,
            FLAG_KEYBOARD_ALIGN_TO_ROOT or FLAG_KEYBOARD_ANIMATE_ALIGN
        )
        bind.textView20.filters = arrayOf(CashierInputFilter())
        bind.textView20.afterTextChange {
            if (it.isEmpty()) {
                bind.vm?.changeMoney?.set(0.0)
                bind.vm?.change2?.set("¥${bind.vm?.changeMoney?.get()}")
            } else {
                val payMoney: Double? = bind.vm?.receivables?.get()
                if (payMoney != null) {
                    if (payMoney <= it.toDouble()) {
                        val scale = BigDecimal(it).minus(BigDecimal.valueOf(payMoney)).setScale(1)
                        bind.vm?.changeMoney?.set(scale.toDouble())
                        bind.vm?.change2?.set("¥${bind.vm?.changeMoney?.get()}")
                    } else {
                        bind.vm?.changeMoney?.set(0.0)
                        bind.vm?.change2?.set("¥${bind.vm?.changeMoney?.get()}")
                    }
                }
            }
        }
        bind.textView20.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                val imm: InputMethodManager =
                    context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(
                    bind.textView20.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    fun setData(payMethod: PosPayMethod, amount: String,cashRoundMode:Int) {
        this.payMethod = payMethod
        val rawData = BigDecimal(amount)
        val scale = rawData.setScale(
            1,
            if (cashRoundMode == 0) RoundingMode.HALF_UP else RoundingMode.DOWN
        )
        loadConfig?.toJson()?.dXLog()
        roundMoney = (rawData - scale).toDouble()
        bind.vm?.receivables?.set(scale.toDouble())
        bind.vm?.receivables2?.set("¥$scale")
//        bind.vm?.actuallyPaid?.set(scale.toString())
        bind.vm?.changeMoney?.set(0.0)
        bind.vm?.change2?.set("¥${bind.vm?.changeMoney?.get()}")
        "舍分金额：$roundMoney".dXLog()


    }


    inner class ProxyClick {
        fun close() {
            dismiss()
        }

        fun confirm() {
            var payMoney: String = bind.textView20.text.toString()
            val receivables: Double? = bind.vm?.receivables?.get()
            val changeMoney: Double? = bind.vm?.changeMoney?.get()
            if (payMoney.isEmpty()) {
                payMoney = receivables.toString()
            }
            if (receivables != null && changeMoney != null) {
                if (receivables > payMoney.toDouble()) {
                    "实付金额不允许小于应付金额".toastFailed()
                    return
                }
                "应付金额：$receivables 舍分金额：$roundMoney 找零金额$changeMoney 实付金额：$payMoney".dXLog()
                payAction.invoke(
                    payMethod,
                    receivables,
                    roundMoney,
                    changeMoney,
                    payMoney.toDouble()
                )

            }


        }

    }

    fun setCashPayClick(payAction: (item: PosPayMethod, receivablesMoney: Double, roundMoney: Double, changeMoney: Double, payMoney: Double) -> Unit) {
        this.payAction = payAction
    }
}