package com.grkj.iscs.presentation

import android.content.Intent
import androidx.appcompat.app.AlertDialog
import com.grkj.iscs.BusinessManager
import com.grkj.iscs.view.base.BaseActivity
import com.grkj.iscs.databinding.ActivityLockerBinding
import com.grkj.iscs.extentions.toHexStrings
import com.grkj.iscs.modbus.ModBusController
import com.grkj.iscs.model.DeviceConst
import com.grkj.iscs.util.Executor
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.util.log.LogUtil

class LockerActivity : BaseActivity<ActivityLockerBinding>() {

    private var cardRfid: String? = null

    override val viewBinding: ActivityLockerBinding
        get() = ActivityLockerBinding.inflate(layoutInflater)

    override fun initView() {
        cardRfid = intent.getStringExtra("card")

        mBinding?.create?.setOnClickListener {
            val intent = Intent(this, PresentationActivity::class.java)
            intent.putExtra("card", cardRfid)
            startActivity(intent)
        }

        mBinding?.current?.setOnClickListener {
            startActivity(Intent(this, CurrentTicketActivity::class.java))
        }
    }

    fun showDlg(rfid: String) {
        Executor.runOnMain {
            PresentationManager.ticketCardNo = rfid

            val lockerStatus = PresentationManager.checkLocker(rfid)

            // 锁
            val dockList = ModBusController.getDockByType(DeviceConst.DOCK_TYPE_PORTABLE)
            if (dockList.isEmpty()) {
                ToastUtils.tip("没有找到移动柜")
                return@runOnMain
            }
            val lockList = dockList[0].getLockList().take(2)
            if (lockList.isEmpty()) {
                ToastUtils.tip("没有找到移动柜的锁")
                return@runOnMain
            }
            if (lockList.size < 2) {
                ToastUtils.tip("移动柜的锁数量不够2个")
                return@runOnMain
            }
            val lockIdxList = lockList.map { it.idx } as MutableList

            // 蓝牙钥匙
            val keyList = ModBusController.getKeyByDockType(DeviceConst.DOCK_TYPE_PORTABLE)
            if (keyList.isNullOrEmpty()) {
                ToastUtils.tip("没有找到钥匙")
                return@runOnMain
            }
            val rfid = keyList[0].rfid
            if (rfid.isNullOrEmpty()) {
                ToastUtils.tip("没有找到钥匙的RFID")
                return@runOnMain
            }

            if (lockerStatus == 2) {
                ToastUtils.tip("解锁已完成")
                return@runOnMain
            }

            // 操作设备
            if (lockerStatus == 0) {
                ModBusController.controlLockBuckle(true, dockList[0].addr, lockIdxList) { res ->
                    LogUtil.i("confirm开锁卡扣 : ${res.toHexStrings()}")
                }
            }
            if (lockerStatus == 0 || lockerStatus == 1) { }
        }
    }
}