package com.miya.fastcashier.ui

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import com.miya.fastcashier.R
import com.miya.fastcashier.config.IntentExtra
import com.miya.fastcashier.databinding.ActivityPriceInputBinding
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.ui.dialog.CommonDialog
import com.miya.fastcashier.ui.dialog.MessageDialog
import com.miya.fastcashier.ui.dialog.PayChooseDialog
import com.miya.fastcashier.ui.dialog.PayChooseDialog.GeneratePayCodeClickListener
import com.miya.fastcashier.utils.CenterToasty
import com.miya.fastcashier.utils.StringPriceFormat
import com.miya.fastcashier.utils.WordUtil
import com.miya.fastcashier.utils.clickWithTrigger
import com.miya.fastcashier.viewmodel.PayViewModel
import com.miya.fastcashier.widget.DecimalKeyboard.DELETE
import com.miya.fastcashier.widget.DecimalKeyboard.DOT
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import com.tencent.mmkv.MMKV
import java.math.BigDecimal


class PriceInputActivity : BaseActivity() {
    private lateinit var viewModel: PayViewModel
    private lateinit var binding: ActivityPriceInputBinding

    private var payChooseDialog: PayChooseDialog? = null
    private var alertDialog: CommonDialog? = null
    private lateinit var payServiceResponse: PayServiceResponse

