package com.ypsx.yppos.ui.activity

import android.device.ScanManager
import android.os.Bundle
import android.os.Process.killProcess
import android.os.Process.myPid
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.KeyEvent.KEYCODE_DEL
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.ypsx.base.ext.view.textStringTrim
import com.ypsx.base.util.RecyclerViewUtil
import com.ypsx.base.util.dXLog
import com.ypsx.common.app.base.BaseActivity
import com.ypsx.common.app.ext.hideKeyboard
import com.ypsx.yppos.R
import com.ypsx.yppos.databinding.ActivityMainBinding
import com.ypsx.yppos.http.data.bean.CouponInfoResponse
import com.ypsx.yppos.http.data.bean.CouponResponse
import com.ypsx.yppos.http.data.bean.InsertOrderProductDTO
import com.ypsx.yppos.http.data.bean.OrderActivityResponse
import com.ypsx.yppos.http.data.entity.PosPayMethod
import com.ypsx.yppos.http.data.request.ConfirmRequest
import com.ypsx.yppos.http.data.request.ProductItem
import com.ypsx.yppos.http.data.request.ProductPromotionRequest
import com.ypsx.yppos.jobs.LogService
import com.ypsx.yppos.jobs.SyncProductService
import com.ypsx.yppos.room.entity.PosProduct
import com.ypsx.yppos.ui.adapter.OrderProductAdapter
import com.ypsx.yppos.ui.popup.*
import com.ypsx.yppos.utils.*
import com.ypsx.yppos.utils.scan.ScanGunKeyEventHelper
import com.ypsx.yppos.viewmodel.request.RequestMainViewModel
import com.ypsx.yppos.viewmodel.state.MainViewModel
import kotlinx.android.synthetic.main.activity_main.*
import razerdp.basepopup.BasePopupWindow.OnDismissListener
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.system.exitProcess


