package com.grkj.iscs.view.fragment

import com.grkj.iscs.databinding.FragmentJobExecutionBinding
import com.grkj.iscs.model.bo.PageChangeBO
import com.grkj.iscs.util.log.LogUtil
import com.grkj.iscs.view.activity.HomeActivity
import com.grkj.iscs.view.activity.HomeActivity.Menu
import com.grkj.iscs.view.adapter.MenuAdapter
import com.grkj.iscs.view.base.BaseMvpFragment
import com.grkj.iscs.view.iview.IJobExecutionView
import com.grkj.iscs.view.presenter.JobExecutionPresenter

/**
 * 作业执行页
 */
class JobExecutionFragment(val changePageCallback: (PageChangeBO) -> Unit) :
    BaseMvpFragment<IJobExecutionView, JobExecutionPresenter, FragmentJobExecutionBinding>() {

    private lateinit var mMenuList: MutableList<Menu>
    private var mPageChangeBO: PageChangeBO? = null

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

    override fun initView() {
        mMenuList = mutableListOf(
            Menu(fragment = StepFragment({ changePage(PageChangeBO(-1)) }) {
                changePage(it)
            }),
            Menu(fragment = WorkerFragment({ refreshPage(mPageChangeBO!!) }) {
                changePage(it)
            }),
            Menu(fragment = JobProgressFragment { refreshPage(mPageChangeBO!!) })
        )

        mBinding?.vp?.isUserInputEnabled = false
        mBinding?.vp?.offscreenPageLimit = mMenuList.size
        mBinding?.vp?.adapter = MenuAdapter(requireActivity().supportFragmentManager, lifecycle, mMenuList)

        (activity as HomeActivity).cardNoLiveData.observeForever {
            if (mBinding?.vp?.currentItem == 2) {
                (mMenuList[2].fragment as JobProgressFragment).getCardNo(it)
            }
        }
    }

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

    override fun refreshPage(pageChangeBO: PageChangeBO) {
        LogUtil.i("$pageChangeBO")
        mPageChangeBO = pageChangeBO
        mBinding?.vp?.currentItem = 0
        (mMenuList[0].fragment as StepFragment).refreshPage(mPageChangeBO!!)
    }

    private fun changePage(pageChangeBO: PageChangeBO) {
        LogUtil.i("$pageChangeBO")
        if (pageChangeBO.pageIdx == -1) {
            changePageCallback(pageChangeBO)
            return
        }
        mBinding?.vp?.currentItem = pageChangeBO.pageIdx
        mMenuList[pageChangeBO.pageIdx].fragment.refreshPage(pageChangeBO)
    }
}