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.util.Log
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.ypsx.base.ext.view.textStringTrim
import com.ypsx.yppos.R
import com.ypsx.yppos.app.base.BaseActivity
import com.ypsx.yppos.app.ext.hideKeyboard
import com.ypsx.yppos.databinding.ActivityMainBinding
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.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.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.*
import java.util.*
import kotlin.collections.ArrayList
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
    val realName: String = CacheUtil.getRealName()


//    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() {
        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()
        }

        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.amount.get()
                var payAmount = mViewModel.payAmount.get()
                var promotionOnSaleTotal = mViewModel.discountSpecial.get()
                var discountTotal = mViewModel.discount.get()
                var data = orderProductAdapter.data
                var arrayList = ArrayList<InsertOrderProductDTO>()
                arrayList.addAll(data)
                arrayList.addAll(posBuyPartsDeleted)

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

        }


    }


    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()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = orderProductAdapter
        orderProductAdapter.addHeaderView(View.inflate(this, R.layout.item_order_header, null))
        orderProductAdapter.run {
            addChildClickViewIds(R.id.rl_item_delete, R.id.tv_count_add, R.id.tv_count_reduce)
            setOnItemChildClickListener { adapter, view, position ->
                when (view.id) {
                    R.id.rl_item_delete -> {
                        var messageDialog = MessagePopupWindow(this@MainActivity)
                        messageDialog.showPopupWindow()
                        messageDialog.setData("单品删除", "是否取消当前商品", "取消", "确定")
                        messageDialog.setMessageClick {
                            var insertOrderProductDTO = orderProductAdapter.data[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]
                        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.toInt() == 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)
                    }
                }
            }
        }

        scanGunKeyEventHelper = ScanGunKeyEventHelper()
        scanGunKeyEventHelper?.setOnBarCodeCatchListener(this)
        productPromotionRequest = ProductPromotionRequest(
            mViewModel.shopId.get(),
            mViewModel.orderNo.get()
        )
        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()
                requestMainViewModel.getKeyWords(textStringTrim)
            }

            return@setOnEditorActionListener false
        }

    }

    inner class ProxyClick {
        fun settings() {
//            mViewModel.orderNo.get().dXLog()
            if (settingsPopupWindow == null) {
                settingsPopupWindow = SettingsPopupWindow(this@MainActivity)
            }
            settingsPopupWindow?.showPopupWindow(mDatabind.ivSettings)
        }

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

        }

        //关闭提示
        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()
            )
            iv_arrow.setImageResource(R.mipmap.ic_temp_down)

            offerDetailsPopupWindow.onDismissListener = object :
                OnDismissListener() {
                override fun onDismiss() {
                    iv_arrow.setImageResource(R.mipmap.ic_temp_up)
                }

            }


        }

        fun payAmount() {
            val payment = mViewModel.payAmount.get()
            val orderNo = mViewModel.orderNo.get()
            val orderPayAmountPopupWindow = OrderPayAmountPopupWindow(this@MainActivity)
            orderPayAmountPopupWindow.showPopupWindow()
            orderPayAmountPopupWindow.setData(orderNo, payment)
            orderPayAmountPopupWindow.setPayClick { it ->
                orderPayAmountPopupWindow.dismiss()
                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 {
                        mViewModel.resetOrderNo()
                        productPromotionRequest.orderNo = mViewModel.orderNo.get()
                        "${realName}点击我知道了，并重置小票号：${productPromotionRequest.orderNo}".dXLog()
                    }
                }
            }
        }
    }

    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)
            orderProductAdapter.notifyDataSetChanged()

        })

        requestMainViewModel.payState.observe(this, {
            if (it.isSuccess) {
                val orderId = it.data?.orderId
                val total = it.data?.total
                var authCode = it.data?.authCode


                if (payAmountPopupWindow != null && payAmountPopupWindow!!.isShowing && payAmountPopupWindow!!.timeIsStart()) {
                    payAmountPopupWindow?.setShowTimer()
                    requestMainViewModel.getStateByOrderId(orderId!!, total!!, authCode!!)
                }

                //支付成功后，
                // 获取支付状态
                //获取订单详情 进行打印
            } 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.amount.set(it.amount)
        })

        requestMainViewModel.paySuccessState.observe(this, {
            payAmountPopupWindow?.dismiss()
            if (it.isSuccess) {
                val paySuccessPopWindow = PaySuccessPopWindow(this)
                paySuccessPopWindow.showPopupWindow()
                paySuccessPopWindow.setData(it.data!!)
                paySuccessPopWindow.onDismissListener = object : OnDismissListener() {
                    override fun onDismiss() {
                        mViewModel.resetOrderNo()
                        mViewModel.resetAmount()
                        productPromotionRequest.orderNo = mViewModel.orderNo.get()
                        productPromotionRequest.products.clear()
                        posBuyPartsDeleted.clear()
                        mViewModel.recyclerShow.set(false)
                        orderProductAdapter.data.clear()
                        orderProductAdapter.notifyDataSetChanged()
                    }
                }
            } else {


                val 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()
                    }

                })
            }
        })
    }


}