class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>(),
    ScanGunKeyEventHelper.OnScanSuccessListener {

    private var exitTime: Long = 0

    private val SCAN_KEYCODE = intArrayOf(520, 521, 522, 523)
    private val requestMainViewModel: RequestMainViewModel by viewModels()
    private val orderProductAdapter: OrderProductAdapter by lazy { OrderProductAdapter(arrayListOf()) }
    var scanGunKeyEventHelper: ScanGunKeyEventHelper? = null
    var settingsPopupWindow: SettingsPopupWindow? = null
    private lateinit var mScanManager: ScanManager
    private lateinit var productPromotionRequest: ProductPromotionRequest
    private var posBuyPartsDeleted = arrayListOf<InsertOrderProductDTO>()
    var activitys: List<OrderActivityResponse>? = null
    var payAmountPopupWindow: PayAmountPopupWindow? = null
    var paySuccessPopWindow: PaySuccessPopWindow? = null
    var payFailedPopWindow: PayFailedPopWindow? = null


    var coupon: CouponInfoResponse? = null


    val realName: String = CacheUtil.getRealName()
    private lateinit var tvListNum: TextView


//    var offerDetailsPopupWindow = OfferDetailsPopupWindow(this)
//    offerDetailsPopupWindow.showPopupWindow(it)

    override fun onResume() {
        super.onResume()
        initScan()
    }

    private fun initScan() {
        mScanManager = ScanManager()
    }


    override fun onPause() {
        super.onPause()
    }

    override fun onDestroy() {
        scanGunKeyEventHelper?.onDestroy()
        LogService.stop(this)
        SyncProductService.stop(this)
        super.onDestroy()
        PrintUtils.close()
    }


    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        if (event != null) {
            scanGunKeyEventHelper?.analysisKeyEvent(event)
        }
        return super.dispatchKeyEvent(event)
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode >= SCAN_KEYCODE[0] && keyCode <= SCAN_KEYCODE[SCAN_KEYCODE.size - 1]
        ) {
            mScanManager.startDecode()
            mDatabind.ivSettings.clearFocus();
            hideKeyboard()

        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                "再按一次退出程序".toast()
                exitTime = System.currentTimeMillis()
            } else {
                this.finish()
                exitProcess(0)
                killProcess(myPid())
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode >= SCAN_KEYCODE[0] && keyCode <= SCAN_KEYCODE[SCAN_KEYCODE.size - 1]
        ) {
            mScanManager.stopDecode()
        }
        return super.onKeyUp(keyCode, event)
    }

    override fun onScanSuccess(barcode: String) {
        Log.i("barcode", barcode + "")
        if (barcode.isNotEmpty()) {
            if (payAmountPopupWindow != null && payAmountPopupWindow!!.isShowing && payAmountPopupWindow!!.timeIsStart()) {
                var payMethod = payAmountPopupWindow?.getPayMethod() ?: PosPayMethod.CCB_BAR_PAY
                var orderNo = mViewModel.orderNo.get()
                var totalAmount = mViewModel.payAmount.get()
                var payAmount = mViewModel.payAmount.get()
                var promotionOnSaleTotal = mViewModel.discountSpecial.get()
                var discountTotal = mViewModel.discountMoney.get()
                var data = orderProductAdapter.data
                var arrayList = ArrayList<InsertOrderProductDTO>()
                arrayList.addAll(data)
                arrayList.addAll(posBuyPartsDeleted)
                var memberId = mViewModel.memberId.get()
                var memberMobile = mViewModel.memberMobile.get()
                var memberPoint = mViewModel.memberPoint.get()

                "$realName 付款方式：${payMethod.name} 支付码：$barcode".dXLog()
                requestMainViewModel.createOrder(
                    orderNo,
                    totalAmount.toDouble(),
                    payAmount.toDouble(),
                    promotionOnSaleTotal.toDouble(),
                    discountTotal.toDouble(),
                    arrayList,
                    payMethod,
                    barcode,
                    0.0, 0.0, memberId, memberMobile, memberPoint, coupon
                )
            } else {
                searchKey(barcode)
//                if (barcode.length == 13 && barcode.startsWith("24")) {
//                    //符合称重条码规则：13位，以24开头
//                    //秤码：13位长度，24开头，第3到7是plu  第8到12是重量
//                    requestMainViewModel.getPlu(barcode)
//                    "$realName 称重码：$barcode".dXLog()
//                } else if (barcode.length == 18 && barcode.startsWith("24")) {
//                    //秤码：13位长度，24开头，第3到7是plu  第8到12是单价的价格  第12到17是重量
//                    requestMainViewModel.getPlu(barcode)
//                    "$realName 称重码：$barcode".dXLog()
//                } else {
//                    "$realName 条码：$barcode".dXLog()
//                    requestMainViewModel.getKeyWords(barcode)
//                }
            }
            mDatabind.ivSettings.clearFocus();

        }


    }


    override fun layoutId(): Int = R.layout.activity_main

    override fun initView(savedInstanceState: Bundle?) {
        LogService.start(this)
        SyncProductService.start(this)
        PrintUtils.init()
        "${realName}进入主页面".dXLog()

        mDatabind.vm = mViewModel
        mDatabind.click = ProxyClick()

        requestMainViewModel.getOptions()
        var linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        recyclerView.layoutManager = linearLayoutManager
        recyclerView.adapter = orderProductAdapter
        val viewHeader = View.inflate(this, R.layout.item_order_header, null)
        tvListNum = viewHeader.findViewById(R.id.tv_list_num)
        tvListNum.text = "购买商品列表(0)"
        orderProductAdapter.addHeaderView(viewHeader)
        orderProductAdapter.run {
            addChildClickViewIds(
                R.id.rl_item_delete,
                R.id.tv_count_add,
                R.id.tv_count_reduce,
                R.id.tv_count
            )
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.rl_item_delete -> {
                        var messageDialog = MessagePopupWindow(this@MainActivity)
                        messageDialog.showPopupWindow()
                        messageDialog.setData("单品删除", "是否取消当前商品", "取消", "确定")
                        messageDialog.setMessageClick {
                            messageDialog.dismiss()
                            var insertOrderProductDTO = orderProductAdapter.data[position]
                            requestMainViewModel.removePluRelation(position)
                            orderProductAdapter.remove(insertOrderProductDTO)
                            insertOrderProductDTO.deleted = true
                            posBuyPartsDeleted.add(insertOrderProductDTO)
                            var orderData = orderProductAdapter.data
                            val size = orderData.size
                            "$realName 主界面选择商品删除".dXLog()
                            if (size > 0) {
                                var products = productPromotionRequest.products
                                if (products.size > 0) {
                                    products.clear()
                                }
                                for (item in orderData) {
                                    val productItem = ProductItem(
                                        item.merchantItemId ?: "",
                                        item.productId,
                                        item.quantity,
                                        item.price
                                    )
                                    products.add(productItem)
                                }
                                requestMainViewModel.request(productPromotionRequest)
                            } else {
                                mViewModel.recyclerShow.set(false)
                            }

                        }


                    }
                    R.id.tv_count_add -> {
                        var insertOrderProductDTO = orderProductAdapter.data[position]
                        if (insertOrderProductDTO.quantity >= 999) {
                            "重量/数量不能在加了".toastSign()
                            return@setOnItemChildClickListener
                        }

                        insertOrderProductDTO.quantity = insertOrderProductDTO.quantity + 1
                        "$realName 主界面选择商品增加${insertOrderProductDTO.quantity}".dXLog()
                        var orderData = orderProductAdapter.data
                        var products = productPromotionRequest.products
                        if (products.size > 0) {
                            products.clear()
                        }
                        for (item in orderData) {
                            val productItem = ProductItem(
                                item.merchantItemId ?: "",
                                item.productId,
                                item.quantity,
                                item.price
                            )
                            products.add(productItem)
                        }
                        requestMainViewModel.request(productPromotionRequest)

                    }
                    R.id.tv_count_reduce -> {
                        var insertOrderProductDTO = orderProductAdapter.data[position]
                        if (insertOrderProductDTO.quantity <= 1) {
                            "重量/数量不能在减了".toastSign()
                            return@setOnItemChildClickListener
                        }
                        insertOrderProductDTO.quantity = insertOrderProductDTO.quantity - 1
                        "$realName 主界面选择商品减少到${insertOrderProductDTO.quantity}".dXLog()
                        var orderData = orderProductAdapter.data
                        var products = productPromotionRequest.products
                        if (products.size > 0) {
                            products.clear()
                        }
                        for (item in orderData) {
                            val productItem = ProductItem(
                                item.merchantItemId ?: "",
                                item.productId,
                                item.quantity,
                                item.price
                            )
                            products.add(productItem)
                        }
                        requestMainViewModel.request(productPromotionRequest)
                    }
                    R.id.tv_count -> {
                        var insertOrderProductDTO = orderProductAdapter.data[position]
                        var changeQuantityPopupWindow = ChangeQuantityPopupWindow(this@MainActivity)
                        changeQuantityPopupWindow.showPopupWindow()
                        changeQuantityPopupWindow.setOrderProduct(insertOrderProductDTO)
                        changeQuantityPopupWindow.setOnChangeClick(object : OnChangeClick {
                            override fun cancel() {

                            }

                            override fun confirm(
                                posProduct: PosProduct?,
                                insertOrderProductDTO2: InsertOrderProductDTO?
                            ) {
                                var orderData = orderProductAdapter.data
                                var products = productPromotionRequest.products
                                if (products.size > 0) {
                                    products.clear()
                                }
                                for (item in orderData) {
                                    val productItem = ProductItem(
                                        item.merchantItemId ?: "",
                                        item.productId,
                                        item.quantity,
                                        item.price
                                    )
                                    products.add(productItem)
                                }
                                requestMainViewModel.request(productPromotionRequest)
                            }


                        })
                    }

                }
            }
        }

        scanGunKeyEventHelper = ScanGunKeyEventHelper()
        scanGunKeyEventHelper?.setOnBarCodeCatchListener(this)
        productPromotionRequest = ProductPromotionRequest(
            mViewModel.shopId.get(),
            mViewModel.orderNo.get(),
            mViewModel.memberId.get(),
            ConfirmRequest()
        )
        et_search_content.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                scanGunKeyEventHelper?.setOnBarCodeCatchListener(null)
            } else {
                scanGunKeyEventHelper?.setOnBarCodeCatchListener(this)
            }
        }
        et_search_content.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideKeyboard()
                val textStringTrim = et_search_content.textStringTrim()
                searchKey(textStringTrim)
            }
            return@setOnEditorActionListener false
        }

    }

    inner class ProxyClick {
        fun toLoginMember() {
            var memberLoginPopupWindow = MemberLoginPopupWindow(this@MainActivity)
            memberLoginPopupWindow.showPopupWindow()
            memberLoginPopupWindow.setMemberLoginClick {
                it.dXLog()
                requestMainViewModel.getMemberByMobile(it)
            }

        }

        fun settings() {
//            mViewModel.orderNo.get().dXLog()
            if (settingsPopupWindow == null) {
                settingsPopupWindow = SettingsPopupWindow(this@MainActivity)
            }
            settingsPopupWindow?.showPopupWindow(mDatabind.ivSettings)
            settingsPopupWindow?.setSyncProductsClick {
                showLoading("同步商品中...")
                requestMainViewModel.syncProducts()

            }
        }

        fun search() {
            val searchContent = mDatabind.etSearchContent.textStringTrim()
            "${realName}搜索条码：$searchContent".dXLog()
            searchKey(searchContent)
//            requestMainViewModel.getKeyWords(searchContent)

        }

        fun onCoupon() {
            if (orderProductAdapter.data.size > 0) {
                val scanCouponPopupWindow =
                    ScanCouponPopupWindow(this@MainActivity, scanGunKeyEventHelper!!)
                scanCouponPopupWindow.showPopupWindow()
                scanCouponPopupWindow.setScanCouponClick {
                    scanCouponPopupWindow.dismiss()
                    productPromotionRequest.confirm = ConfirmRequest(true, it)
                    requestMainViewModel.request(productPromotionRequest)
                }
            } else {
                val messageDialog = MessageTipsPopupWindow(this@MainActivity)
                messageDialog.showPopupWindow()
                messageDialog.setData("请先商品过机再核销优惠券", "我知道了")

            }
        }

        //关闭提示
        fun tips() {
            "${realName}关闭提示".dXLog()
            mViewModel.tipsShow.set(false)
        }

        //查看优惠
        fun discount() {
            var offerDetailsPopupWindow = OfferDetailsPopupWindow(this@MainActivity)
            offerDetailsPopupWindow.showPopupWindow(ll_amount)
            offerDetailsPopupWindow.setData(
                mViewModel.discount.get(),
                mViewModel.discountSpecial.get(),
                mViewModel.discountMoney.get(),
                mViewModel.discountTime.get(),
                mViewModel.discountMember.get()
            )
            iv_arrow.setImageResource(R.drawable.ic_discount_down)
            offerDetailsPopupWindow.onDismissListener = object :
                OnDismissListener() {
                override fun onDismiss() {
                    iv_arrow.setImageResource(R.drawable.ic_discount_up)
                }

            }
        }

        fun payAmount() {
            var memberId = mViewModel.memberId.get()
            if (!TextUtils.isEmpty(memberId)) {
                productPromotionRequest.confirm = ConfirmRequest(true, "")
                requestMainViewModel.request(productPromotionRequest)
            } else {
                payAmountPopup()
            }
        }
    }

    private fun payAmountPopup() {
        val payment = mViewModel.payAmount.get()
        val orderNo = mViewModel.orderNo.get()
        val discountCoupon = mViewModel.discountCoupon.get()
        val orderPayAmountPopupWindow = OrderPayAmountPopupWindow(this@MainActivity)
        orderPayAmountPopupWindow.showPopupWindow()
        orderPayAmountPopupWindow.setData(orderNo, payment, discountCoupon)
        orderPayAmountPopupWindow.setPayClick { it ->
            orderPayAmountPopupWindow.dismiss()
            if (it == PosPayMethod.CASHPAY) {
                val cashRoundMode = mViewModel.cashRoundMode.get()
                val rawData = BigDecimal(payment)
                val scale = rawData.setScale(
                    1,
                    if (cashRoundMode == 0) RoundingMode.HALF_UP else RoundingMode.DOWN
                )
                if (scale.toDouble() < 0.1) {
                    "现金收款金额不能小于0.1元".toastFailed()
                    return@setPayClick
                }

                val cashPayPopupWindow = CashPayPopupWindow(this@MainActivity)
                cashPayPopupWindow.showPopupWindow()
                cashPayPopupWindow.setData(it, payment, cashRoundMode)
                cashPayPopupWindow.setCashPayClick { payMethod, receivablesMoney, roundMoney, changeMoney, payMoney ->
                    cashPayPopupWindow.dismiss()
                    var orderNo = mViewModel.orderNo.get()
                    var totalAmount = mViewModel.payAmount.get()
                    var payAmount = mViewModel.payAmount.get()
                    var promotionOnSaleTotal = mViewModel.discountSpecial.get()
                    var discountTotal = mViewModel.discountMoney.get()
                    var data = orderProductAdapter.data
                    var arrayList = ArrayList<InsertOrderProductDTO>()
                    arrayList.addAll(data)
                    arrayList.addAll(posBuyPartsDeleted)
                    var memberId = mViewModel.memberId.get()
                    var memberMobile = mViewModel.memberMobile.get()
                    var memberPoint = mViewModel.memberPoint.get()
                    "$realName 付款方式：${payMethod.name} ".dXLog()
                    requestMainViewModel.createOrder(
                        orderNo,
                        totalAmount.toDouble(),
                        payAmount.toDouble(),
                        promotionOnSaleTotal.toDouble(),
                        discountTotal.toDouble(),
                        arrayList,
                        payMethod,
                        "", roundMoney, changeMoney, memberId, memberMobile, memberPoint, coupon
                    )
                }

            } else {
                payAmountPopupWindow = PayAmountPopupWindow(this@MainActivity)
                payAmountPopupWindow?.showPopupWindow()
                payAmountPopupWindow?.setData(it, payment)
                payAmountPopupWindow?.onDismissListener = object :
                    OnDismissListener() {
                    override fun onDismiss() {
                        payAmountPopupWindow = null
                    }
                }
                payAmountPopupWindow?.setKeyEventListener { event ->
                    scanGunKeyEventHelper?.analysisKeyEvent(event)
                    return@setKeyEventListener true
                }
                payAmountPopupWindow?.setFinishClick {
                    payAmountPopupWindow?.dismiss()
                    "${realName}支付超时".dXLog()
                    val messageDialog = MessagePopupWindow(this@MainActivity)
                    messageDialog.showPopupWindow()
                    messageDialog.setData("支付超时", "请确认是否支付成功", gone = false)
                    messageDialog.setMessageClick {
                        messageDialog.dismiss()
                        mViewModel.resetOrderNo()
                        productPromotionRequest.orderNo = mViewModel.orderNo.get()
                        "${realName}点击我知道了，并重置小票号：${productPromotionRequest.orderNo}".dXLog()
                    }
                }
            }
        }
        orderPayAmountPopupWindow.setCancelPayAction {
            if (coupon == null) {
                return@setCancelPayAction
            }
            val memberId = mViewModel.memberId.get()
            val shopId = mViewModel.shopId.get()
            requestMainViewModel.cancelCoupon(shopId, memberId, orderNo, coupon!!)
        }
    }

    private fun searchKey(searchContent: String) {
        if (searchContent.isEmpty()) {
            "搜索商品条码/PLU".toast()
            return
        }
        if (searchContent.length == 13 && searchContent.startsWith("24")) {
            //符合称重条码规则：13位，以24开头
            //秤码：13位长度，24开头，第3到7是plu  第8到12是重量
            requestMainViewModel.getPlu(searchContent)
            "$realName 称重码：$searchContent".dXLog()
        } else if (searchContent.length == 18 && searchContent.startsWith("24")) {
            //秤码：13位长度，24开头，第3到7是plu  第8到12是单价的价格  第12到17是重量
            requestMainViewModel.getPlu(searchContent)
            "$realName 称重码：$searchContent".dXLog()
        } else {
            "$realName 条码：$searchContent".dXLog()
            requestMainViewModel.getKeyWords(searchContent)
        }
    }

    override fun createObserver() {
        requestMainViewModel.productItemData.observe(this) {
            productPromotionRequest.products.clear()
            if (orderProductAdapter.data.size > 0) {
                val data = orderProductAdapter.data
                for (item in data) {
                    val productItem = ProductItem(
                        item.merchantItemId ?: "",
                        item.productId,
                        item.quantity,
                        item.price
                    )
                    productPromotionRequest.products.add(productItem)
                }
            }
            et_search_content.text?.clear()
            productPromotionRequest.products.add(it)
            requestMainViewModel.request(productPromotionRequest)
        }
//        requestMainViewModel.productPromotionsResponse.observe(this) {
////            requestMainViewModel.queryAllIn(it)
//        }

        requestMainViewModel.posBuyPartList.observe(this) {
            val recyclerShow = mViewModel.recyclerShow.get()
            if (!recyclerShow) {
                mViewModel.recyclerShow.set(true)
            }
            orderProductAdapter.setList(it)

            val size = orderProductAdapter.data.size
            RecyclerViewUtil.smoothMoveToPosition(mDatabind.recyclerView, size - 1)
//            mDatabind.recyclerView.smoothScrollToPosition()

        }

        requestMainViewModel.payState.observe(this) {
            if (it.isSuccess) {
                val orderId = it.data?.orderId
                val total = it.data?.total
                var authCode = it.data?.authCode
                var memberPoint = mViewModel.memberPoint.get()
                if (payAmountPopupWindow != null && payAmountPopupWindow!!.isShowing && payAmountPopupWindow!!.timeIsStart()) {
                    payAmountPopupWindow?.setShowTimer()
                    requestMainViewModel.getStateByOrderId(
                        orderId!!,
                        total!!,
                        authCode!!,
                        memberPoint
                    )
                }
                //支付成功后，
                // 获取支付状态
                //获取订单详情 进行打印
            } else {
                it.errorMsg.toast()

            }
        }

        requestMainViewModel.payAmountBean.observe(this) {

            mViewModel.discountMoney.set(it.discountMoney.toString())
            mViewModel.discountTime.set(it.discountTime.toString())
            mViewModel.discountSpecial.set(it.discountSpecial.toString())
            mViewModel.discount.set(it.discountTotal.toString())
            mViewModel.payAmount.set(it.payApportionAmount.toString())
            mViewModel.discountMember.set(it.discountMember.toString())
            mViewModel.discountCoupon.set(it.discountCoupon.toString())
            mViewModel.amount.set(it.amount)
//            mViewModel.productsNum.set(it.listNum)
            tvListNum.text = "购买商品列表(${it.listNum})"

            if (it.isFinal) {
                coupon = it.coupon
                payAmountPopup()
            }
        }

        requestMainViewModel.paySuccessState.observe(this) {
            if (payAmountPopupWindow != null) {
                payAmountPopupWindow!!.dismiss()
            }

            if (it.isSuccess) {
                if (payFailedPopWindow != null) {
                    payFailedPopWindow!!.dismiss()
                }
                paySuccessPopWindow = PaySuccessPopWindow(this)
                paySuccessPopWindow!!.showPopupWindow()
                paySuccessPopWindow!!.setData(it.data!!)
                paySuccessPopWindow!!.onDismissListener = object : OnDismissListener() {
                    override fun onDismiss() {
                        paySuccessView()
                    }
                }
            } else {
                payFailedPopWindow = PayFailedPopWindow(this)
                payFailedPopWindow!!.showPopupWindow()
                payFailedPopWindow!!.setData(it.errorMsg)
                payFailedPopWindow!!.setOnPayFailedClick(object : OnPayFailedClick {
                    override fun back() {
                        mViewModel.resetOrderNo()
                        productPromotionRequest.orderNo = mViewModel.orderNo.get()
                    }

                    override fun payAgain() {
                        mViewModel.resetOrderNo()
                        productPromotionRequest.orderNo = mViewModel.orderNo.get()
                        mDatabind.click?.payAmount()
                    }

                })
            }
        }

        requestMainViewModel.paySuccessStateCash.observe(this) {
            val payAmount =
                BigDecimal(it.data!!.payAmount).minus(BigDecimal.valueOf(it.data!!.roundPrice))
                    .plus(
                        BigDecimal.valueOf(it.data!!.changeAmount)
                    ).setScale(2, RoundingMode.HALF_UP).toString()
            val paySuccessPopWindow = CashPaySuccessPopWindow(this)
            paySuccessPopWindow.showPopupWindow()
            paySuccessPopWindow.setData(payAmount, it.data!!.changeAmount.toString())
            paySuccessPopWindow.onDismissListener = object : OnDismissListener() {
                override fun onDismiss() {
                    paySuccessView()
                }
            }
        }

        requestMainViewModel.syncProductsState.observe(this) {
            dismissLoading()
            if (!it.isSuccess) {
                it.errorMsg.toastFailed()
            }
        }

        requestMainViewModel.posProduct.observe(this) {
            val changeQuantityPopupWindow = ChangeQuantityPopupWindow(this)
            changeQuantityPopupWindow.showPopupWindow()
            changeQuantityPopupWindow.setPosProduct(it)
            changeQuantityPopupWindow.setOnChangeClick(object : OnChangeClick {
                override fun cancel() {
                    et_search_content.text?.clear()
                }

                override fun confirm(
                    posProduct: PosProduct?,
                    insertOrderProductDTO: InsertOrderProductDTO?
                ) {
                    val productItem =
                        ProductItem(
                            posProduct?.merchantItemId!!,
                            posProduct.id,
                            posProduct.spec.toDouble(),
                            posProduct.sellPrice
                        )
                    requestMainViewModel.addPluRelation("", posProduct.id)
                    productPromotionRequest.products.clear()
                    if (orderProductAdapter.data.size > 0) {
                        val data = orderProductAdapter.data
                        for (item in data) {
                            val productItem = ProductItem(
                                item.merchantItemId ?: "",
                                item.productId,
                                item.quantity,
                                item.price
                            )
                            productPromotionRequest.products.add(productItem)
                        }
                    }
                    et_search_content.text?.clear()
                    productPromotionRequest.products.add(productItem)
                    requestMainViewModel.request(productPromotionRequest)
                }


            })
        }
        requestMainViewModel.memberInfoState.observe(this) {
            if (it.isSuccess) {
                var data = it.data
                mDatabind.vm?.memberMobile?.set(data?.mobile)
                mDatabind.vm?.memberId?.set(data?.userId)
                mDatabind.vm?.memberShow?.set(true)
                mDatabind.vm?.memberPoint?.set(data?.point)
                mDatabind.vm?.memberMobileInfo?.set("会员信息：${data?.mobile}")
                productPromotionRequest.memberId = mDatabind.vm?.memberId!!.get()
                "会员登录成功".toast()
                if (orderProductAdapter.data.size > 0) {
                    requestMainViewModel.request(productPromotionRequest)
                }
            } else {
                //it.errorMsg = 手机号
                var memberRegisterPopupWindow = MemberRegisterPopupWindow(this)
                memberRegisterPopupWindow.showPopupWindow()
                memberRegisterPopupWindow.setMobile(it.errorMsg)
                memberRegisterPopupWindow.setRegisterMemberClick { mobile, gender, ageGroup ->
                    requestMainViewModel.registerMember(
                        mobile,
                        gender,
                        ageGroup,
                        shopId = mViewModel.shopId.get()
                    )
                }

            }
        }
        requestMainViewModel.cancelCouponState.observe(this) {
            if (it.isSuccess) {
                productPromotionRequest.confirm.isFinal = false
                productPromotionRequest.confirm.userCouponCode = ""
                coupon = null
                requestMainViewModel.request(productPromotionRequest)
            }
        }
    }

    private fun paySuccessView() {
        mViewModel.resetOrderNo()
        mViewModel.resetAmount()
        productPromotionRequest.orderNo = mViewModel.orderNo.get()
        productPromotionRequest.products.clear()
        productPromotionRequest.memberId = ""
        productPromotionRequest.confirm.isFinal = false
        productPromotionRequest.confirm.userCouponCode = ""
        coupon = null


        posBuyPartsDeleted.clear()
        mViewModel.recyclerShow.set(false)
        orderProductAdapter.data.clear()
        orderProductAdapter.notifyDataSetChanged()
    }


}
