package com.grkj.iscs.view.fragment

import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.Observer
import com.grkj.iscs.BusinessManager
import com.grkj.iscs.R
import com.grkj.iscs.databinding.FragmentJobProgressBinding
import com.grkj.iscs.extentions.debounce
import com.grkj.iscs.model.bo.PageChangeBO
import com.grkj.iscs.model.eventmsg.MsgEvent
import com.grkj.iscs.model.eventmsg.MsgEventConstants.MSG_EVENT_UPDATE_TICKET_PROGRESS
import com.grkj.iscs.model.eventmsg.UpdateTicketProgressMsg
import com.grkj.iscs.model.vo.ticket.TicketDetailMonitorRespVO
import com.grkj.iscs.util.ToastUtils
import com.grkj.iscs.util.log.LogUtil
import com.grkj.iscs.view.base.BaseMvpFragment
import com.grkj.iscs.view.dialog.TipDialog
import com.grkj.iscs.view.iview.IJobProgressView
import com.grkj.iscs.view.presenter.JobProgressPresenter
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder

/**
 * 作业票工作进度页
 */
class JobProgressFragment(val goBack: () -> Unit) :
    BaseMvpFragment<IJobProgressView, JobProgressPresenter, FragmentJobProgressBinding>() {

    private val mPointList = mutableListOf<TicketDetailMonitorRespVO.IsJobTicketPointsVO>()
    private val mUserList = mutableListOf<TicketDetailMonitorRespVO.IsJobTicketUser>()
    private var mStep = 0
    private var mPageChangeBO: PageChangeBO? = null
    private var mTipDialog: TipDialog? = null
    private lateinit var observer: Observer<MsgEvent>
    private var isVisible: Boolean = false

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

    override fun initView() {
        mBinding?.cbBack?.setOnClickListener { goBack() }

        mBinding?.rvPoint?.adapter =
            object : CommonAdapter<TicketDetailMonitorRespVO.IsJobTicketPointsVO>(requireActivity(), R.layout.item_rv_point, mPointList) {
                override fun convert(holder: ViewHolder, point: TicketDetailMonitorRespVO.IsJobTicketPointsVO, position: Int) {
                    holder.setText(R.id.tv_name, point.pointName)
                    holder.setText(R.id.tv_function, point.remark)
                    holder.setVisible(R.id.iv_status, point.switchStatus != null)
                    holder.getView<ImageView>(R.id.iv_status)
                        .setBackgroundResource(if (point.switchStatus == "1") R.mipmap.switch_off else R.mipmap.switch_on)
                    when(point.pointStatus) {
                        "1" -> {
                            holder.setVisible(R.id.ll_lock_status, true)
                            holder.setText(R.id.tv_lock_status, getString(R.string.has_locked))
                        }
                        "2" -> {
                            holder.setVisible(R.id.ll_lock_status, true)
                            holder.getView<LinearLayout>(R.id.ll_lock_status).isSelected = true
                            holder.setText(R.id.tv_lock_status, getString(R.string.unlocked))
                        }
                    }
                }
            }

        mBinding?.rvColocker?.adapter =
            object : CommonAdapter<TicketDetailMonitorRespVO.IsJobTicketUser>(requireActivity(), R.layout.item_rv_worker_status, mUserList) {
                override fun convert(holder: ViewHolder, user: TicketDetailMonitorRespVO.IsJobTicketUser, position: Int) {
                    holder.setText(R.id.tv_name, user.userName)
                    holder.setVisible(R.id.iv_ready_to_lock, user.jobStatus!! >= 3 || mStep == 6)
                    holder.setVisible(R.id.iv_locked, user.jobStatus >= 4)
                    holder.setVisible(R.id.iv_unlocked, user.jobStatus >= 5)
                }
            }

        mBinding?.cbAction?.debounce(2000) {
            if (mStep == 4) {
                presenter?.handleLockProcess(mPageChangeBO?.ticketId!!)
            } else if (mStep == 7) {
                presenter?.handleUnlockProcess(mPageChangeBO?.ticketId!!)
            }
        }

        observer = Observer { newData ->
            when (newData.code) {
                MSG_EVENT_UPDATE_TICKET_PROGRESS -> {
                    LogUtil.i("Update progress msg, isVisible : $isVisible")
                    if (isVisible) {
                        val ticketId = (newData.data as UpdateTicketProgressMsg).ticketId
                        LogUtil.i("Update progress msg, ticketId : $ticketId")
                        if (ticketId == mPageChangeBO?.ticketId) {
                            mPageChangeBO?.let {
                                refreshPage(it)
                            }
                        }
                    }
                }
            }
        }

        BusinessManager.mEventBus.observe(viewLifecycleOwner, observer)
    }

    override fun onResume() {
        super.onResume()
        isVisible = true
    }

    override fun refreshPage(pageChangeBO: PageChangeBO) {
        mPageChangeBO = pageChangeBO
        presenter?.getTicketDetailMonitor(pageChangeBO.ticketId!!) {
            mPointList.clear()
            mUserList.clear()
            mPointList.addAll(it?.ticketPointsList!!)
            mUserList.addAll(it.colockUserList!!)
            mBinding?.rvPoint?.adapter?.notifyDataSetChanged()
            mBinding?.rvColocker?.adapter?.notifyDataSetChanged()
            handleActionBtnVisibility()
        }
        presenter?.getTicketDetail(pageChangeBO.ticketId) {
            mBinding?.tvTitle?.text = it?.ticketName
        }

        getStepDetail(pageChangeBO.ticketId!!)
    }

    fun getCardNo(cardNo: String) {
        getStepDetail(mPageChangeBO?.ticketId!!) {
            presenter?.getCardInfoByNfc(cardNo) {
                if (it == null) {
                    return@getCardInfoByNfc
                }
                if (mTipDialog == null) {
                    mTipDialog = TipDialog(requireContext())
                }
                val jobStatus = mUserList.find { itUser -> itUser.userId == it.userId }?.jobStatus
                if (jobStatus == null || jobStatus >= 5) {
                    return@getCardInfoByNfc
                }

                if (mStep == 6) {
                    if (jobStatus < 4) {
                        mTipDialog?.setTip(getString(R.string.confirm_to_colock, cardNo))
                    } else {
                        mTipDialog?.setTip(getString(R.string.confirm_to_uncolock, cardNo))
                    }
                    mTipDialog?.setConfirmListener {
                        presenter?.updateColockerStatus(mPageChangeBO?.ticketId!!, cardNo, if (jobStatus < 4) "4" else "5") {
                            refreshPage(mPageChangeBO!!)
                        }
                    }
                    mTipDialog?.showCancelCountdown(10)
                } else {
                    ToastUtils.tip(R.string.can_not_do_colock_action)
                }
            }
        }
    }

    private fun getStepDetail(ticketId: Long, callback: (() -> Unit)? = null) {
        presenter?.getStepDetail(ticketId) {
            mBinding?.tvWorker?.text = "${it?.get(2)?.userNum}/${it?.get(4)?.userNum}/${it?.get(7)?.userNum}"
            mBinding?.tvLock?.text = "${it?.get(2)?.lockNum}/${it?.get(4)?.lockNum}/${it?.get(7)?.lockNum}"

            it?.filter { it.stepStatus == "1" }?.maxByOrNull { it.stepIndex!! }?.stepIndex?.let {
                mStep = it
            }
            handleActionBtnVisibility()
            callback?.invoke()
        }
    }

    private fun handleActionBtnVisibility() {
        when (mStep) {
            4 -> {
                if (!mPointList.all { it.pointStatus == "1" }) {
                    mBinding?.cbAction?.visibility = View.VISIBLE
                }
            }
            7 -> {
                if (!mPointList.all { it.pointStatus == "2" }) {
                    mBinding?.cbAction?.visibility = View.VISIBLE
                    mBinding?.cbAction?.setIcon(R.mipmap.ticket_unlocked)
                    mBinding?.cbAction?.setText(getString(R.string.go_unlocking))
                }
            }
            else -> {
                mBinding?.cbAction?.visibility = View.GONE
            }
        }
        mBinding?.cbAction?.isEnabled = mBinding?.cbAction?.visibility == View.VISIBLE
    }

    override fun onPause() {
        super.onPause()
        mStep = 0
        mTipDialog?.dismiss()
        isVisible = false
    }

    override fun onDestroy() {
        super.onDestroy()
        BusinessManager.mEventBus.removeObserver(observer)
    }

    override fun initPresenter(): JobProgressPresenter {
        return JobProgressPresenter()
    }
}