    companion object {
        const val PRICEINPUT_TYPE_COLLECTION = 1
        const val PRICEINPUT_TYPE_CREFUND = 2

        fun start(context: BaseActivity) {
            start(context, PRICEINPUT_TYPE_COLLECTION, null)
        }

        fun start(context: BaseActivity, type: Int, payServiceResponse: PayServiceResponse?) {
            val intent = Intent(context, PriceInputActivity::class.java)
            intent.putExtra(IntentExtra.KEY_EXTRA_DATA, payServiceResponse)
            intent.putExtra(IntentExtra.KEY_EXTRA_TYPE, type)
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityPriceInputBinding.inflate(layoutInflater)
        setContentView(binding.root)
        viewModel = ViewModelProvider(this).get(PayViewModel::class.java)

        initView()
        initListener()
    }

    private fun initView() {
        val type = intent.getIntExtra(IntentExtra.KEY_EXTRA_TYPE, PRICEINPUT_TYPE_COLLECTION)
        when (type) {
            PRICEINPUT_TYPE_COLLECTION -> {
                binding.tvTitle.text = "收款"
                binding.tvPriceText.text = "收款金额"
                binding.etPrice.setHint("输入收款金额")
                binding.tvRefundPriceTotal.visibility = View.GONE
                binding.tvScanPayCode.visibility = View.VISIBLE
                binding.tvGeneratePayCode.visibility = View.VISIBLE
                binding.tvRefund.visibility = View.GONE
            }
            PRICEINPUT_TYPE_CREFUND -> {
                binding.tvTitle.text = "退款"
                binding.tvPriceText.text = "订单金额"
                binding.etPrice.setHint("输入退款金额")
                binding.tvRefundPriceTotal.visibility = View.VISIBLE
                this.payServiceResponse =
                    intent.getSerializableExtra(IntentExtra.KEY_EXTRA_DATA) as PayServiceResponse
                binding.tvRefundPriceTotal.text =
                    "¥${StringPriceFormat.transStringPriceToDecimalString(payServiceResponse.tradPrice)}"
                binding.tvScanPayCode.visibility = View.GONE
                binding.tvGeneratePayCode.visibility = View.GONE
                binding.tvRefund.visibility = View.VISIBLE
            }
        }
    }

    private fun initListener() {
        binding.tvScanPayCode.clickWithTrigger {

            val price = binding.etPrice.text
            if (TextUtils.isEmpty(price)) {
                CenterToasty.error(this, "请输入金额!", Toast.LENGTH_LONG).show()
                return@clickWithTrigger
            }

            val intent = Intent()
            intent.setClass(this@PriceInputActivity, PayActivity::class.java)
            intent.putExtra("price", price)
            startActivity(intent)
        }

        binding.tvGeneratePayCode.clickWithTrigger {
            if (null == payChooseDialog) {
                payChooseDialog = PayChooseDialog(this)
                payChooseDialog!!.setGeneratePayCodeClickListener(object :
                    GeneratePayCodeClickListener {
                    override fun choose(payType: String) {
                        showProgressDialog("生成付款码")
                        viewModel.generatePayCode(binding.etPrice.text.toString(), payType)
                    }
                })
            }
            payChooseDialog!!.show()
        }

        binding.llBack.clickWithTrigger { finish() }

        binding.numKeyboard.setKeyboardClickListener {
            when (it) {
                DELETE -> {
                    if (TextUtils.isEmpty(binding.etPrice.text.toString())) {
                        return@setKeyboardClickListener
                    }
                    var currentCode: String = binding.etPrice.text.toString()
                    currentCode = if (currentCode.length <= 1) {
                        ""
                    } else {
                        currentCode.substring(0, currentCode.length - 1)
                    }
                    binding.etPrice.setText(currentCode)
                    if (binding.tvInvalidRefundPrice.visibility == View.VISIBLE) {
                        binding.tvInvalidRefundPrice.visibility = View.GONE
                    }
                }
                DOT -> {
                    var currentCode: String = binding.etPrice.text.toString()
                    if (!currentCode.contains(".") && !TextUtils.isEmpty(currentCode)) {
                        currentCode += "."
                        binding.etPrice.setText(currentCode)
                    } else {
                        CenterToasty.error(this, "金额格式有误！", Toast.LENGTH_SHORT).show()
                    }
                }
                else -> {
                    var currentCode: String = binding.etPrice.text.toString()
                    if (currentCode.contains(".")) {
                        val tmp =
                            currentCode.substring(
                                currentCode.indexOf("."),
                                currentCode.length - 1
                            )
                        if (tmp.length < 2) {
                            if (BigDecimal(currentCode + it).compareTo(BigDecimal.ZERO) == 0 && tmp.length == 1) {
                                CenterToasty.error(this, "金额不能为0！", Toast.LENGTH_SHORT).show()
                            } else {
                                currentCode += it
                                binding.etPrice.text = currentCode
                            }
                        } else {
                            CenterToasty.error(this, "金额最多设置2位小数！", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        if (currentCode.startsWith("0") && currentCode.length == 1 && it == 0) {
                            CenterToasty.error(this, "第二位不能输入0！", Toast.LENGTH_SHORT).show()
                        } else {
                            if (BigDecimal(currentCode + it).compareTo(BigDecimal("99999")) == 1) {
                                CenterToasty.error(this, "金额不能超过99999！", Toast.LENGTH_SHORT)
                                    .show()
                            } else {
                                currentCode += it
                                binding.etPrice.text = currentCode
                            }
                        }
                    }
                }
            }
        }

        viewModel.payServiceResponseLiveData.observe(this, { result ->
            dismissProgressDialog()

            result.getOrElse {
                it.message?.let { it1 ->
                    CenterToasty.error(this, it1, Toast.LENGTH_LONG).show()
                }
                return@observe
            }

            result.getOrNull().also {
                it?.let { it1 ->
                    val intent = Intent()
                    if ("1" == it1.chanelTag) {
                        intent.setClass(this@PriceInputActivity, WxPayCodeActivity::class.java)
                    } else {
                        intent.setClass(this@PriceInputActivity, AliPayCodeActivity::class.java)
                    }
                    intent.putExtra("payServiceResponse", it1)
                    startActivity(intent)
                }
            }
        })

        viewModel.refundLiveData.observe(this, { payResult ->
            payResult.onFailure {
                dismissProgressDialog()
                it.message?.let { it1 ->

                    if(it1.contains("大于可退金额")){
                        CenterToasty.error(this, "本次退款金额大于可退金额！", Toast.LENGTH_LONG).show()
                    }else{
                        CenterToasty.error(this, it1, Toast.LENGTH_LONG).show()
                    }
                }
            }
            payResult.onSuccess {
                dismissProgressDialog()
                CenterToasty.success(this, "退款成功!!", Toast.LENGTH_LONG).show()
                finish()
            }
        })

        binding.tvRefund.clickWithTrigger {

            val price = binding.etPrice.text.toString()

            if (TextUtils.isEmpty(price)) {
                CenterToasty.error(this, "退款金额不能为空！", Toast.LENGTH_SHORT).show()
                return@clickWithTrigger
            }

            val priceYuan2Fen = StringPriceFormat.transStringYuan2Fen(price)
            if (priceYuan2Fen.toDouble() > payServiceResponse.tradPrice.toDouble()) {
                binding.tvInvalidRefundPrice.visibility = View.VISIBLE
                return@clickWithTrigger
            }
            doubleRefundConfirm(price)
        }
    }

    /**
     * 二次退款确认
     */
    private fun doubleRefundConfirm(refundPrice: String) {
        var content: String = getString(R.string.text_refund_amount, refundPrice)
        if (null == alertDialog) {
            alertDialog = CommonDialog(this)
        }
        alertDialog!!.setCustomMessage(
            WordUtil.matcherDiscolor(
                this,
                R.color.color_D83773, content,
                "¥$refundPrice"
            )
        )
            .setNegativeStr(getString(R.string.cancel))
            .setPositiveStr("确认退款")
            .setOnClickListener(object : CommonDialog.OnDialogClickListener {
                override fun onNegativeClick() {
                    alertDialog!!.dismiss()
                    alertDialog = null
                }

                override fun onPositiveClick() {
                    alertDialog!!.dismiss()
                    alertDialog = null
                    run {
                        showProgressDialog("退款中")
                        viewModel.refund(
                            payServiceResponse,
                            StringPriceFormat.getPayPriceFenStringFromYuan(refundPrice, "0")
                        )
                    }
                }
            })
            .show()
    }

    override fun onStop() {
        super.onStop()
        payChooseDialog?.dismiss()
        alertDialog?.dismiss()
    }
}