package com.example.chemical.ui.verify

import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityScanCodeTwoBinding
import com.example.chemical.ui.DoubleDialogBean
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.utils.*
import com.example.chemical.weidith.CustomDialog
import com.example.chemical.weidith.DoublePeopleDialog
import com.google.zxing.BarcodeFormat
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.lztek.toolkit.Lztek
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.bean.UserValidationBean
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.*

//扫码-双人认证
class ScanCodeTwoActivity : BaseCountDownActivity<ActivityScanCodeTwoBinding>() {
    private var count = 1   //认证次数
    private var mChemicalLevel: Int = 0      //管控类型
    private var mTag = 0     //0  新增入库    1 归还废弃空瓶等   2 待入库  3 领用认证需要换api 需要判断不同权限 进行验证通过
    private var mUserId: String? = null  //第二个人
    private var mDoorId: String? = null
    private var isLogin = false  //是否是登陆人
    private var mLztek: Lztek? = null
    private var mDeviceNum: String? = null  //设备唯一标识
    private var currentDateTimeOne: String? = null
    private var currentDateTimeTwo: String? = null
    private val handler = Handler()  //扫码查询
    private val mTimer = Timer()
    private val handlerUtil = HandlerUtil.getInstance()  //语音播放
    private var mVoiceCount = 1  //认证次数
    private val mDoubleDialogBean = mutableListOf<DoubleDialogBean>() //双人认证 需要显示的

    override fun createViewBinding() = ActivityScanCodeTwoBinding.inflate(LayoutInflater.from(this))

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        Constants.AUTHENTICATION = false
        try {
            SharedPreferencesHelper.clearList(this)
        } catch (e: Exception) {
        }
        mTag = intent.getIntExtra("mTag", 0)
        mDoorId = intent.getStringExtra("doorId")  //柜子id
        mChemicalLevel = intent.getIntExtra("chemicalLevel", 0)
        val intExtra = intent.getIntExtra("hides", 0)
        Constants.AUTHENTICATION = false
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        if (intExtra == 4) {
            viewBinding.lint.visibility = View.GONE
            viewBinding.lintTwo.visibility = View.GONE
        } else if (intExtra == 2) {//刷卡 跳转扫码  隐藏人脸
            viewBinding.face.visibility = View.GONE
            viewBinding.faceTow.visibility = View.GONE
        }


