package com.abbidot.tracker.deprecated.ui.activity.profile.recharge

import android.content.Intent
import android.text.TextUtils
import android.view.View
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.CreditCardBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.database.MyDatabase
import com.abbidot.tracker.databinding.ActivityAddCreditCardBinding
import com.abbidot.tracker.util.Util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 添加信用卡
 * card.cardNumber = "4111111111111111"
 *card.expirationDate = "08/20"
 *card.countryCode = "USA"
 */
class AddCreditCardActivity :
    BaseActivity<ActivityAddCreditCardBinding>(ActivityAddCreditCardBinding::inflate),
    View.OnFocusChangeListener {

    override fun getTopBar() = mViewBinding.addCreditCardBar.titleTopBar

    override fun initData() {
        super.initData()
        setTopBarTitle(R.string.txt_pay_order_add_card)

        setOnClickListenerViews(mViewBinding.confirmSaveCardBtn)

        mViewBinding.addCreditCardNumberEd.addTextChangedListener {
            mViewBinding.addCreditCardCardView.setCardNumber(it.toString())
        }
        mViewBinding.addCreditCardNameEd.addTextChangedListener {
            val lastName = mViewBinding.addCreditCardLastNameEd.text.toString()
            val name = "$lastName " + it.toString()
            mViewBinding.addCreditCardCardView.setCardholderName(name)
        }
        mViewBinding.addCreditCardLastNameEd.addTextChangedListener {
            val firstName = mViewBinding.addCreditCardNameEd.text.toString()
            val name = it.toString() + " $firstName"
            mViewBinding.addCreditCardCardView.setCardholderName(name)
        }
        mViewBinding.addCreditCardValidityEd.addTextChangedListener {
            formatCardExpiry(it.toString())
        }
        mViewBinding.addCreditCardCvvEd.addTextChangedListener {
            mViewBinding.addCreditCardCardView.setCVV(it.toString())
        }

        mViewBinding.addCreditCardValidityEd.onFocusChangeListener = this
        mViewBinding.addCreditCardNameEd.onFocusChangeListener = this
        mViewBinding.addCreditCardLastNameEd.onFocusChangeListener = this
        mViewBinding.addCreditCardNumberEd.onFocusChangeListener = this
        mViewBinding.addCreditCardCvvEd.onFocusChangeListener = this
    }

    /**
     * 格式化有效期
     */
    private fun formatCardExpiry(cardExpiry: String) {
        var formatCardExpiry = cardExpiry
        val separator = "/"
        if (formatCardExpiry.length == 3) {
            formatCardExpiry = if (formatCardExpiry.contains(separator)) {
                cardExpiry.substring(0, 2)
            } else {
                cardExpiry.substring(0, 2) + separator + cardExpiry.last()
            }
            mViewBinding.addCreditCardValidityEd.apply {
                setText(formatCardExpiry)
                setSelection(formatCardExpiry.length)
            }
        }
        mViewBinding.addCreditCardCardView.setCardExpiry(formatCardExpiry)
    }


    private fun confirmSaveCard() {
        val cardNumber = mViewBinding.addCreditCardNumberEd.text.toString()
        val firstName = mViewBinding.addCreditCardNameEd.text.toString()
        val lastName = mViewBinding.addCreditCardLastNameEd.text.toString()
        val creditCardValidity = mViewBinding.addCreditCardValidityEd.text.toString()
        val cvv = mViewBinding.addCreditCardCvvEd.text.toString()

        if (TextUtils.isEmpty(cardNumber) || TextUtils.isEmpty(firstName) || TextUtils.isEmpty(
                    creditCardValidity) || TextUtils.isEmpty(cvv) || TextUtils.isEmpty(lastName)
        ) {
            showToast(R.string.txt_not_null)
            return
        }

        if (!creditCardValidity.contains("/")) {
            showToast(R.string.txt_card_validity_format)
            return
        } else {
            val dates = creditCardValidity.split("/")
            try {
                if (dates[0].toInt() > 12) {
                    showToast(R.string.txt_card_validity_format)
                    return
                }
            } catch (e: Exception) {
                showToast(R.string.txt_card_validity_format)
                return
            }
        }
        if (Util.getCreditCardType(cardNumber) == 0 || cardNumber.length < 9) {
            showToast(R.string.txt_card_number_format)
            return
        }

        lifecycleScope.launch(Dispatchers.IO) {
            val card = CreditCardBean()
            card.cardNumber = cardNumber
            card.lastName = lastName
            card.firstName = firstName
            card.expirationDate = creditCardValidity
            card.cvv = cvv
            MyDatabase.creditCardDao().insert(card)
            runOnUiThread {
                val intent = Intent()
                intent.putExtra(ConstantString.Card, card)
                setResult(ResultCode.ResultCode_1, intent)
                showToast(R.string.txt_save_successful, isFinish = true)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v!!) {
            mViewBinding.confirmSaveCardBtn -> {
                confirmSaveCard()
            }
        }
    }

    override fun onFocusChange(v: View, hasFocus: Boolean) {
        if (hasFocus) {
            when (v) {
                mViewBinding.addCreditCardNumberEd, mViewBinding.addCreditCardNameEd, mViewBinding.addCreditCardLastNameEd, mViewBinding.addCreditCardValidityEd -> {
                    mViewBinding.addCreditCardCardView.showFrontAnimation()
                }
                mViewBinding.addCreditCardCvvEd -> {
                    mViewBinding.addCreditCardCardView.showBehindAnimation()
                }
            }
        }
    }

}