package com.grkj.iscs.presentation

import android.content.Intent
import android.os.Environment
import android.view.View
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.grkj.iscs.BusinessManager
import com.grkj.iscs.view.base.BaseActivity
import com.grkj.iscs.databinding.ActivityPresentationLoginBinding
import com.grkj.iscs.extentions.removeLeadingZeros
import com.grkj.iscs.extentions.toHexStrings
import com.grkj.iscs.modbus.ModBusController
import com.grkj.iscs.model.DeviceConst.DEVICE_TYPE_CARD
import com.grkj.iscs.model.DeviceConst.DEVICE_TYPE_KEY
import com.grkj.iscs.model.DeviceConst.DEVICE_TYPE_LOCK
import com.grkj.iscs.model.DeviceConst.DOCK_TYPE_PORTABLE
import com.grkj.iscs.model.presentation.WorkTicketStatusBean
import com.grkj.iscs.util.ActivityUtils
import com.grkj.iscs.util.Executor
import com.grkj.iscs.util.FileUtil
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.util.log.LogUtil

class PresentationLoginActivity : BaseActivity<ActivityPresentationLoginBinding>() {

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

    override fun initView() {
        val path =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath + "/presentation/presentation.txt"
        val str = FileUtil.readTxt(path)

        if (str.isEmpty()) {
            ToastUtils.tip("未找到 presentation.txt 文件，请先在手机Download目录创建 presentation 文件夹，并将 presentation.txt 文件放入")
            return
        }
        LogUtil.i("Mac Json : $str")
        PresentationManager.cardList =
            Gson().fromJson(str, object : TypeToken<List<PresentationManager.PCardInfoBean>>() {}.type)
        if (PresentationManager.cardList.isEmpty()) {
            ToastUtils.tip("配置列表为空")
            return
        }
        PresentationManager.keyMac = PresentationManager.cardList.first().keyMac
        val lockerList = PresentationManager.cardList.filter { it.isLocker }
        for (i in lockerList.indices) {
            PresentationManager.mLockerList.add(PresentationManager.PLockerBean("上锁人${i + 1}", lockerList[i].rfid, 0))
        }
        val togetherList = PresentationManager.cardList.filter { !it.isLocker }
        for (i in togetherList.indices) {
            PresentationManager.mLockerTogetherList.add(
                PresentationManager.PLockerTogetherBean(
                    "共锁人${i + 1}",
                    false,
                    togetherList[i].rfid,
                    0
                )
            )
        }

        handleLoading(true, "正在初始化设备...")
        BusinessManager.connectDock(true)
        // TODO 时间需要由ModBusController重置后来通知
        Executor.delayOnMain(2000) {
            handleLoading(false)
        }

        BusinessManager.registerStatusListener(this) { dockBean ->
            when (dockBean.type) {
                DOCK_TYPE_PORTABLE -> {
                    dockBean.deviceList.forEach { deviceBean ->
                        if (deviceBean.isExist) {
                            when (deviceBean.type) {
                                DEVICE_TYPE_CARD -> {
                                    ModBusController.readPortalCaseCardRfid(dockBean.addr) { res ->
                                        if (res.size >= 11) {
                                            val rfid = res.copyOfRange(3, 11).toHexStrings(false).removeLeadingZeros()
                                            LogUtil.i("卡片RFID ： $rfid")
                                            if(window.decorView.visibility != View.VISIBLE) {
//                                            ToastUtils.tip("当前页面不可见")
                                                val current = ActivityUtils.currentActivity()
                                                if (current is LockerActivity) {
                                                    current.showDlg(rfid)
                                                } else if (current is LockerTogetherActivity) {
                                                    current.showDlg(rfid)
                                                }
                                            } else {
                                                if (PresentationManager.cardList.any { it.rfid == rfid && it.isLocker}) {
                                                    ToastUtils.tip("登录成功，欢迎 $rfid")
                                                    val intent = Intent(this, LockerActivity::class.java)
                                                    intent.putExtra("card", rfid)
                                                    startActivity(intent)
                                                } else if (PresentationManager.cardList.any { it.rfid == rfid && !it.isLocker}) {
                                                    ToastUtils.tip("登录成功，欢迎 $rfid")
                                                    val intent = Intent(this, LockerTogetherActivity::class.java)
                                                    intent.putExtra("card", rfid)
                                                    startActivity(intent)
                                                } else {
                                                    ToastUtils.tip("登录失败，$rfid 没有权限")
                                                }
                                            }
                                        }
                                    }
                                }


                                DEVICE_TYPE_KEY -> {
                                    Executor.runOnMain {
//                                        BusinessManager.getTicketStatusBusiness(PresentationManager.keyMac, this) { b, s, rst ->
//                                            handleLoading(b, s)
//                                            if (!s.isNullOrEmpty() && s.startsWith("工作票完成接收")) {
//                                                val ticket = s.substring(2)
//                                                val ticketStatusBean = Gson().fromJson(ticket, WorkTicketStatusBean::class.java)
//                                                PresentationManager.updateWorkTicket(ticketStatusBean)
//                                            }
//                                        }
                                    }
                                }
                                DEVICE_TYPE_LOCK -> {
                                    Executor.runOnMain {
                                        ModBusController.readLockRfid(dockBean.addr, deviceBean.idx) { res ->
                                            val rfid = res.copyOfRange(3, 11).toHexStrings(false).removeLeadingZeros()
                                            PresentationManager.updateLockReturnStatus(rfid)
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        BusinessManager.unregisterListener(this)
    }
}