package com.grkj.iscs.presentation

import com.google.gson.Gson
import com.grkj.iscs.modbus.ModBusController
import com.grkj.iscs.model.DeviceConst
import com.grkj.iscs.model.presentation.WorkTicketBean
import com.grkj.iscs.model.presentation.WorkTicketStatusBean
import com.grkj.iscs.util.Executor
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.util.log.LogUtil

object PresentationManager {

//    val cardList = mutableListOf("267747D5", "34A347D5", "464947D5")


    var keyMac = "64:E8:33:47:59:7A"
//        val keyMac = "64:E8:33:47:59:42"

    var cardList: List<PCardInfoBean> = mutableListOf()

    val mSopList = mutableListOf(
        PresentationBean(
            1,
            "组装车间",
            "打包线1",
            "组装包装车间-打包线1-保养",
            "组装包装车间-打包线1-保养",
            "SOP001",
            "保养",
            mutableListOf(PPointBean("E-1", "1DA0C66D031080"), PPointBean("E-2", "1DCAD26D031080"))
        ),
        PresentationBean(
            2,
            "拆解车间",
            "打包线2",
            "拆解包装车间-打包线2-维护",
            "拆解包装车间-打包线2-维护",
            "SOP002",
            "维护",
            mutableListOf(PPointBean("E-3", "1DA0C66D031080"), PPointBean("E-4", "1DCAD26D031080"))
        )
    )

    // 上锁人
//    val mLockerList = mutableListOf("上锁人1", "上锁人2", "上锁人3")
    val mLockerList = mutableListOf<PLockerBean>()
    // 安全员
    val mSafetyList = mutableListOf("安全员1", "安全员2", "安全员3")


    // 共锁人
    val mLockerTogetherList = mutableListOf<PLockerTogetherBean>()
//    val mLockerTogetherList = mutableListOf(
//        PLockerTogetherBean("共锁人1", false, null),
//        PLockerTogetherBean("共锁人2", false, null)
//    )

    var workTicketList = mutableListOf<PServerTicket>()

    // 卡片信息
    data class PCardInfoBean(val rfid: String, val isLocker: Boolean, val keyMac: String) {
        override fun toString(): String {
            return "PCardInfoBean(rfid='$rfid', isLocker=$isLocker, keyMac='$keyMac')"
        }
    }
    // 上锁人
    data class PLockerBean(val name: String, var rfid: String?, var status: Int?)     {   // status:0待上锁 1待解锁 2已解锁
        override fun toString(): String {
            return "PLockerBean(name='$name', rfid=$rfid, status=$status)"
        }
    }

    // 共锁人
    data class PLockerTogetherBean(var name: String? = null, var isChecked: Boolean = false, var rfid: String?, var status: Int?) {  // status:0待上锁 1待解锁 2已解锁
        override fun toString(): String {
            return "PLockerTogetherBean(name=$name, isChecked=$isChecked, rfid=$rfid, status=$status)"
        }
    }

    // 隔离点位
    data class PPointBean(var name: String? = null, var rfid: String? = null) {
        override fun toString(): String {
            return "PPointBean(name=$name, rfid=$rfid)"
        }
    }
    // 服务端工作票(完整)
    data class PServerTicket(
        var ticketId: Int? = null,
        var sopId: Long? = null,
        var sop: PresentationBean? = null,
        var workTicketBean: WorkTicketBean? = null,
        var startTime: String? = null,
        var endTime: String? = null,
        var status: Int? = null,     // 0：待上锁人上锁 1：部分共锁人上锁 2：待共锁人解锁 3：部分共锁人解锁 4：待上锁人解锁 5：待归还设备 6：已完成
        var locker: PLockerBean? = null,    // 上锁人
        var lockerTogetherList: MutableList<PLockerTogetherBean>? = null,  // 共锁人
        var safety: String? = null,  // 安全员
        var isAllLocksReturned: Boolean = false    // 是否归还所有锁具
    ) {
        override fun toString(): String {
            return "PServerTicket(ticketId=$ticketId, sopId=$sopId, sop=$sop, workTicketBean=$workTicketBean, startTime=$startTime, endTime=$endTime, status=$status, locker=$locker, lockerTogetherList=$lockerTogetherList, safety=$safety)"
        }
    }


    fun checkLocker(rfid: String): Int? {
        val locker = workTicketList.find { it.locker?.rfid == rfid && it.status != 6 }?.locker
        if (locker == null) {
            return null
        }
        return locker.status
    }

