SwipeActivity.kt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package com.example.chemical.ui.login
  2. import android.content.IntentFilter
  3. import android.hardware.usb.UsbManager
  4. import android.os.Bundle
  5. import android.os.Handler
  6. import android.os.Looper
  7. import android.view.KeyEvent
  8. import android.view.LayoutInflater
  9. import android.view.MotionEvent
  10. import android.view.View
  11. import android.widget.TextView
  12. import com.blankj.utilcode.util.AppUtils
  13. import com.blankj.utilcode.util.LogUtils
  14. import com.bumptech.glide.Glide
  15. import com.bumptech.glide.load.engine.DiskCacheStrategy
  16. import com.bumptech.glide.request.RequestOptions
  17. import com.example.chemical.ChemicalApp
  18. import com.example.chemical.R
  19. import com.example.chemical.databinding.ActivitySwipeBinding
  20. import com.example.chemical.receiver.OnSerialScanListener
  21. import com.example.chemical.receiver.PortScanHelper
  22. import com.example.chemical.receiver.UsbReceiver
  23. import com.example.chemical.ui.MainActivity
  24. import com.example.chemical.ui.common.BaseCountDownActivity
  25. import com.example.chemical.utils.MediaPlayerHelper
  26. import com.example.chemical.utils.UiManager
  27. import com.example.chemical.weidith.AuthenticationDialog
  28. import com.example.chemical.weidith.CustomDialog
  29. import com.rc.core.log.RcLog
  30. import com.rc.httpcore.HttpClient
  31. import com.rc.httpcore.HttpConfig
  32. import com.rc.httpcore.client.ApiRepository
  33. import com.rc.httpcore.exception.NetException
  34. import org.greenrobot.eventbus.EventBus
  35. import org.greenrobot.eventbus.Subscribe
  36. import org.greenrobot.eventbus.ThreadMode
  37. import retrofit2.HttpException
  38. import java.net.ConnectException
  39. import java.net.SocketTimeoutException
  40. /**
  41. * 刷卡登录
  42. */
  43. class SwipeActivity : BaseCountDownActivity<ActivitySwipeBinding>() {
  44. private var mUsbReceiver: UsbReceiver? = null // 刷卡广播注册
  45. private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数
  46. override fun createViewBinding() = ActivitySwipeBinding.inflate(LayoutInflater.from(this))
  47. override fun initViews(savedInstanceState: Bundle?) {
  48. super.initViews(savedInstanceState)
  49. MediaPlayerHelper.playRawMp3(this, R.raw.login_shua_ka)
  50. //注册广播
  51. EventBus.getDefault().register(this)
  52. viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
  53. viewBinding.tvReturn.setOnClickListener {
  54. UiManager.switcherCashier(this, MainActivity::class.java)
  55. }
  56. val stringExtra = intent.getStringExtra("mtypes")
  57. when (stringExtra) {
  58. "1" -> {
  59. viewBinding.linType.visibility = View.GONE
  60. }
  61. "6" -> {
  62. viewBinding.tvFace.visibility = View.GONE
  63. }
  64. "4" -> {
  65. viewBinding.tvWx.visibility = View.GONE
  66. }
  67. }
  68. viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
  69. Glide.with(this)
  70. .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
  71. .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
  72. .into(viewBinding.image)
  73. val map = mutableMapOf<String, String>()
  74. if (stringExtra != null) {
  75. map["mtypes"] = stringExtra
  76. }
  77. try {
  78. val face = intent.getStringExtra("faceList")
  79. if (face != null) {
  80. map["faceList"] = face
  81. }
  82. } catch (e: Exception) {
  83. }
  84. viewBinding.tvFace.setOnClickListener {
  85. UiManager.switcher(this, map, FacialLoginActivity::class.java)
  86. finish()
  87. }
  88. viewBinding.tvWx.setOnClickListener {
  89. if (stringExtra != null) {
  90. map["mtypes"] = stringExtra
  91. }
  92. UiManager.switcher(this, map, ScanLoginActivity::class.java)
  93. finish()
  94. }
  95. }
  96. override fun onResume() {
  97. super.onResume()
  98. mPortScanHelper.onResume()
  99. registerUsbBroadcast()
  100. }
  101. private val mPortScanHelper by lazy {
  102. PortScanHelper(this, object : OnSerialScanListener {
  103. override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
  104. if (!mHandleScanEvent) {
  105. if (content.isNotBlank()) {
  106. mHandleScanEvent = true
  107. handleScanEvent(content)
  108. }
  109. }
  110. }
  111. })
  112. }
  113. //刷卡usb链接
  114. private fun registerUsbBroadcast() {
  115. if (null == mUsbReceiver) {
  116. val filter = IntentFilter().apply {
  117. addAction(UsbReceiver.ACTION_USB_PERMISSION)
  118. addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
  119. addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
  120. addAction(UsbReceiver.ACTION_USB_STATE) // usb连接状态广播
  121. }
  122. mUsbReceiver = UsbReceiver()
  123. registerReceiver(mUsbReceiver, filter)
  124. }
  125. }
  126. //调用刷卡信息
  127. private fun handleScanEvent(cont: String) {
  128. showLoading("登录中...")
  129. HttpClient.token = null
  130. val disposable = ApiRepository.cardNum(cont)
  131. .subscribe({ data ->
  132. ChemicalApp.userData = data
  133. authenticationInfo(data.userId, ChemicalApp.subjectId!!)
  134. }, { throwable ->
  135. dismissLoading()
  136. throwableView(throwable)
  137. mHandleScanEvent = false
  138. })
  139. addDisposable(disposable)
  140. }
  141. //验证当前人员身份
  142. private fun authenticationInfo(userId: String, subId: String) {
  143. showLoading("验证中...")
  144. val disposable = ApiRepository.userCardValidation(userId, subId)
  145. .subscribe({ data ->
  146. dismissLoading()
  147. LogUtils.json(data)
  148. val allFalse = with(data) {
  149. cabinetAdmin == false &&
  150. belongUser == false &&
  151. toipcUser == false &&
  152. safeUser == false &&
  153. collegeAdmin == false &&
  154. schoolLevelAdmin == false &&
  155. adminUser == false &&
  156. apply == false &&
  157. white == false
  158. }
  159. if (allFalse) {
  160. HttpClient.token = null
  161. ChemicalApp.userData = null
  162. customDialogView(2, "当前身份不符合")
  163. mHandleScanEvent = false
  164. } else {
  165. //校级管理员 schoolLevelAdmin
  166. //院级管理员 collegeAdmin
  167. //实验室负责人 adminUser
  168. //安全负责人 safeUser
  169. //柜锁管理员 cabinetAdmin
  170. //是否化学品归属人 belongUser
  171. //是否化学品归属课题组下成员 toipcUser
  172. if (data.schoolLevelAdmin == true || data.collegeAdmin == true) {
  173. authenticationDialog(data.faceImg, data.userName)
  174. } else if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
  175. //实验室负责人 or 安全负责人 or 柜锁管理员
  176. authenticationDialog(data.faceImg, data.userName)
  177. } else if (data.belongUser == true || data.toipcUser == true) { //当前身份 归属人or课题组
  178. authenticationDialog(data.faceImg, data.userName)
  179. } else if (data.white == true || data.apply == true) {// 白名单和实验室准入
  180. authenticationDialog(data.faceImg, data.userName)
  181. } else {
  182. HttpClient.token = null
  183. ChemicalApp.userData = null
  184. customDialogView(2, "当前身份不符合")
  185. mHandleScanEvent = false
  186. }
  187. }
  188. }, { throwable ->
  189. dismissLoading()
  190. throwableView(throwable)
  191. HttpClient.token = null
  192. ChemicalApp.userData = null
  193. mHandleScanEvent = false
  194. })
  195. addDisposable(disposable)
  196. }
  197. //获取刷卡信息
  198. override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
  199. mPortScanHelper.dispatchKeyEvent(event)
  200. return super.dispatchKeyEvent(event)
  201. }
  202. //停止 销毁广播传递
  203. override fun onPause() {
  204. mPortScanHelper.onPause()
  205. super.onPause()
  206. }
  207. override fun onDestroy() {
  208. super.onDestroy()
  209. mPortScanHelper.onPause()
  210. // 移除回调,以防止内存泄漏
  211. try {
  212. handlerBack.removeCallbacks(countdownRunnable)
  213. } catch (e: Exception) {
  214. }
  215. unregisterReceiver(mUsbReceiver)
  216. // 停止定时更新
  217. EventBus.getDefault().unregister(this) //关闭广播
  218. }
  219. //必须写这个方法 防止注册失败
  220. @Subscribe(threadMode = ThreadMode.MAIN)
  221. fun onUpdateEventEvent(event: KeyEvent) {
  222. }
  223. override fun onBackPressed() {
  224. super.onBackPressed()
  225. UiManager.switcherCashier(this, MainActivity::class.java)
  226. }
  227. override fun cdTime(cd: Int) {
  228. viewBinding.tvReturn.text = "返回${cd}s"
  229. }
  230. private val handlerBack = Handler(Looper.getMainLooper())
  231. private var timeLeftInSeconds = 2
  232. private var mTvView: TextView? = null
  233. private var mDialogsAut: AuthenticationDialog? = null
  234. //身份认证成功
  235. private fun authenticationDialog(faceImg: String?, userName: String) {
  236. MediaPlayerHelper.playRawMp3(this, R.raw.login_ren_zheng_tong_hua)
  237. mDialogsAut = AuthenticationDialog(
  238. this,
  239. faceImg,
  240. ChemicalApp.confs!!.subName,
  241. ChemicalApp.confs!!.deptName,
  242. "${ChemicalApp.confs!!.buildName}${ChemicalApp.confs!!.floorName}",
  243. userName, object : AuthenticationDialog.IClickLit {
  244. override fun onUpView(tvView: TextView) {
  245. mTvView = tvView
  246. }
  247. })
  248. mDialogsAut!!.show()
  249. // 开始倒计时
  250. handlerBack.post(countdownRunnable)
  251. // 获取对话框的 Window 对象
  252. mDialogsAut!!.window?.decorView?.setOnTouchListener { _, event ->
  253. // 判断是否点击了对话框外部空白区域
  254. if (event.action == MotionEvent.ACTION_DOWN) {
  255. val x = event.x
  256. val y = event.y
  257. val dialogView = mDialogsAut!!.window?.decorView
  258. if (dialogView != null && (x < 0 || x > dialogView.width || y < 0 || y > dialogView.height)) {
  259. // 在此处执行点击对话框外部空白区域时的操作
  260. // 例如关闭对话框
  261. // 移除回调,以防止内存泄漏
  262. mDialogsAut!!.dismiss()
  263. finish()
  264. return@setOnTouchListener true
  265. }
  266. }
  267. return@setOnTouchListener false
  268. }
  269. }
  270. private val countdownRunnable = object : Runnable {
  271. override fun run() {
  272. if (timeLeftInSeconds > 0) {
  273. mTvView!!.text = "${timeLeftInSeconds}秒后自动返回首页"
  274. timeLeftInSeconds--
  275. handlerBack.postDelayed(this, 1000)
  276. } else {
  277. mDialogsAut!!.dismiss()
  278. finish()
  279. }
  280. }
  281. }
  282. /**
  283. * 0 没有图标 1 绿色 2红色
  284. * 失败或者成功的弹框
  285. */
  286. private fun customDialogView(types: Int, msg: String) {
  287. if (!this.isFinishing && !this.isDestroyed) {
  288. val customDialog = CustomDialog(this, types, msg)
  289. customDialog.show()
  290. }
  291. }
  292. /**
  293. * 异常处理
  294. */
  295. private fun throwableView(throwable: Throwable) {
  296. when (throwable) {
  297. is NetException -> {
  298. if (throwable.message.isNullOrEmpty()) {
  299. "接口请求失败(${throwable.code})"
  300. } else {
  301. throwable.message!!
  302. }
  303. }
  304. is SocketTimeoutException -> "请求超时,请稍后重试"
  305. is ConnectException -> "无法连接服务器,请检查网络"
  306. is HttpException -> "服务器繁忙,请稍后重试"
  307. else -> null
  308. }?.let { customDialogView(2, "$it") }
  309. }
  310. }