package xn.hxp.ui.verify

import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.rc.core.ui.activity.BaseActivity
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.UserValidationBean
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.HttpException
import xn.hxp.R
import xn.hxp.app.ChemicalApp
import xn.hxp.comm.Constants
import xn.hxp.databinding.ActivitySwipeCodeTwoBinding
import xn.hxp.receiver.OnSerialScanListener
import xn.hxp.receiver.PortScanHelper
import xn.hxp.receiver.UsbReceiver
import xn.hxp.ui.DoubleDialogBean
import xn.hxp.utils.AudioPlayer
import xn.hxp.utils.HandlerUtil
import xn.hxp.utils.SharedPreferencesHelper
import xn.hxp.utils.UiManager
import xn.hxp.weidith.CustomDialog
import xn.hxp.weidith.DoublePeopleDialog
import java.net.ConnectException
import java.net.SocketTimeoutException

//双人-刷卡认证
class SwipeCodeTwoActivity : BaseActivity() {

    private var mUsbReceiver: UsbReceiver? = null  // 刷卡广播注册
    private var mHandleScanEvent = false //当前是否已经获取过 usb返回的参数
    private var isLogin = false  //是否是登陆人
    private var count = 1   //认证次数
    private var mDoorId: String? = null   //柜门id
    private var mChemicalLevel: Int = 0      //管控类型
    private var mTag = 0     //0  新增入库    1 归还废弃空瓶等   2 待入库  3 领用认证需要换api 需要判断不同权限 进行验证通过
    private var mUserId: String? = null

    private val handlerUtil = HandlerUtil.getInstance()
    private var mVoiceCount = 1  //认证次数
    private val mDoubleDialogBean = mutableListOf<DoubleDialogBean>() //双人认证 需要显示的

    lateinit var viewBinding: ActivitySwipeCodeTwoBinding
    override fun setViewBinding(): ViewBinding {
        viewBinding = ActivitySwipeCodeTwoBinding.inflate(layoutInflater)
        return viewBinding
    }

    override fun onInit() {
        Constants.AUTHENTICATION = false
        //注册广播
        EventBus.getDefault().register(this)
        try {
            SharedPreferencesHelper.clearList(this)
        } catch (e: Exception) {
        }
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        mTag = intent.getIntExtra("mTag", 0)
        val intExtra = intent.getIntExtra("hides", 0)
        mDoorId = intent.getStringExtra("doorId")
        mChemicalLevel = intent.getIntExtra("chemicalLevel", 0)
        if (intExtra == 4) {
            viewBinding.lint.visibility = View.GONE
            viewBinding.lintTwo.visibility = View.GONE
        } else if (intExtra == 2) {
            viewBinding.face.visibility = View.GONE
            viewBinding.faceTwo.visibility = View.GONE
        }
        val map = mutableMapOf<String, Any>()
        //跳转扫码
        map["chemicalLevel"] = mChemicalLevel  //管控类型
        map["doorId"] = "$mDoorId"  //柜子id
        map["mTag"] = mTag
        map["hides"] = intExtra   //隐藏扫码
        viewBinding.face.setOnClickListener {

            //需要双人认证  人脸
            UiManager.switcher(this, map, TwoPersonActivity::class.java)
            finish()
        }
        viewBinding.wxScan.setOnClickListener {

            UiManager.switcher(this, map, ScanCodeTwoActivity::class.java)
            finish()
        }
        viewBinding.faceTwo.setOnClickListener {

            //需要双人认证  人脸
            UiManager.switcher(this, map, TwoPersonActivity::class.java)
            finish()
        }
        viewBinding.wxScanTwo.setOnClickListener {

            UiManager.switcher(this, map, ScanCodeTwoActivity::class.java)
            finish()
        }

        viewBinding.tvReturn.setOnClickListener {

            finish()
        }

        viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(viewBinding.image)
        AudioPlayer.getInstance().play(R.raw.first_card_verify)
//        customDialogView(0,"请第一个人进行认证")
        // 定义一个定时任务  双人-刷卡认证
//        val task = object : TimerTask() {
//            override fun run() {
//                if (mVoiceCount == 6) {
//                    finish()
//                }
//                if (count == 1) {
//                    MediaPlayerHelper.playRawMp3(
//                        this@SwipeCodeTwoActivity,
//                        R.raw.diyiwei_shua_ka_renzheng
//                    )
//                } else {
//                    MediaPlayerHelper.playRawMp3(
//                        this@SwipeCodeTwoActivity,
//                        R.raw.dierweishuakarenzheng
//                    )
//                }
//                mVoiceCount++
//            }
//        }

        // 使用 schedule 方法执行任务，延迟 0 毫秒，每隔 10 秒执行一次
//        mTimer.schedule(task, 0, 10000)
        handlerUtil.startTask(task, 10000)
    }

    private val task = Runnable {
        if (mVoiceCount == 6) {
            finish()
        }
        if (count == 1) {
            AudioPlayer.getInstance().play(R.raw.first_card_verify)
        } else {
            AudioPlayer.getInstance().play(R.raw.second_card_verify)
        }
        mVoiceCount++

    }

