package com.grkj.iscs_mc.view.fragment

import com.bumptech.glide.Glide
import com.grkj.iscs_mc.R
import com.grkj.iscs_mc.databinding.FragmentMaterialManualReplacementBinding
import com.grkj.iscs_mc.extentions.navigateUp
import com.grkj.iscs_mc.model.vo.material.MaterialPropertyValuePageRespVO
import com.grkj.iscs_mc.model.vo.material.MaterialTypePageRespVO
import com.grkj.iscs_mc.model.vo.replacement.ManualReplacementListRespVO
import com.grkj.iscs_mc.view.base.BaseMvpFragment
import com.grkj.iscs_mc.view.dialog.TipDialog
import com.grkj.iscs_mc.view.iview.IMaterialManualReplacementView
import com.grkj.iscs_mc.view.presenter.MaterialManualReplacementPresenter
import com.grkj.iscs_mc.view.widget.ExpandableTabLayout
import com.grkj.iscs_mc.view.widget.SelectableInput
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder

/**
 * 物资更换手动操作页
 */
class MaterialManualReplacementFragment :
    BaseMvpFragment<IMaterialManualReplacementView, MaterialManualReplacementPresenter, FragmentMaterialManualReplacementBinding>() {

    private val mMaterialList = mutableListOf<ManualReplacementListRespVO>()
    private val mDetailList = mutableListOf<ManualReplacementListRespVO.MaterialsPageVO>()
    private val mTypeList = mutableListOf<MaterialTypePageRespVO.Record>()
    private val mPropertyList = mutableListOf<MaterialPropertyValuePageRespVO.Record>()

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

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

        mBinding?.rvReplacement?.adapter =
            object : CommonAdapter<ManualReplacementListRespVO.MaterialsPageVO>(
                requireContext(),
                R.layout.item_rv_manual_replacement,
                mDetailList
            ) {
                override fun convert(
                    holder: ViewHolder,
                    vo: ManualReplacementListRespVO.MaterialsPageVO,
                    position: Int
                ) {
                    // 旧
                    holder.getView<SelectableInput>(R.id.ci_name_old).setText(vo.materialsName)
                    holder.getView<SelectableInput>(R.id.ci_type_old)
                        .setText(mTypeList.find { it.materialsTypeId == vo.materialsTypeId }?.materialsTypeName)
                    holder.getView<SelectableInput>(R.id.ci_model_old)
                        .setText(mPropertyList.find { it.recordId.toString() == vo.propertiesValueId }?.valueName)
                    holder.getView<SelectableInput>(R.id.ci_rfid_old).setText(vo.materialsRfid)
                    holder.getView<SelectableInput>(R.id.ci_date_old).setText(vo.expirationDate)
                    Glide.with(this@MaterialManualReplacementFragment).load(vo.materialsTypePicture)
                        .into(holder.getView(R.id.iv_old))

                    // 新
                    val ciName = holder.getView<SelectableInput>(R.id.ci_name_new)
                    ciName.setEnableStatus(!vo.isDone)
                    ciName.setText(vo.newName)
                    ciName.setOnTextChangeListener(object : SelectableInput.OnTextChangeListener {
                        override fun onTextChange(str: String?) {
                            vo.newName = str
                            presenter?.syncData(mMaterialList, vo)
                        }
                    })

                    // 类型
                    val ciType = holder.getView<SelectableInput>(R.id.ci_type_new)
                    ciType.setEnableStatus(!vo.isDone)
                    ciType.setOptionList(mTypeList.map { it.materialsTypeName!! }.toMutableList())
                    ciType.setText(mTypeList.find { it.materialsTypeId == vo.selectedTypeId }?.materialsTypeName)
                    ciType.setOnSpinnerSelectListener(object :
                        SelectableInput.OnSpinnerSelectListener {
                        override fun onSelect(str: String?, index: Int) {
                            if (vo.selectedTypeId != mTypeList[index].materialsTypeId) {
                                vo.selectedModelId = null
                            }
                            vo.selectedTypeId = mTypeList[index].materialsTypeId
                            mBinding?.rvReplacement?.adapter?.notifyItemChanged(position)
                            presenter?.syncData(mMaterialList, vo)
                        }
                    })

                    // 型号
                    val ciModel = holder.getView<SelectableInput>(R.id.ci_model_new)
                    ciModel.setEnableStatus(!vo.isDone)
                    ciModel.setOptionList(mPropertyList
                        .filter {
                            it.propertyId.toString() ==
                                    mTypeList.find { it.materialsTypeId == vo.selectedTypeId }?.propertyIds
                        }
                        .map { it.valueName!! }
                        .toMutableList())
                    ciModel.setText(mPropertyList.find { it.recordId == vo.selectedModelId }?.valueName)
                    ciModel.setOnSpinnerSelectListener(object :
                        SelectableInput.OnSpinnerSelectListener {
                        override fun onSelect(str: String?, index: Int) {
                            vo.selectedModelId = mPropertyList[index].recordId
                            presenter?.syncData(mMaterialList, vo)
                        }
                    })

                    val ciRfid = holder.getView<SelectableInput>(R.id.ci_rfid_new)
                    ciRfid.setEnableStatus(!vo.isDone)
                    ciRfid.setText(vo.newRfid)
                    ciRfid.setOnTextChangeListener(object : SelectableInput.OnTextChangeListener {
                        override fun onTextChange(str: String?) {
                            vo.newRfid = str
                            presenter?.syncData(mMaterialList, vo)
                        }
                    })

                    val ciDate = holder.getView<SelectableInput>(R.id.ci_date_new)
                    ciDate.setEnableStatus(!vo.isDone)
                    ciDate.setText(vo.newDate)
                    ciDate.setOnTextChangeListener(object : SelectableInput.OnTextChangeListener {
                        override fun onTextChange(str: String?) {
                            vo.newDate = str
                            presenter?.syncData(mMaterialList, vo)
                        }
                    })

                    Glide.with(this@MaterialManualReplacementFragment)
                        .load(mTypeList.find { it.materialsTypeId == vo.selectedTypeId }?.materialsTypePicture)
                        .into(holder.getView(R.id.iv_new))

                    // 按钮
                    holder.setVisible(R.id.tv_reset, vo.isDone)
                    holder.setOnClickListener(R.id.tv_reset) {
                        vo.isDone = false
                        mBinding?.rvReplacement?.adapter?.notifyItemChanged(position)
                        presenter?.syncData(mMaterialList, vo)
                    }

                    holder.setVisible(R.id.tv_confirm, !vo.isDone)
                    holder.setOnClickListener(R.id.tv_confirm) {
                        if (presenter?.checkData(vo) == true) {
                            vo.isDone = true
                            mBinding?.rvReplacement?.adapter?.notifyItemChanged(position)
                            presenter?.syncData(mMaterialList, vo)
                        }
                    }
                }
            }

        mBinding?.etlType?.setOnSelectListener(object : ExpandableTabLayout.OnSelectListener {
            override fun onSelect(position: Int) {
                mDetailList.clear()
                mMaterialList[position].materials?.let {
                    mDetailList.addAll(it)
                }
                mBinding?.rvReplacement?.adapter?.notifyDataSetChanged()
            }
        })

        presenter?.getManualReplacementList {
            it?.let {
                mMaterialList.addAll(it)
                mMaterialList.forEach {
                    it.materials?.forEach { itDetail ->
                        itDetail.newName = itDetail.materialsName
                        itDetail.newRfid = itDetail.materialsRfid
                        itDetail.newDate = itDetail.expirationDate
                        itDetail.selectedTypeId = itDetail.materialsTypeId
                        itDetail.selectedModelId = itDetail.propertiesValueId?.toLong()
                    }
                }
            }
            val list = mutableListOf<ExpandableTabLayout.ItemData>()
            it?.forEach { itData ->
                list.add(
                    ExpandableTabLayout.ItemData(
                        "${itData.materialsTypeName}(${itData.exNumber})",
                        iconUrl = itData.materialsTypeIcon
                    )
                )
            }
            mBinding?.etlType?.setData(list)

            mDetailList.clear()
            if (mMaterialList.isNotEmpty()) {
                mMaterialList[0].materials?.let {
                    mDetailList.addAll(it)
                }
            }
            mBinding?.rvReplacement?.adapter?.notifyDataSetChanged()
        }

        presenter?.getMaterialType {
            if (!it?.records.isNullOrEmpty()) {
                mTypeList.addAll(it?.records!!)
                mBinding?.rvReplacement?.adapter?.notifyDataSetChanged()
            }
        }

        presenter?.getMaterialProperty {
            if (!it.isNullOrEmpty()) {
                mPropertyList.addAll(it)
                mBinding?.rvReplacement?.adapter?.notifyDataSetChanged()
            }
        }

        mBinding?.cbSubmit?.setOnClickListener {
            submitConfirm()
        }
    }

    private fun submitConfirm() {
        val dialog = TipDialog(requireContext())
        dialog.setTip(getString(R.string.manual_replacement_submit_confirm_tip))
        dialog.setConfirmListener {
            presenter?.submit(mMaterialList, mPropertyList) {
                if (it) navigateUp()
            }
        }
        dialog.show()
    }

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