        mLztek = Lztek.create(this)
        val toUpperCase = mLztek!!.ethMac.toUpperCase()
        mDeviceNum = toUpperCase.replace(":", "")
        currentDateTimeOne = TimesUils.getCurrentDateTime()
        Thread.sleep(10)
        currentDateTimeTwo = TimesUils.getCurrentDateTime()
        var cont =
            "https://lab.zjznai.com/labTest?doorId=${mDoorId}&subId=${ChemicalApp.subjectId!!}&type=12&macId=${mDeviceNum}&code=${currentDateTimeOne}" // 要生成二维码的文本内容
        loadQRCodeIntoImageView(cont, 100, 100, viewBinding.imgOne)
        var tow =
            "https://lab.zjznai.com/labTest?doorId=${mDoorId}&subId=${ChemicalApp.subjectId!!}&type=12&macId=${mDeviceNum}&code=${currentDateTimeTwo}" // 要生成二维码的文本内容
        loadQRCodeIntoImageView(tow, 100, 100, viewBinding.imgTwo)
        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.card.setOnClickListener {

            UiManager.switcher(
                this,
                map,
                SwipeCodeTwoActivity::class.java,
                Constants.REQUEST_CODE
            )
            finish()
        }
        viewBinding.faceTow.setOnClickListener {

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

            UiManager.switcher(
                this,
                map,
                SwipeCodeTwoActivity::class.java
            )
            finish()
        }
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }
        MediaPlayerHelper.playRawMp3(this, R.raw.diyiren_saoma)

        handlerUtil.startTask(task, 10000)
    }

    // 定义一个定时任务  扫码-双人认证
    private val task = Runnable {
        if (mVoiceCount == 6) {
            finish()
        }
        if (count == 1) {
            MediaPlayerHelper.playRawMp3(this@ScanCodeTwoActivity, R.raw.diyiren_saoma)
        } else {
            MediaPlayerHelper.playRawMp3(this@ScanCodeTwoActivity, R.raw.dierren_saoma)
        }
        mVoiceCount++

    }

    override fun initData() {
        super.initData()
        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)

        // 在3秒后执行延迟任务
        handler.postDelayed(delayedTask, 4000)
    }


    private val delayedTask = object : Runnable {
        override fun run() {
            // 在这里编写需要延迟执行的代码
            scanLogin(mDeviceNum!!)
            // 调度下一次延迟任务，确保在执行完后再延迟3.5秒
            handler.postDelayed(this, 4000)
        }
    }

    private fun scanLogin(macId: String) {
        if (count == 2) {
            if (viewBinding.imgTwo.visibility == View.GONE) {
                viewBinding.imgTwo.visibility = View.VISIBLE
                currentDateTimeOne = currentDateTimeTwo
            }
        }
        showLoading("查询中...")
        val disposable =
            ApiRepository.aioScanLogin(ChemicalApp.subjectId!!, mDoorId!!, currentDateTimeOne!!)
                .subscribe({ data ->
                    dismissLoading()
                    if (count == 1) {
                        mUserId = data.userId
                        RcLog.info("第a一个人 $mUserId    ${data.userId}")
                    } else {
                        if (mUserId.equals(data.userId) && count == 2) {
                            customDialogView(0, "不能是同一个人")
//                            customDialog(data.userName, data.faceImg)
//                            var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
//                            mDoubleDialogBean.add(bean)
//                            scanLogin(macId)
                            return@subscribe
                        }
                    }

                    //0  新增入库    1 领用归还废弃空瓶等   2 待入库   需要判断不同权限 进行验证通过
                    when (mTag) {
                        0 -> {
                            //新增入库
                            if (count == 1) {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    count++
                                    isLogin = true
                                    scanLogin(macId)
                                    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++
                                            if (count == 2) {
                                                scanLogin(macId)
                                                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 {
                                            customDialogView(0, "无权限信息")
                                        }
                                    } else {
                                        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                                            count++
                                            if (count == 2) {
                                                scanLogin(macId)
                                                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 {
                                            customDialogView(0, "无权限信息")
                                        }
                                    }
                                }
                            } else {
                                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 {
                                            customDialogView(2, "无权限信息")
                                        }
                                    } 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 {
                                            customDialogView(0, "无权限信息")
                                        }
                                    }
                                } else {
                                    if (data.userId == ChemicalApp.userData!!.userId) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "无权限信息")
                                    }
                                }
                            }
                        }
                        1 -> { //归还业务 领用  标签管理
                            if (count == 1) {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    count++
                                    isLogin = true
                                    scanLogin(macId)
                                    customDialog(data.userName, data.faceImg)
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                } else {
                                    obtainCertification(data, macId)
                                }
                            } else {
                                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 {
                                        customDialogView(0, "认证失败")
                                    }
                                } else {
                                    if (data.userId == ChemicalApp.userData!!.userId) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            }
                        }
                        2 -> {//待入库
                            if (count == 1) {
                                if (data.userId == ChemicalApp.userData!!.userId) {
                                    count++
                                    isLogin = true
                                    scanLogin(macId)
                                    customDialog(data.userName, data.faceImg)
                                    var bean =
                                        DoubleDialogBean(data.userName, data.faceImg, data.userId)
                                    mDoubleDialogBean.add(bean)
                                } else {
                                    toBeStored(data, macId)
                                }
                            } else {
                                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 {
                                            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 {
                                            customDialogView(0, "认证失败")
                                        }
                                    }
                                } else {
                                    if (data.userId == ChemicalApp.userData!!.userId) {
                                        var bean = DoubleDialogBean(
                                            data.userName,
                                            data.faceImg,
                                            data.userId
                                        )
                                        mDoubleDialogBean.add(bean)
                                        passThrough()
                                    } else {
                                        customDialogView(0, "认证失败")
                                    }
                                }
                            }
                        }
                    }

                }, { throwable ->
                    dismissLoading()
                    throwableView(throwable)
//                    // 定义延迟执行的任务
//                    val delayedTask = object : Runnable {
//                        override fun run() {
//                            // 在这里编写需要延迟执行的代码
//                            scanLogin(mDeviceNum!!)
//                            // 任务执行后移除该任务，避免再次执行
//                            handler.removeCallbacks(this)
//                        }
//                    }
//                    // 在3秒后执行延迟任务
//                    handler.postDelayed(delayedTask, 3000)
                })
        addDisposable(disposable)
    }


    private fun obtainCertification(data: UserValidationBean, macId: String) {
        //校级管理员 schoolLevelAdmin
        //院级管理员  collegeAdmin
        //实验室负责人 adminUser
        //安全负责人 safeUser
        //柜锁管理员 cabinetAdmin
        //是否化学品归属人 belongUser
        //是否化学品归属课题组下成员  toipcUser
        if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
            count++
            scanLogin(macId)
            customDialog(data.userName, data.faceImg)
            var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
            mDoubleDialogBean.add(bean)
        } else {
            customDialogView(0, "认证失败")
        }
    }

    private fun toBeStored(data: UserValidationBean, macId: String) {
        //校级管理员 schoolLevelAdmin
        //院级管理员  collegeAdmin
        //实验室负责人 adminUser
        //安全负责人 safeUser
        //柜锁管理员 cabinetAdmin
        //是否化学品归属人 belongUser
        //是否化学品归属课题组下成员  toipcUser
        if (mChemicalLevel == 1) {
            //管控
//            if (data.belongUser == true || data.toipcUser == true || data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
            if (data.adminUser == true || data.safeUser == true || data.cabinetAdmin == true) {
                count++
                scanLogin(macId)
                customDialog(data.userName, data.faceImg)
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                customDialogView(0, "认证失败")
            }
        } else {
            //非管控  实验室负责人or安全负责人or柜锁管理员
            if (data.safeUser == true || data.adminUser == true || data.cabinetAdmin == true) {
                count++
                scanLogin(macId)
                customDialog(data.userName, data.faceImg)
                var bean = DoubleDialogBean(data.userName, data.faceImg, data.userId)
                mDoubleDialogBean.add(bean)
            } else {
                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)
        MediaPlayerHelper.playRawMp3(this@ScanCodeTwoActivity, R.raw.dierren_saoma)
    }

    // 使用 Glide 加载二维码到 ImageView
    private fun loadQRCodeIntoImageView(
        text: String,
        width: Int,
        height: Int,
        imageView: ImageView
    ) {
        val bitmap = generateQRCode(text, width, height)
        bitmap?.let {
            Glide.with(this)
                .load(it)
                .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
                .into(imageView)
        }
    }

    // 生成二维码的函数
    private fun generateQRCode(text: String, width: Int, height: Int): Bitmap? {
        try {
            val bitMatrix: BitMatrix =
                MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height)
            val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            for (x in 0 until width) {
                for (y in 0 until height) {
                    bitmap.setPixel(
                        x,
                        y,
                        if (bitMatrix[x, y]) 0xFF000000.toInt() else 0xFFFFFFFF.toInt()
                    )
                }
            }
            return bitmap
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            try {
                handlerUtil.removeCallbacks(task)
                handlerUtil.stopAllTasks()
            } catch (e: Exception) {

            }
        } catch (e: Exception) {
        }

        try {
            handlerBack.removeCallbacks(countdownRunnable)
            handlerBack.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }

        try {
            handler.removeCallbacks(delayedTask)
            handler.removeCallbacksAndMessages(null)
        } catch (e: Exception) {
        }
    }

    /**
     * 0  没有图标 1 绿色(成功)   2红色（失败）
     *   失败或者成功的弹框
     */
    private fun customDialogView(types: Int, msg: String) {
//        handler.postDelayed(delayedTask, 3000)
        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 = 5
    private var mTvView: TextView? = null
    private val handlerBack = Handler(Looper.getMainLooper())

    //验证通过
    private fun passThrough() {
        // 在需要时关闭定时器
        try {
            handlerUtil.removeCallbacks(task)
            handlerUtil.stopAllTasks()
        } catch (e: Exception) {
        }

        try {
            handler.removeCallbacks(delayedTask)
            handler.removeCallbacksAndMessages(null)
        } 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
        }
        MediaPlayerHelper.playRawMp3(this, R.raw.shuangren_tongguo)
    }

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