    override fun onResume() {
        super.onResume()
        mPortScanHelper.onResume()
        registerUsbBroadcast()
    }

    override fun onBackPressed() {
        super.onBackPressed()

        finish()
    }

    override fun cdTime(cd: Int) {
        viewBinding.tvReturn.text = "返回${cd}s"
    }

    private val mPortScanHelper by lazy {
        PortScanHelper(this, object : OnSerialScanListener {
            override fun dispatchScanEvent(type: OnSerialScanListener.ScanType, content: String) {
                if (!mHandleScanEvent) {
                    if (content.isNotBlank()) {
                        mHandleScanEvent = true
                        handleScanEvent(content)
                    }
                }
            }

        })
    }

    //刷卡usb链接
    private fun registerUsbBroadcast() {
        if (null == mUsbReceiver) {
            val filter = IntentFilter().apply {
                addAction(UsbReceiver.ACTION_USB_PERMISSION)
                addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
                addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
                addAction(UsbReceiver.ACTION_USB_STATE) // usb连接状态广播
            }
            mUsbReceiver = UsbReceiver()
            registerReceiver(mUsbReceiver, filter)
        }
    }

    //调用刷卡信息
    private fun handleScanEvent(cont: String) {
        //只有 0  1    1代表 已经需要第二次进行验证
        showLoading("验证中...")
        val mutableMap = mutableMapOf<String, String>()
        mutableMap["cardNum"] = "$cont"
        mutableMap["subId"] = "${ChemicalApp.subjectId}"
        mutableMap["doorId"] = "$mDoorId"
        val disposable = ApiRepository.useCardVerify(mutableMap)
            .subscribe({ data ->
                dismissLoading()
                if (count == 1) {
                    mUserId = data.userId
                    LogUtils.i("第a一个人 $mUserId    ${data.userId}")
                } else {
                    LogUtils.i("第b一个人 $mUserId    ${data.userId}")
                    if (mUserId.equals(data.userId) && count == 2) {
                        customDialogView(0, "不能是同一人")
                        mHandleScanEvent = false
                        return@subscribe
                    }
                }

                //0  新增入库    1 领用归还废弃空瓶等   2 待入库   需要判断不同权限 进行验证通过
                when (mTag) {
                    0 -> {
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                count++
                                mHandleScanEvent = false
                                isLogin = true
                                customDialog(data.userName, data.faceImg)
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                if (mChemicalLevel == 1) {
                                    //管控 校级管理员或院级管理
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        count++
                                        mHandleScanEvent = false
                                        if (count == 2) {
                                            customDialog(data.userName, data.faceImg)
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                        } else {
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                            passThrough()
                                        }
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                } else {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        count++
                                        mHandleScanEvent = false
                                        if (count == 2) {
                                            customDialog(data.userName, data.faceImg)
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                        } else {
                                            var bean = DoubleDialogBean(
                                                data.userName,
                                                data.faceImg,
                                                data.userId
                                            )
                                            mDoubleDialogBean.add(bean)
                                            passThrough()
                                        }
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                }

                            }
                        } else if (count == 2) {
                            if (isLogin) {
                                //已经有登陆人
                                if (mChemicalLevel == 1) {
                                    //管控 校级管理员或院级管理
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                } else {
                                    if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "无权限信息")
                                    }
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "无权限信息")
                                }
                            }
                        }

                    }

                    1 -> { //归还业务  标签管理
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                count++
                                mHandleScanEvent = false
                                isLogin = true
                                customDialog(data.userName, data.faceImg)
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                obtainCertification(data)
                            }
                        } else if (count == 2) {
                            if (isLogin) {
                                if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "认证失败")
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "认证失败")
                                }
                            }
                        }
                    }

                    2 -> {//待入库
                        if (count == 1) {
                            if (data.userId == ChemicalApp.userData!!.userId) {
                                count++
                                mHandleScanEvent = false
                                isLogin = true
                                customDialog(data.userName, data.faceImg)
                                var bean =
                                    DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                mDoubleDialogBean.add(bean)
                            } else {
                                toBeStored(data)
                            }
                        } else if (count == 2) {
                            if (isLogin) {
                                if (mChemicalLevel == 1) {
                                    //管控
                                    if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "认证失败")
                                    }
                                } else {
                                    //非管控  实验室负责人or安全负责人or柜锁管理员
                                    if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        mHandleScanEvent = false
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            } else {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                    passThrough()
                                } else {
                                    mHandleScanEvent = false
                                    customDialogView(0, "认证失败")
                                }
                            }
                        }
                    }
                }
            }, { throwable ->
                dismissLoading()
//                showNetError(throwable)
                mHandleScanEvent = false
                throwableView(throwable)
            })
        addDisposable(disposable)

    }


    private fun obtainCertification(data: UserValidationBean) {
        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
            count++
            mHandleScanEvent = false
            customDialog(data.userName, data.faceImg)
            var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
            mDoubleDialogBean.add(bean)
        } else {
            mHandleScanEvent = false
            customDialogView(0, "认证失败")
        }
    }

    private fun toBeStored(data: UserValidationBean) {
        if (mChemicalLevel == 1) {
            //管控
            if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                count++
                mHandleScanEvent = false
                customDialog(data.userName, data.faceImg)
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                mHandleScanEvent = false
                customDialogView(0, "认证失败")
            }
        } else {
            //非管控  实验室负责人or安全负责人or柜锁管理员
            if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                count++
                mHandleScanEvent = false
                customDialog(data.userName, data.faceImg)
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                mHandleScanEvent = false
                customDialogView(0, "认证失败")
            }
        }
    }

    private fun customDialog(userName: String, imgUrl: String?) {
//        customDialogView(0,"请第二个人进行认证")
        viewBinding.through.visibility = View.VISIBLE
        viewBinding.userName.text = "$userName"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}$imgUrl")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .error(R.mipmap.icon_zhan_wei)
            .into(viewBinding.imgView)
        AudioPlayer.getInstance().play(R.raw.first_card_verify)
    }

    //获取刷卡信息
    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        mPortScanHelper.dispatchKeyEvent(event)
        return super.dispatchKeyEvent(event)
    }

    //停止 销毁广播传递
    override fun onPause() {
        mPortScanHelper.onPause()
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPortScanHelper.onPause()
        // 停止定时更新
        unregisterReceiver(mUsbReceiver)
        try {
            handlerUtil.removeCallbacks(task)
            handlerUtil.stopAllTasks()
            handlerBack.removeCallbacks(countdownRunnable)
            handlerBack.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }
        EventBus.getDefault().unregister(this) //关闭广播
    }

    override fun cdFinish() {
        finish()
    }

    //必须写这个方法  防止注册失败
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUpdateEventEvent(event: KeyEvent) {

    }

    /**
     * 0  没有图标 1 绿色(成功)   2红色（失败）
     *   失败或者成功的弹框
     */
    private fun customDialogView(types: Int, msg: String) {
        if (!this.isFinishing && !this.isDestroyed) {
            val customDialog = CustomDialog(this, types, msg)
            customDialog.show()
        }
    }

    /**
     * 异常处理
     */
    private fun throwableView(throwable: Throwable) {
        when (throwable) {
            is NetException -> {
                if (throwable.message.isNullOrEmpty()) {
                    "接口请求失败(${throwable.code})"
                } else {
                    throwable.message!!
                }
            }

            is SocketTimeoutException -> "请求超时，请稍后重试"
            is ConnectException -> "无法连接服务器，请检查网络"
            is HttpException -> "服务器繁忙，请稍后重试"
            else -> null
        }?.let { customDialogView(2, "$it") }
    }

    private lateinit var dialogsAut: DoublePeopleDialog
    private var timeLeftInSeconds = 2
    private var mTvView: TextView? = null
    private val handlerBack = Handler(Looper.getMainLooper())

    //验证通过
    private fun passThrough() {
        try {
            handlerUtil.removeCallbacks(task)
            handlerUtil.stopAllTasks()
        } catch (e: Exception) {

        }
        // 在需要时关闭定时器
        try {
            // 取消定时器，停止所有任务的执行
            LogUtils.i("验证通过${mDoubleDialogBean[0].name}")
            LogUtils.i("验证通过${mDoubleDialogBean[1].name}")
        } catch (e: Exception) {
        }
        Constants.AUTHENTICATION = true
        // 存储集合到 SharedPreferences

        SharedPreferencesHelper.saveList(this, mDoubleDialogBean)
        dialogsAut =
            DoublePeopleDialog(this, mDoubleDialogBean, object : DoublePeopleDialog.IClickLit {
                override fun onUpView(tvView: TextView) {
                    mTvView = tvView
                }
            })
        dialogsAut.show()
        // 开始倒计时
        handlerBack.post(countdownRunnable)
        // 获取对话框的 Window 对象
        dialogsAut?.window?.decorView?.setOnTouchListener { _, event ->
            // 判断是否点击了对话框外部空白区域
            if (event.action == MotionEvent.ACTION_DOWN) {
                val x = event.x
                val y = event.y
                val dialogView = dialogsAut?.window?.decorView
                if (dialogView != null && (x < 0 || x > dialogView.width || y < 0 || y > dialogView.height)) {
                    // 在此处执行点击对话框外部空白区域时的操作
                    // 例如关闭对话框
                    dialogsAut.dismiss()
                    finish()
                    return@setOnTouchListener true
                }
            }
            return@setOnTouchListener false
        }
        AudioPlayer.getInstance().play(R.raw.verify_success)
    }

    private val countdownRunnable = object : Runnable {
        override fun run() {
            if (timeLeftInSeconds > 0) {
                mTvView!!.text = "${timeLeftInSeconds}秒后自动返回首页"
                timeLeftInSeconds--
                handlerBack.postDelayed(this, 1000)
            } else {
                dialogsAut!!.dismiss()
                finish()
            }
        }
    }


}