左晓为主开发手持机充值管理机
zuojincheng
1 天以前 d773ab0295feba24ae4fc14f61e8aa310e40f4ba
generallibrary/src/main/java/com/dayu/general/activity/NewCard2Activity.kt
@@ -4,25 +4,32 @@
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.TypedValue
import android.view.View
import android.widget.RadioButton
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.dayu.baselibrary.net.subscribers.SubscriberListener
import com.dayu.baselibrary.tools.nfc.NFCCallBack
import com.dayu.baselibrary.view.TitleBar.ClickType_LEFT_IMAGE
import com.dayu.general.BaseApplication
import com.dayu.general.R
import com.dayu.general.bean.card.UserCard
import com.dayu.general.bean.db.CardRegistrationBean
import com.dayu.general.bean.net.ClientInfo
import com.dayu.general.bean.net.NewCardDataResult
import com.dayu.general.bean.net.PaymentMethod
import com.dayu.general.bean.net.PaymentMethodResponse
import com.dayu.general.dao.BaseDaoSingleton
import com.dayu.general.databinding.ActivityNewCard1GeBinding
import com.dayu.general.databinding.ActivityNewCardGeBinding
import com.dayu.general.net.ApiManager
import com.dayu.general.net.BaseResponse
import com.dayu.general.tool.CardCommon.Companion.USER_CARD_TYPE_1
import com.dayu.general.tool.NfcReadHelper
import com.dayu.general.tool.NfcWreatHelper
import com.dayu.general.utils.DateUtils
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.coroutines.launch
import android.util.TypedValue
import java.util.Calendar
/**
 * Description: 用户开卡界面(同步修改白卡密码)
@@ -31,11 +38,11 @@
 */