    fun updateTogetherLockerStatus(rfid: String, rst: Int) {
        if (rst == 1 || rst == 0) {
            workTicketList.find { it.lockerTogetherList?.find { it.rfid == rfid } != null }?.lockerTogetherList?.find { it.rfid == rfid }?.status = rst + 1
        } else {
            ToastUtils.tip("未知共锁人状态更新")
        }
    }



    fun checkTogetherLocker(rfid: String): Int? {
        val pServerTicket = workTicketList.find { itList -> itList.lockerTogetherList?.find { it.rfid == rfid } != null }
        if (pServerTicket == null) {
            return null
        }
        val lockerStatus = pServerTicket.locker?.status
        val togetherStatus = pServerTicket.lockerTogetherList?.find { it.rfid == rfid }?.status
        if (lockerStatus == 0) {
            return 100
        }
        return togetherStatus
    }

    fun updateWorkTicket(ticketStatusBean: WorkTicketStatusBean) {
        LogUtil.i("updateWorkTicket1 : $ticketStatusBean")
        LogUtil.i("updateWorkTicket2 : $workTicketList")
        val statusTicketList = ticketStatusBean.data
        if (statusTicketList.isNullOrEmpty()) {
            ToastUtils.tip("钥匙无工作票数据")
            return
        }
        val taskCodeList = statusTicketList.map { it.taskCode }
        val pServerTicket = workTicketList.find { it.workTicketBean?.data!!.any { taskCodeList.contains(it.taskCode) } }
        val serverTicketList = pServerTicket?.workTicketBean?.data
        if (serverTicketList.isNullOrEmpty()) {
            ToastUtils.tip("无服务端工作票数据")
            return
        }
        serverTicketList.forEach { itServerTicket ->
            var isLockerDone = true
            itServerTicket.dataList?.forEach { itServerTask ->
                statusTicketList.forEach { itStatusTicket ->
                    itStatusTicket.dataList?.forEach { itStatusTask ->
                        if (itServerTask.equipRfidNo == itStatusTask.equipRfidNo) {
                            itServerTask.infoRfidNo = itStatusTask.infoRfidNo
                            if (itStatusTask.target == 0) {
                                itServerTask.target = 1
                            }
                            if (itStatusTask.closed == 0) {
                                isLockerDone = false
                                LogUtil.i("测试打印 ： 有未完成的")
                            }
                        }
                    }
                }
            }
            if (pServerTicket.locker?.status == 0) {
                pServerTicket.status = 1
            } else if (pServerTicket.locker?.status == 1) {
                if (pServerTicket.isAllLocksReturned) {
                    pServerTicket.status = 6
                } else {
                    pServerTicket.status = 5
                }
            }
            if (isLockerDone) {
                LogUtil.i("测试打印 ： 上锁人状态 - ${pServerTicket.locker?.status}")
                if (pServerTicket.locker?.status == 0 || pServerTicket.locker?.status == 1) {
                    pServerTicket.locker?.status = pServerTicket.locker!!.status!! + 1
                }
            }
        }

        LogUtil.i("updateWorkTicket3 : $workTicketList")
    }

    fun getTicketJson(): String {
        val workTicketBean = workTicketList.find { it.workTicketBean?.cardNo == ticketCardNo && (it.status == 0 || it.status == 1) }?.workTicketBean
        if (workTicketBean == null) {
            ToastUtils.tip("暂无可处理的工作票")
        }
        val jsonStr = Gson().toJson(workTicketBean)
        LogUtil.i("getTicketJson : $jsonStr")
        return jsonStr
    }

    var ticketCardNo = ""

    fun updateLockReturnStatus(rfid: String) {
        Executor.runOnMain {
            val pServerTicket = workTicketList.find { it.workTicketBean?.data!!.any { it.dataList!!.any { it.infoRfidNo == rfid } } }
            pServerTicket?.let {
                val dockList = ModBusController.getDockByType(DeviceConst.DOCK_TYPE_PORTABLE)
                if (dockList.isEmpty()) {
                    return@runOnMain
                }
                val dockLockRfidList = dockList[0].getLockList().map { it.rfid }

                val ticketLockRfidList = mutableListOf<String?>()

                // 遍历 data 列表
                it.workTicketBean?.data?.forEach { dataDto ->
                    // 遍历 dataList 列表
                    dataDto.dataList?.forEach { dataListDto ->
                        // 添加 infoRfidNo 到集合中
                        ticketLockRfidList.add(dataListDto.infoRfidNo)
                    }
                }
                it.isAllLocksReturned = dockLockRfidList.containsAll(ticketLockRfidList)
                if (it.isAllLocksReturned && it.status == 5) {
                    ToastUtils.tip("工作票已完成")
                    it.status = 6
                }
            }
        }
    }
}