package com.grkj.iscs.view.fragment

import android.view.View
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.google.android.material.card.MaterialCardView
import com.grkj.iscs.R
import com.grkj.iscs.databinding.FragmentStepBinding
import com.grkj.iscs.model.bo.PageChangeBO
import com.grkj.iscs.model.vo.machinery.MachineryDetailRespVO
import com.grkj.iscs.model.vo.ticket.LotoMapRespVO
import com.grkj.iscs.model.vo.ticket.StepDetailRespVO
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.IStepView
import com.grkj.iscs.view.presenter.StepPresenter
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder
import kotlin.math.ceil
import kotlin.math.sqrt

/**
 * 作业票执行步骤页 - 八大步骤
 */
class StepFragment(val goBack: () -> Unit, val changePage: (PageChangeBO) -> Unit) :
    BaseMvpFragment<IStepView, StepPresenter, FragmentStepBinding>() {

    private lateinit var mStepList: MutableList<StepBO>
    private var mLotoList = mutableListOf<LotoMapRespVO>()
    private var mChangePage: PageChangeBO? = null
    private var mMachineryDetail: MachineryDetailRespVO? = null
    private var mStep: Int = 0
    private lateinit var mTipDialog: TipDialog

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

    override fun initView() {
        mTipDialog = TipDialog(requireActivity())
        mStepList = mutableListOf(
            StepBO(R.mipmap.step1, getString(R.string.recognize_work_content), 1, "①"),
            StepBO(R.mipmap.step2, getString(R.string.power_isolation_way), 2, "②"),
            StepBO(R.mipmap.step3, getString(R.string.notice_worker), 3, "③"),
            StepBO(R.mipmap.step4, getString(R.string.shutdown), 4, "④"),
            StepBO(R.mipmap.step5, getString(R.string.unlock_and_restore_switch), 8, "⑧"),
            StepBO(R.mipmap.step6, getString(R.string.check_before_unlocking), 7, "⑦"),
            StepBO(R.mipmap.step7, getString(R.string.ensure_power_isolation), 6, "⑥"),
            StepBO(R.mipmap.step8, getString(R.string.lock_and_hang_a_sign), 5, "⑤")
        )
        mBinding?.rvStep?.adapter = object : CommonAdapter<StepBO>(requireContext(), R.layout.item_rv_step, mStepList) {
            override fun convert(holder: ViewHolder, step: StepBO, position: Int) {
                if (step.stepDetail?.stepStatus == "1") {
                    holder.getView<MaterialCardView>(R.id.cv_step)
                        .setCardBackgroundColor(requireContext().getColor(R.color.item_rv_step_bg_done))
                } else {
                    holder.getView<MaterialCardView>(R.id.cv_step).setCardBackgroundColor(
                        if (mStep + 1 == step.index)
                            requireContext().getColor(R.color.item_rv_step_bg_doing)
                        else
                            requireContext().getColor(R.color.common_bg_white_10)
                    )
                }

                holder.setVisible(R.id.iv_arrow_right, step.index !in 4..5)
                holder.setVisible(R.id.iv_arrow_bottom, step.index == 4)
                holder.getView<ImageView>(R.id.iv_arrow_right).rotation = if (step.index > 5) 180f else 0f
                holder.getView<ImageView>(R.id.iv_icon).setImageResource(step.pic)
                holder.setText(R.id.tv_name, step.stepDetail?.androidStepContent)
                holder.setText(R.id.tv_index, step.indexStr)
                holder.getView<ImageView>(R.id.iv_status).setImageResource(if (step.stepDetail?.stepStatus == "1") R.mipmap.step_executed else R.mipmap.step_not_executed)
                holder.setText(R.id.tv_status,
                    if (step.stepDetail?.stepStatus == "1") {
                        if (step.index == 3) getString(R.string.allocated) else getString(R.string.executed)
                    } else {
                        if (step.index == 3) getString(R.string.not_allocated) else getString(R.string.not_executed)
                    }
                )
                holder.setOnClickListener(R.id.root) {
                    handleStep(step.index)
                }
            }
        }
        
        mBinding?.rvLoto?.adapter = object : CommonAdapter<LotoMapRespVO>(requireContext(), R.layout.item_rv_loto, mLotoList) {
            override fun convert(holder: ViewHolder, loto: LotoMapRespVO, position: Int) {
                val cl = holder.getView<ConstraintLayout>(R.id.cl_container)
                val param = cl.layoutParams
                param.width = param.width * 3 / (mBinding?.rvLoto?.layoutManager as GridLayoutManager).spanCount
                cl.layoutParams = param

                Glide.with(this@StepFragment).load(loto.pointIcon).into(holder.getView(R.id.iv_icon))
                holder.setText(R.id.tv_name, loto.pointName)
                holder.setVisible(R.id.rl_cover, mMachineryDetail?.pointIdList?.contains(loto.pointId!!) == true)
            }
        }

        mBinding?.cbBack?.setOnClickListener { goBack() }

        mBinding?.cbAction?.setOnClickListener {
            if (mStep in 1..5) {
                presenter?.cancelTicket(mChangePage?.ticketId!!) {
                    if (it) changePage(PageChangeBO(-1))
                }
            } else if (mStep == 8) {
                if (mStepList.find { it.index == 8 }?.stepDetail?.conflictJobNum != 0) {
                    mTipDialog.setTip(getString(R.string.action_confirm_finish_ticket))
                    mTipDialog.setConfirmListener {
                        presenter?.finishTicket(mChangePage?.ticketId!!) {
                            if (it) changePage(PageChangeBO(-1))
                        }
                    }
                    mTipDialog.show()
                } else {
                    presenter?.finishTicket(mChangePage?.ticketId!!) {
                        if (it) changePage(PageChangeBO(-1))
                    }
                }
            }
        }

        mBinding?.llDetail?.setOnClickListener {
            if (mStep >= 4) {
                changePage(PageChangeBO(2, mChangePage?.workstationId, mChangePage?.ticketId,
                    mChangePage?.machineryId, mChangePage?.machineryName))
            }
        }
    }

    override fun refreshPage(pageChangeBO: PageChangeBO) {
        LogUtil.i("$pageChangeBO")
        mChangePage = pageChangeBO

        presenter?.getTicketDetail(pageChangeBO.ticketId) {
            mBinding?.tvTitle?.text = it?.ticketName
        }

        presenter?.getStepDetail(pageChangeBO.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}"
            mStepList.forEach { step ->
                step.stepDetail = it?.find { it.stepIndex == step.index }
            }
            mBinding?.rvStep?.adapter?.notifyDataSetChanged()
            it?.filter { it.stepStatus == "1" }?.maxByOrNull { it.stepIndex!! }?.stepIndex?.let {
                mStep = it
            }
            if (mStep <= 5) {
                mBinding?.cbAction?.visibility = View.VISIBLE
                mBinding?.cbAction?.setText(getString(R.string.cancel_the_job))
            } else if (mStep == 8) {
                mBinding?.cbAction?.visibility = View.VISIBLE
                mBinding?.cbAction?.setText(getString(R.string.finish_the_job))
            } else {
                mBinding?.cbAction?.visibility = View.GONE
            }
        }

        presenter?.getMachineryDetail(pageChangeBO.machineryId!!,
            {
                mMachineryDetail = it
                Glide.with(this).load(it?.machineryImg).into(mBinding?.ivMachinery!!)
            }) { itList ->
            itList?.let {
                mLotoList.clear()
                mLotoList.addAll(it)
            } ?: mLotoList.clear()

            val spanCount = (ceil(sqrt(mLotoList.size.toFloat())) - 1).toInt()
            (mBinding?.rvLoto?.layoutManager as GridLayoutManager).spanCount = spanCount

            mBinding?.rvLoto?.adapter?.notifyDataSetChanged()
        }
    }

    private fun handleStep(step: Int) {
        when (step) {
            3 -> {
                if (mStep == 0 || mStep > 5) return
                changePage(PageChangeBO(1, mChangePage?.workstationId, mChangePage?.ticketId, mChangePage?.machineryId, mChangePage?.machineryName))
            }
            4 -> {
                if (mStep == 0 || mStep >= 4) return
                updateStep(4)
            }
            5, 6, 7, 8 -> {
                if (mStep == 0 || mStep != step - 1) return
                updateStep(step)
            }
        }
    }

    private fun updateStep(step: Int) {
        val str = when (step) {
            4 -> getString(R.string.action_confirm_shut_down)
            5 -> getString(R.string.action_confirm_lock)
            6 -> getString(R.string.action_confirm_power_isolation)
            7 -> getString(R.string.action_confirm_check_before_unlocking)
            8 -> getString(R.string.action_confirm_restore)
            else -> ""
        }
        mTipDialog.setTip(str)
        mTipDialog.setConfirmListener {
            if (step == 4) {
                presenter?.updateStep(mStepList[2].stepDetail?.stepId!!, "1") {
                    presenter?.updateStep(mStepList[3].stepDetail?.stepId!!, "1") {
                        refreshPage(mChangePage!!)
                        // 自动跳转
                        changePage(PageChangeBO(2, mChangePage?.workstationId, mChangePage?.ticketId,
                            mChangePage?.machineryId, mChangePage?.machineryName))
                    }
                }
            } else {
                presenter?.updateStep(mStepList.find { it.index == step }?.stepDetail?.stepId!!, "1") {
                    refreshPage(mChangePage!!)
                    if (step == 6 || step == 7) {
                        // 自动跳转
                        changePage(PageChangeBO(2, mChangePage?.workstationId, mChangePage?.ticketId,
                            mChangePage?.machineryId, mChangePage?.machineryName))
                    }
                }
            }
        }
        mTipDialog.show()
    }

    override fun onPause() {
        super.onPause()
        mStep = 0
    }

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

    data class StepBO(val pic: Int, val title: String, val index: Int, val indexStr: String, var stepDetail: StepDetailRespVO? = null)
}