package com.grkj.iscs.view.presenter

import com.grkj.iscs.BusinessManager
import com.grkj.iscs.R
import com.grkj.iscs.view.base.BasePresenter
import com.grkj.iscs.view.dialog.TipDialog
import com.grkj.iscs.extentions.serialNo
import com.grkj.iscs.view.iview.ITicketDetailView
import com.grkj.iscs.modbus.ModBusController
import com.grkj.iscs.model.Constants.JOB_STATUS_ACQUIRE_KEY
import com.grkj.iscs.model.Constants.JOB_STATUS_ACQUIRE_LOCK
import com.grkj.iscs.model.Constants.JOB_STATUS_NOT_STARTED
import com.grkj.iscs.model.Constants.JOB_STATUS_READY_TO_LOCK
import com.grkj.iscs.model.Constants.JOB_STATUS_READY_TO_UNLOCK
import com.grkj.iscs.model.Constants.JOB_STATUS_UNLOCKED
import com.grkj.iscs.model.Constants.USER_TYPE_COLOCKER
import com.grkj.iscs.model.Constants.USER_TYPE_LOCKER
import com.grkj.iscs.model.vo.lock.LockTakeUpdateReqVO
import com.grkj.iscs.model.vo.ticket.TicketDetailRespVO
import com.grkj.iscs.model.vo.ticket.TicketEquipDetailRespVO
import com.grkj.iscs.util.Executor
import com.grkj.iscs.util.NetApi
import com.grkj.iscs.util.SPUtils
import com.grkj.iscs.util.ToastUtils

class TicketDetailPresenter : BasePresenter<ITicketDetailView>() {
    /**
     * 获取作业票详细信息
     */
    fun getTicketDetail(ticketId: Long?, callBack: (TicketDetailRespVO?) -> Unit) {
        if (ticketId == null) {
            ToastUtils.tip(mContext!!.resources.getString(R.string.ticket_id_is_null))
            return
        }
        NetApi.getTicketDetail(ticketId) {
            Executor.runOnMain {
                callBack.invoke(it)
            }
        }
    }

    fun doAction(vo: TicketDetailRespVO?) {
        val loginUser = SPUtils.getLoginUser(mContext!!)
        if (loginUser == null) {
            ToastUtils.tip(R.string.please_login)
            return
        }

        if (vo?.ticketId == null) {
            return
        }

        val roleList = vo.jobTicketUserList?.filter { it.userId == loginUser.userId }

        // 都判断，防止身兼数职
        if (roleList?.any { it.userType == USER_TYPE_LOCKER } == true) {
            NetApi.getTicketEquipDetail(vo.ticketId) {
                if (it == null) {
                    return@getTicketEquipDetail
                }
                doLockAction(loginUser.userId!!, vo, it)
            }
        }
        if (roleList?.any { it.userType == USER_TYPE_COLOCKER } == true) {
            NetApi.getTicketEquipDetail(vo.ticketId) {
                if (it == null) {
                    return@getTicketEquipDetail
                }
                doCoLockerAction(loginUser.userId!!, vo, it)
            }
        }
    }

    /**
     * 上锁人操作
     */
    private fun doLockAction(userId: Long, ticketDetail: TicketDetailRespVO, equipDetail: TicketEquipDetailRespVO) {
        val role = ticketDetail.jobTicketUserList?.find { it.userId == userId && it.userType == USER_TYPE_LOCKER }
        if (role == null) {
            return
        }

        when(role.jobStatus) {
            JOB_STATUS_NOT_STARTED, JOB_STATUS_ACQUIRE_LOCK -> {
                // 取锁具、取钥匙
                val needLockCount = equipDetail.ticketLockVOList?.filter { it.lockId == null }?.size ?: 0
//                BusinessManager.checkEquipCount(needLockCount) { keyPair, lockMap ->
//                    val list = mutableListOf<LockTakeUpdateReqVO>()
//                    lockMap.forEach { (_, lockList) ->
//                        list.addAll(lockList.map { LockTakeUpdateReqVO(ticketDetail.ticketId, it.rfid, mContext!!.serialNo()) })
//                    }
//                    NetApi.updateLockTake(list) {
//                        if (it == true) {
//                            lockMap.forEach { (addr, lockList) ->
//                                // 开锁卡扣
//                                ModBusController.controlLockBuckle(true, addr, lockList.map { it.idx }.toMutableList())
//                            }
//                        }
//                    }
//                    // null表示锁具数量不够，不给钥匙
//                    if (keyPair != null) {
//                        // 更新钥匙信息
//                        NetApi.updateKeyTake(ticketDetail.ticketId!!, keyPair.second?.rfid!!, mContext!!.serialNo()) {
//                            if (it) {
//                                // 下发工作票
////                                BusinessManager.sendTicketBusiness(keyPair.second?.mac!!, ticketDetail, mvpView as TicketDetailActivity) { b, s, rst ->
////
////                                }
//                            }
//                        }
//                    }
//                }
            }
            JOB_STATUS_ACQUIRE_KEY -> {
                // 这个时候锁具已经全了
//                BusinessManager.checkEquipCount(0) { keyPair, _ ->
//                    // null表示锁具数量不够，不给钥匙
//                    if (keyPair != null) {
//                        // 更新钥匙信息
//                        NetApi.updateKeyTake(ticketDetail.ticketId!!, keyPair.second?.rfid!!, mContext!!.serialNo()) {
//                            if (it) {
//                                // 下发工作票
////                                BusinessManager.sendTicketBusiness(keyPair.second?.mac!!, ticketDetail, mvpView as TicketDetailActivity) { b, s, rst ->
////                                    (mvpView as TicketDetailActivity).handleLoading(b, s)
////                                }
//                            }
//                        }
//                    }
//                }
            }
            JOB_STATUS_READY_TO_LOCK -> {
                // TODO 不用做，由钥匙工作票自动更新
            }
            JOB_STATUS_READY_TO_UNLOCK -> {
                // TODO 弹框，由钥匙工作票自动更新
            }
            JOB_STATUS_UNLOCKED -> {
                ToastUtils.tip(R.string.ticket_is_locker_part_finished)
            }
        }
    }

    /**
     * 共锁人操作
     */
    private fun doCoLockerAction(userId: Long, ticketDetail: TicketDetailRespVO, equipDetail: TicketEquipDetailRespVO) {
        val role = ticketDetail.jobTicketUserList?.find { it.userId == userId && it.userType == USER_TYPE_COLOCKER }
        if (role == null) {
            return
        }
        when(role.jobStatus) {
            JOB_STATUS_NOT_STARTED -> {
                showTipDlg(mContext!!.getString(R.string.make_sure_to_colock)) {
                    SPUtils.getLoginUser(mContext!!)?.userId?.let {
                        NetApi.updateTicketProgress(ticketDetail.ticketId!!, it) {

                        }
                    }
                }
            }
            JOB_STATUS_READY_TO_UNLOCK -> {
                showTipDlg(mContext!!.getString(R.string.make_sure_to_unlock)) {
                    SPUtils.getLoginUser(mContext!!)?.userId?.let {
                        NetApi.updateTicketProgress(ticketDetail.ticketId!!, it) {

                        }
                    }
                }
            }
            JOB_STATUS_UNLOCKED -> {
                ToastUtils.tip(R.string.ticket_is_colocker_part_finished)
            }
        }
    }

    private fun showTipDlg(tip: String, callback: () -> Unit) {
        val dlg = TipDialog(mContext!!)
        dlg.setTip(tip)
        dlg.setConfirmListener {
            callback.invoke()
        }
        dlg.show()
    }
}