package com.grkj.iscs.view.fragment

import android.view.View
import android.widget.ImageView
import com.grkj.iscs.R
import com.grkj.iscs.databinding.FragmentWorkerBinding
import com.grkj.iscs.model.Constants.USER_ROLE_COLOCKER
import com.grkj.iscs.model.Constants.USER_ROLE_LOCKER
import com.grkj.iscs.model.bo.PageChangeBO
import com.grkj.iscs.model.vo.ticket.TicketUserReqVO
import com.grkj.iscs.model.vo.user.UserListRespVO
import com.grkj.iscs.util.SPUtils
import com.grkj.iscs.view.base.BaseMvpFragment
import com.grkj.iscs.view.iview.IWorkerView
import com.grkj.iscs.view.presenter.WorkerPresenter
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder

/**
 * 分配人员页
 */
class WorkerFragment(val goBack: () -> Unit, val changePage: (PageChangeBO) -> Unit) :
    BaseMvpFragment<IWorkerView, WorkerPresenter, FragmentWorkerBinding>() {
    private val mSelectedList = mutableListOf<TicketUserReqVO>()
    private val mColockerSelectedShowList = mutableListOf<TicketUserReqVO>()    // 仅展示用

    private val mLockerList = mutableListOf<UserListRespVO.Row>()
    private val mColockerInsideList = mutableListOf<UserListRespVO.Row>()
    private val mColockerOutsideList = mutableListOf<UserListRespVO.Row>()
    private var mPageChangeBO: PageChangeBO? = null

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

    override fun initView() {
        mBinding?.layoutLocker?.ivPhoto?.isSelected = true

        mBinding?.cbCancel?.setOnClickListener { goBack() }
        mBinding?.cbConfirm?.setOnClickListener {
            presenter?.updateTicketUser(mPageChangeBO?.ticketId!!, mSelectedList) {
                if (it) { goBack() }
            }
        }

        mBinding?.rvColockerSelected?.adapter =
            object : CommonAdapter<TicketUserReqVO>(requireActivity(), R.layout.item_rv_worker, mColockerSelectedShowList) {
                override fun convert(holder: ViewHolder, data: TicketUserReqVO, position: Int) {
                    holder.getView<ImageView>(R.id.iv_photo).isSelected = true
                    holder.setText(R.id.tv_name, data.userName)
                    holder.setOnClickListener(R.id.root) {
                        // 共锁人取消
                        mSelectedList.removeIf { it.userId == data.userId }
                        mColockerSelectedShowList.removeIf { it.userId == data.userId }
                        mBinding?.rvColockerSelected?.adapter?.notifyDataSetChanged()
                        mBinding?.rvColockerInside?.adapter?.notifyDataSetChanged()
                        mBinding?.rvColockerOutside?.adapter?.notifyDataSetChanged()
                    }
                }
            }

        mBinding?.tvLockerSelect?.setOnClickListener {
            mBinding?.llLocker?.visibility = View.VISIBLE
            mBinding?.llColockerInside?.visibility = View.GONE
            mBinding?.llColockerOutside?.visibility = View.GONE
        }

        mBinding?.tvColockerSelect?.setOnClickListener {
            mBinding?.llLocker?.visibility = View.GONE
            mBinding?.llColockerInside?.visibility = View.VISIBLE
            mBinding?.llColockerOutside?.visibility = View.VISIBLE
        }

        mBinding?.rvLockerList?.adapter =
            object : CommonAdapter<UserListRespVO.Row>(requireActivity(), R.layout.item_rv_worker, mLockerList) {
                override fun convert(holder: ViewHolder, user: UserListRespVO.Row, position: Int) {
                    holder.getView<ImageView>(R.id.iv_photo).isSelected = mSelectedList.any { it.userId == user.userId && it.userRole == USER_ROLE_LOCKER}
                    holder.setText(R.id.tv_name, user.nickName)
                    holder.setOnClickListener(R.id.root) {
                        // 上锁人选择
                        if (mSelectedList.any { it.userId == user.userId }) {
                            mSelectedList.removeIf { it.userId == user.userId }
                            mBinding?.layoutLocker?.root?.visibility = View.INVISIBLE
                        } else {
                            mSelectedList.removeIf { it.userRole == USER_ROLE_LOCKER }
                            mSelectedList.add(TicketUserReqVO(user.userId!!, user.nickName!!, "0", USER_ROLE_LOCKER))
                            mBinding?.layoutLocker?.root?.visibility = View.VISIBLE
                            mBinding?.layoutLocker?.tvName?.text = user.nickName
                        }
                        mBinding?.rvLockerList?.adapter?.notifyDataSetChanged()
                    }
                }
            }

        mBinding?.rvColockerInside?.adapter =
            object : CommonAdapter<UserListRespVO.Row>(requireActivity(), R.layout.item_rv_worker, mColockerInsideList) {
                override fun convert(holder: ViewHolder, user: UserListRespVO.Row, position: Int) {
                    holder.getView<ImageView>(R.id.iv_photo).isSelected = mSelectedList.any { it.userId == user.userId && it.userRole == USER_ROLE_COLOCKER}
                    holder.setText(R.id.tv_name, user.nickName)
                    holder.setOnClickListener(R.id.root) {
                        // 内部共锁人选择
                        if (mSelectedList.any { it.userId == user.userId }) {
                            mSelectedList.removeIf { it.userId == user.userId }
                            mColockerSelectedShowList.removeIf { it.userId == user.userId }
                        } else {
                            val addUser = TicketUserReqVO(user.userId!!, user.nickName!!, "0", USER_ROLE_COLOCKER)
                            mSelectedList.add(addUser)
                            mColockerSelectedShowList.add(addUser)
                        }
                        mBinding?.rvColockerSelected?.adapter?.notifyDataSetChanged()
                        mBinding?.rvColockerInside?.adapter?.notifyDataSetChanged()
                    }
                }
            }

        mBinding?.rvColockerOutside?.adapter =
            object : CommonAdapter<UserListRespVO.Row>(requireActivity(), R.layout.item_rv_worker, mColockerOutsideList) {
                override fun convert(holder: ViewHolder, user: UserListRespVO.Row, position: Int) {
                    holder.getView<ImageView>(R.id.iv_photo).isSelected = mSelectedList.any { it.userId == user.userId }
                    holder.setText(R.id.tv_name, user.nickName)
                    holder.setOnClickListener(R.id.root) {
                        // 外部共锁人选择
                        if (mSelectedList.any { it.userId == user.userId }) {
                            mSelectedList.removeIf { it.userId == user.userId }
                            mColockerSelectedShowList.removeIf { it.userId == user.userId }
                        } else {
                            val addUser = TicketUserReqVO(user.userId!!, user.nickName!!, "1", USER_ROLE_COLOCKER)
                            mSelectedList.add(addUser)
                            mColockerSelectedShowList.add(addUser)
                        }
                        mBinding?.rvColockerSelected?.adapter?.notifyDataSetChanged()
                        mBinding?.rvColockerOutside?.adapter?.notifyDataSetChanged()
                    }
                }
            }

        mBinding?.layoutLocker?.root?.setOnClickListener {
            if (mBinding?.layoutLocker?.root?.visibility == View.VISIBLE) {
                mBinding?.layoutLocker?.root?.visibility = View.INVISIBLE
                mSelectedList.removeIf { it.userRole == USER_ROLE_LOCKER }
                mBinding?.rvLockerList?.adapter?.notifyDataSetChanged()
            }
        }
    }

    override fun refreshPage(pageChangeBO: PageChangeBO) {
        mSelectedList.clear()
        mColockerSelectedShowList.clear()
        mLockerList.clear()
        mColockerInsideList.clear()
        mColockerOutsideList.clear()
        mBinding?.rvColockerSelected?.adapter?.notifyDataSetChanged()
        mBinding?.rvLockerList?.adapter?.notifyDataSetChanged()
        mBinding?.rvColockerInside?.adapter?.notifyDataSetChanged()
        mBinding?.rvColockerOutside?.adapter?.notifyDataSetChanged()

        mBinding?.llLocker?.visibility = View.VISIBLE
        mBinding?.llColockerInside?.visibility = View.GONE
        mBinding?.llColockerOutside?.visibility = View.GONE

        mPageChangeBO = pageChangeBO
        mBinding?.layoutLocker?.root?.visibility = View.INVISIBLE

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

            if (it?.jobTicketUserList.isNullOrEmpty()) {
                return@getTicketDetail
            }
            mSelectedList.clear()
            mColockerSelectedShowList.clear()
            it?.jobTicketUserList?.forEach { user ->
                if (user.userRole == USER_ROLE_LOCKER) {
                    mBinding?.layoutLocker?.root?.visibility = View.VISIBLE
                    mBinding?.layoutLocker?.tvName?.text = user.userName
                }
                mSelectedList.add(TicketUserReqVO(user.userId!!, user.userName!!, user.userType!!, user.userRole!!))
            }
            // 上锁人默认选择自己
            if (mSelectedList.none { it.userRole == USER_ROLE_LOCKER }) {
                val user = it?.jobTicketUserList?.find { it.userId == SPUtils.getLoginUser(requireContext())?.userId }
                user?.let {
                    mSelectedList.add(TicketUserReqVO(it.userId!!, it.userName!!, it.userType!!, USER_ROLE_LOCKER))
                    mBinding?.layoutLocker?.root?.visibility = View.VISIBLE
                    mBinding?.layoutLocker?.tvName?.text = it.userName
                }
            }
            mColockerSelectedShowList.addAll(mSelectedList.filter { it.userRole == USER_ROLE_COLOCKER }.toMutableList())
            mBinding?.rvColockerSelected?.adapter?.notifyDataSetChanged()
            mBinding?.rvLockerList?.adapter?.notifyDataSetChanged()
            mBinding?.rvColockerInside?.adapter?.notifyDataSetChanged()
            mBinding?.rvColockerOutside?.adapter?.notifyDataSetChanged()
        }

        presenter?.getUserList(mPageChangeBO?.workstationId, 3, 9) {
            mLockerList.clear()
            if (!it?.rows.isNullOrEmpty()) {
                mLockerList.addAll(it?.rows!!)
            }
            // 上锁人默认选择自己
            if (mSelectedList.none { it.userRole == USER_ROLE_LOCKER }) {
                val user = it?.rows?.find { it.userId == SPUtils.getLoginUser(requireContext())?.userId }
                user?.let {
                    mSelectedList.add(TicketUserReqVO(it.userId!!, it.nickName!!, "0", USER_ROLE_LOCKER))
                    mBinding?.layoutLocker?.root?.visibility = View.VISIBLE
                    mBinding?.layoutLocker?.tvName?.text = it.nickName
                }
            }
            mBinding?.rvLockerList?.adapter?.notifyDataSetChanged()
        }

        presenter?.getUserList(mPageChangeBO?.workstationId, 4) {
            mColockerInsideList.clear()
            mColockerOutsideList.clear()
            if (!it?.rows.isNullOrEmpty()) {
                it?.rows?.forEach { user ->
                    if (user.unitId == 9L) {
                        mColockerInsideList.add(user)
                    } else {
                        mColockerOutsideList.add(user)
                    }
                }
            }
            mBinding?.rvColockerInside?.adapter?.notifyDataSetChanged()
            mBinding?.rvColockerOutside?.adapter?.notifyDataSetChanged()
        }

        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}"
        }
    }

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