class NewCard2Activity : BaseNfcActivity() {
    private lateinit var binding: ActivityNewCard1GeBinding
    private lateinit var binding: ActivityNewCardGeBinding
    // 支付方式
    private var paymentMethod: String = "现金"
    // 支付方式ID
    private var paymentId: Long = 0
@@ -48,38 +55,40 @@
    // 用户ID
    private var userId: String = ""
    // 客户ID
    private var clientId: String = ""
    private lateinit var clientInfo : ClientInfo
    // 是否已读卡
    private var isReadCard: Boolean = false
    private var orderId:String=""
    companion object {
        private const val TAG = "NewCard2Activity"
    }
    // 支付方式数据类
    data class PaymentMethod(
        val id: Long,
        val name: String,
        val remarks: String,
        val deleted: Int
    )
    // 支付方式接口返回数据类
    data class PaymentMethodResponse(
        val itemTotal: Any?,
        val obj: List<PaymentMethod>,
        val pageCurr: Any?,
        val pageSize: Any?,
        val pageTotal: Any?
    )
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityNewCard1GeBinding.inflate(layoutInflater)
        binding = ActivityNewCardGeBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 获取传递的clientId参数
        clientId = intent.getStringExtra("clientId") ?: ""
        initView()
        // 如果有clientId,获取客户信息
        if (clientId.isNotEmpty()) {
            getClientInfo(clientId)
        }
        // 获取支付方式
        getPaymentMethods()
        initListener()
    }
    private fun initView() {
        // 初始化标题栏返回按钮
@@ -90,21 +99,66 @@
        // 初始化NFC读卡容器,初始隐藏
        binding.nfcContainer.visibility = View.VISIBLE
        // 从Intent中获取用户信息(如果有)
        val userName = intent.getStringExtra("userName") ?: ""
        val rawIdCard = intent.getStringExtra("idCard")
        val idCard = if (rawIdCard.isNullOrBlank()) "无" else rawIdCard
        val farmerCode = intent.getStringExtra("farmerCode") ?: ""
        userId = intent.getStringExtra("userId") ?: ""
        // 设置用户信息
        binding.newCardUserName.text = userName
        binding.newCardIdCard.text = idCard
        binding.newCardFarmerCode.text = farmerCode
        // 设置金额输入限制为两位小数
        binding.newCardRechargeAmount.addTextChangedListener(createDecimalTextWatcher())
        binding.newCardCardFee.addTextChangedListener(createDecimalTextWatcher())
    }
    /**
     * 获取客户详细信息
     */
    private fun getClientInfo(clientId: String) {
        ApiManager.getInstance().requestGetLoading(
            this,
            "terminal/client/getTermOne/$clientId",
            ClientInfo::class.java,
            null,
            object : SubscriberListener<BaseResponse<ClientInfo>>() {
                override fun onNext(response: BaseResponse<ClientInfo>) {
                    if (response.success) {
                        clientInfo = response.content!!
                        if (clientInfo != null) {
                            // 显示客户信息到界面
                            displayClientInfo(clientInfo)
                        } else {
                            Toast.makeText(
                                this@NewCard2Activity,
                                "获取客户信息失败: 返回数据为空",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    } else {
                        Toast.makeText(
                            this@NewCard2Activity,
                            "获取客户信息失败: ${response.msg}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
                override fun onError(e: Throwable?) {
                    super.onError(e)
                    Toast.makeText(
                        this@NewCard2Activity,
                        "获取客户信息失败: ${e?.message ?: "网络异常"}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        )
    }
    /**
     * 显示客户信息到界面
     */
    private fun displayClientInfo(clientInfo: ClientInfo) {
        // 保存用户ID供后续使用
        userId = clientInfo.clientId
        // 显示用户基本信息
        binding.newCardUserName.text = clientInfo.name
        binding.newCardIdCard.text = if (clientInfo.idCard.isBlank()) "无" else clientInfo.idCard
        binding.newCardFarmerCode.text = clientInfo.clientNum
    }
    /**
@@ -163,23 +217,23 @@
                resources.getDimensionPixelSize(R.dimen.dimen_40),
                1.0f
            )
            // 如果不是最后一个按钮,添加右边距
            if (index < paymentMethodList.size - 1) {
                (radioButton.layoutParams as android.widget.LinearLayout.LayoutParams).rightMargin =
                (radioButton.layoutParams as android.widget.LinearLayout.LayoutParams).rightMargin =
                    resources.getDimensionPixelSize(R.dimen.dimen_15)
            }
            radioButton.text = method.name
            radioButton.background = resources.getDrawable(R.drawable.radio_selector)
            radioButton.buttonDrawable = null
            radioButton.gravity = android.view.Gravity.CENTER
            radioButton.setTextColor(resources.getColorStateList(R.color.radio_button_text_color))
            radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
            // 添加到RadioGroup
            binding.newCardPaymentMethod.addView(radioButton)
            // 默认选中第一个
            if (index == 0) {
                radioButton.isChecked = true
@@ -244,6 +298,9 @@
        }
    }
    /**
     * 注册新卡
     */
    private fun registerNewCard() {
        // 获取充值金额
        val rechargeAmountStr = binding.newCardRechargeAmount.text.toString()
@@ -262,47 +319,69 @@
        // 构建请求参数
        val params = HashMap<String, Any>()
        params["cardAddr"] = cardPhysicalId // 水卡地址(物理ID)
        params["clientNum"] = binding.newCardFarmerCode.text.toString() // 农户编号
        params["cardCost"] = (cardFee * 100).toInt() // 购卡金额(工本费)转为分
        params["amount"] = (rechargeAmount * 100).toInt() // 充值金额转为分
        params["clientId"] = clientId // 农户ID
        params["cardCost"] = cardFee  // 购卡金额(工本费)(元)
        params["amount"] = rechargeAmount  // 充值金额(元)
        params["paymentId"] = paymentId // 支付方式ID
        params["remarks"] = remark // 备注
        params["protocol"] = "p206V1_0_1" // 协议
        params["operator"] = BaseApplication.userId // 操作人ID
        // 执行卡片激活API请求
        ApiManager.getInstance().requestPostLoading(
            this,
            "sell/card/active",
            String::class.java,
            "terminal/card/termActiveCard",
            NewCardDataResult::class.java,
            params,
            object : SubscriberListener<BaseResponse<String>>() {
                override fun onNext(response: BaseResponse<String>) {
            object : SubscriberListener<BaseResponse<NewCardDataResult>>() {
                override fun onNext(response: BaseResponse<NewCardDataResult>) {
                    if (response.success) {
                        orderId=response.content?.orderNo.toString()
                        // 保存开卡信息到数据库
                        val cardRegistration = CardRegistrationBean(
                            cardNumber = cardPhysicalId,
                            userName = binding.newCardUserName.text.toString(),
                            idCard = binding.newCardIdCard.text.toString(),
                            farmerCode = binding.newCardFarmerCode.text.toString(),
                            clientId = clientId,
                            cardFee = cardFee,
                            remark = binding.newCardRemark.text.toString(),
                            paymentMethod = paymentId.toInt(),
                            isReported = true,
                            isCardWritten = true
                        )
                            isCardWritten = false, // 初始设置为false,写卡成功后再更新为true
                            operatorId = orderId,
                            )
                        // 使用协程在后台线程中保存数据
                        lifecycleScope.launch {
                            try {
                                BaseDaoSingleton.getInstance(this@NewCard2Activity)
                                    .cardRegistrationDao().insert(cardRegistration)
                                Toast.makeText(
                                    this@NewCard2Activity,
                                    "开卡成功",
                                    Toast.LENGTH_SHORT
                                ).show()
                                setResult(RESULT_OK)
                                finish()
                                Intent(this@NewCard2Activity, NfcWreatActivity::class.java).apply {
                                    putExtra("cardType", USER_CARD_TYPE_1)
                                    putExtra("orderId", orderId)
                                    putExtra("cardAddr", cardPhysicalId)
                                    var userCard = UserCard()
                                    userCard.areaNumber =clientInfo.districtNum
                                    userCard.userCode =clientInfo.clientNum
                                    userCard.phoneNumber =clientInfo.phone
                                    userCard.userCodeNumber = response.content?.cardNum?.toInt()!!
                                    userCard.projectCode = response.content?.projectNo?.toInt()!!
                                    userCard.balance = response.content?.balance?.toInt()!!
//                                    userCard.surplusWater = response.content?.surplusWater?.toInt()!!
                                    userCard.waterPrice = response.content?.waterPrice?.toFloat()!!
//                                    userCard.electricPrice = response.content?.electricPrice?.toFloat()!!
                                    userCard.rechargeDate = DateUtils.parseStringToCalendar(response.content?.time)
                                    putExtra("userCard", userCard)
                                    startActivity(this)
                                }
                            } catch (e: Exception) {
                                CrashReport.postCatchedException(e)
                                Toast.makeText(
@@ -348,17 +427,25 @@
    }
    override fun onNfcBack(intent: Intent) {
        var cardNumber = NfcReadHelper.getInstance(intent, this).getCardNumberNoClose()
        if (!cardNumber.isEmpty()) {
            try {
                // 创建密钥列表的副本,避免ConcurrentModificationException
                val keyList = ArrayList(NfcReadHelper.getInstance(intent, this).getKeyList())
        if (!isReadCard) {
            val cardNumber = NfcReadHelper.getInstance(intent, this).getCardNumberNoClose()
            if (cardNumber.isNotEmpty()) {
                try {
                    // 创建密钥列表的副本,避免ConcurrentModificationException
                    val keyList = ArrayList(NfcReadHelper.getInstance(intent, this).getKeyList())
                NfcWreatHelper.getInstance(intent, this).changePS(keyList, false, true, object :
                    NFCCallBack {
                    // 使用美化的加载动画来显示NFC操作的加载状态
                    val nfcHelper = NfcWreatHelper.getInstance(intent, this)
                    nfcHelper.setLoadingView(binding.loadingContainer, binding.nfcProgressWheel)
                    override fun isSusses(flag: Boolean, msg: String?) {
                        if (flag) {
                    // 异步修改密码
                    nfcHelper.changePSAsync(
                        keyList,
                        false,
                        true
                    ) { success: Boolean, msg: String? ->
                        if (success) {
                            isReadCard = true
                            // 保存卡物理ID
                            cardPhysicalId = cardNumber
                            // 更新UI
@@ -371,22 +458,44 @@
                            // 密码修改失败,处理错误情况
                            Toast.makeText(
                                this@NewCard2Activity,
                                "卡片初始化失败:" + msg,
                                "卡片初始化失败:$msg",
                                Toast.LENGTH_LONG
                            )
                                .show()
                            ).show()
                        }
                    }
                })
            } catch (e: Exception) {
                // 处理异常情况
                CrashReport.postCatchedException(e)
                e.printStackTrace()
                } catch (e: Exception) {
                    // 处理异常情况
                    CrashReport.postCatchedException(e)
                    e.printStackTrace()
                }
            } else {
                Toast.makeText(
                    this@NewCard2Activity,
                    "获取卡号失败",
                    Toast.LENGTH_SHORT
                ).show()
            }
        } else {
            Toast.makeText(
                this@NewCard2Activity,
                "当前已读卡,不可再次读卡",
                Toast.LENGTH_SHORT
            ).show()
        }
    }
    override fun onDestroy() {
        super.onDestroy()
        // 清理NFC工具类中的RxJava订阅,防止内存泄漏
        try {
            NfcReadHelper.getInstance(intent, this).clearDisposables()
            NfcWreatHelper.getInstance(intent, this).clearDisposables()
            // 确保停止动画,避免内存泄漏
            binding.nfcProgressWheel.stopSpinning()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}