package xn.hxp.ui.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import xn.hxp.app.ChemicalApp
import xn.hxp.R
import xn.hxp.databinding.FragmentInventoryIedgerBinding
import xn.hxp.ui.adapter.CabinetDoorAdapter
import xn.hxp.ui.adapter.CabinetDoorRighAdapter
import xn.hxp.ui.adapter.CustomSpinnerTwoAdapter
import xn.hxp.ui.adapter.InventoryAdapter
import xn.hxp.weidith.ChemicalTypeDialog
import xn.hxp.weidith.StorageDialog
import com.blankj.utilcode.util.LogUtils
import com.rc.core.ui.fragment.BaseFragment
import com.rc.httpcore.bean.ChemicalTypeBean
import com.rc.httpcore.bean.LockVoListBean
import com.rc.httpcore.client.ApiRepository


/**
 * 库存台账
 */
class InventoryIedgerFragment : BaseFragment() {

    private val mAdapter by lazy { InventoryAdapter(requireActivity()) }
    private var mCabinetId: String? = null
    private var mCabinetName: String? = null
    private var mDoorId: String? = null
    private var mDoorName: String? = null
    private var mNumberMonths: String? = null   //1：近一月 3：近三月
    private var mChemicalCategory: String? = null
    private var mChemicalLevel: String? = null
    private var mCabinetLockVoList: List<LockVoListBean>? = null  //柜锁会又多个
    private var mLockStr = ArrayList<String>()  // 需要打开得柜锁数量
    private val mAdapterLeft by lazy { CabinetDoorAdapter(requireActivity()) }  //左边柜子
    private val mAdapterRigh by lazy { CabinetDoorRighAdapter(requireActivity()) }  //右边柜子
    private val sPrintDate: MutableList<String> = mutableListOf()  //级别  管控or非管控
    private val sOutbound: MutableList<String> = mutableListOf()  //出库方式  1.在库，2.空瓶出库 3.废弃出库 4.整瓶领用
    private var mStatus: String? = null   //出库方式 null 1.在库，2.空瓶出库 3.废弃出库 4.整瓶领用
    private var mPages = 1  //总页码
    private var mDataPage = -1  //返回得总条数
    private var page = 1
    private var pageSize = 10

    companion object {
        fun newInstance(): InventoryIedgerFragment {
            return InventoryIedgerFragment()
        }
    }

    lateinit var viewBinding: FragmentInventoryIedgerBinding
    override fun setViewBinding(inflater: LayoutInflater, container: ViewGroup?): ViewBinding {
        viewBinding = FragmentInventoryIedgerBinding.inflate(inflater, container, false)
        return viewBinding
    }

    override fun onInit() {

        viewBinding.rvView?.layoutManager = LinearLayoutManager(requireActivity())
        viewBinding.rvView?.adapter = mAdapter
        //获取列表信息
        getLists()

        viewBinding.radioOne.setOnClickListener {
            //全部
            mNumberMonths = null
            viewBinding.radioTwo.isChecked = false
            viewBinding.radioThree.isChecked = false
        }
        viewBinding.radioTwo.setOnClickListener {
            //近一个月
            mNumberMonths = "1"
            viewBinding.radioOne.isChecked = false
            viewBinding.radioThree.isChecked = false
        }
        viewBinding.radioThree.setOnClickListener {
            //近三个月
            mNumberMonths = "3"
            viewBinding.radioOne.isChecked = false
            viewBinding.radioTwo.isChecked = false
        }

        //化学品柜 查询
        viewBinding.relCabinet.setOnClickListener {
            getCabinet(1)
        }

        //类别
        viewBinding.chemType.setOnClickListener {
            showLoading("查询中...")
            val disposable = ApiRepository.getOptions("chemicals_category")
                .subscribe({ data ->
                    dismissLoading()
                    val chemDialog = ChemicalTypeDialog(
                        requireActivity(),
                        data.toMutableList(),
                        object : ChemicalTypeDialog.IonClickListener {
                            override fun onClick(data: ChemicalTypeBean) {
                                viewBinding.chemType.text = "${data.label}"
                                viewBinding.chemType.tag = "${data.value}"
                                mChemicalCategory = "${data.value}"
                            }
                        })
                    if (!chemDialog.isShowing) {
                        chemDialog.show()
                    }
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)

                })
            addDisposable(disposable)
        }

        sPrintDate.add("级别")
        sPrintDate.add("管控")
        sPrintDate.add("非管控")
        val sPinner = viewBinding.sPinner
        val customAdapter = CustomSpinnerTwoAdapter(requireActivity(), sPrintDate!!)
        sPinner.adapter = customAdapter
        sPinner.setSelection(0)
        sPinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                // 当用户选择某一项时被调用
                LogUtils.i("=======当前选择下标 ${sPrintDate!![position]}")
                LogUtils.i("=======当前选择下标 $position")
                when (position) {
                    0 -> {
                        mChemicalLevel = null
                    }

                    1 -> {
                        mChemicalLevel = "1"
                    }

                    2 -> {
                        mChemicalLevel = "2"
                    }
                }

                // 在这里可以使用 selectedPosition 来执行相应的操作
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有任何项被选择时被调用
                LogUtils.i("=======DUOC")
            }
        }


        //1.在库，2.空瓶出库 3.废弃出库 4.整瓶领用
        sOutbound.add("出库方式")
        sOutbound.add("在库")
        sOutbound.add("空瓶出库")
        sOutbound.add("废弃出库")
        sOutbound.add("整瓶领用")
        val outbound = viewBinding.outbound
        val customAdapterOutbound = CustomSpinnerTwoAdapter(requireActivity(), sOutbound!!)
        outbound.adapter = customAdapterOutbound
        outbound.setSelection(0)
        outbound.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                // 当用户选择某一项时被调用

                when (position) {
                    0 -> {
                        mStatus = null
                    }

                    1 -> {
                        mStatus = "1"
                    }

                    2 -> {
                        mStatus = "2"
                    }

                    3 -> {
                        mStatus = "3"
                    }

                    4 -> {
                        mStatus = "4"
                    }
                }

                // 在这里可以使用 selectedPosition 来执行相应的操作
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有任何项被选择时被调用
                LogUtils.i("=======DUOC")
            }
        }


        //搜索
        viewBinding.reQuy.setOnClickListener {
            page = 1
            getLists()
        }

        viewBinding.butUpper.setOnClickListener {
            //上一页
            if (mDataPage != 0) {
                if (page != 1) {
                    page--
                    getLists()
                }
            }
        }

        viewBinding.butNext.setOnClickListener {
            //下一页
            if (mDataPage != 0) {
                if (mDataPage != page) {
                    page++
                    getLists()
                }
            }
        }
    }


    private fun getLists() {
        showLoading("查询中...")
        val map = mutableMapOf<String, Any>()
        map["subId"] = "${ChemicalApp.subjectId}"
        if (mNumberMonths != null) {
            map["numberMonths"] = mNumberMonths!!   //月份 1：近一月 3：近三月  全部 不传
        }
        if (mChemicalCategory != null) {
            map["chemicalCategory"] = mChemicalCategory!!  //化学品类别
        }
        if (mChemicalLevel != null) {
            map["chemicalLevel"] = mChemicalLevel!!   //级别，1是管控，2是非管控
        }
        if (mCabinetId != null) {
            map["cabinetId"] = mCabinetId!!
        }
        if (mDoorId != null) {
            map["doorId"] = mDoorId!!          //柜门id
        }
        val searchValue = viewBinding.edCont.text.toString().trim()
        if (searchValue.isNotEmpty()) {
            map["searchValue"] = searchValue!!     //搜索内容
        }
        if (mStatus != null) {
            map["status"] = mStatus!!
        }
        map["sortAttribute"] = "aioSort"
        map["page"] = "$page"
        map["pageSize"] = "$pageSize"
        val disposable =
            ApiRepository.stockLedger(map)
                .subscribe({ data ->
                    dismissLoading()
                    viewBinding.total.text = "入库数：${data.total}"
                    mDataPage = data.pages  //总页
                    if (mAdapter.data != null) {
                        mAdapter.data.clear()
                        mAdapter.notifyDataSetChanged()
                        initPagesView(data.pages)
                    }
                    if (data.pages != 0) {
                        if (data.pages > 1 && data.current > 1) {
                            //当前需要更新页码
                            upPagesView(data.pages, data.current)
                            mAdapter.setList(data.records.toMutableList())
                        } else {
                            mAdapter.setNewInstance(data.records.toMutableList())
                            initPagesView(data.pages)
                        }
                    }
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)

                })
        addDisposable(disposable)
    }

    /**
     * 总页码 当前页  初始化
     */
    private fun initPagesView(pages: Int) {
        mPages = pages
        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
        viewBinding.one.setTextColor(ContextCompat.getColor(requireActivity(), R.color.white))
        viewBinding.two.setTextColor(ContextCompat.getColor(requireActivity(), R.color.black))

        when (pages) {
            1 -> {
                viewBinding.one.visibility = View.VISIBLE
            }

            2 -> {
                viewBinding.two.visibility = View.VISIBLE
            }

            3 -> {
                viewBinding.two.visibility = View.VISIBLE
                viewBinding.three.visibility = View.VISIBLE
            }

            else -> {
                viewBinding.two.visibility = View.VISIBLE
                viewBinding.three.visibility = View.VISIBLE
                viewBinding.drop.visibility = View.VISIBLE
                viewBinding.many.visibility = View.VISIBLE
                viewBinding.many.text = "$pages"
            }
        }
        if (pages == 1 || pages == 0) {
            viewBinding.two.visibility = View.GONE
            viewBinding.three.visibility = View.GONE
            viewBinding.many.visibility = View.GONE
            viewBinding.drop.visibility = View.GONE
        }
        if (pages < 4) {
            when (pages) {
                1 -> {
                    viewBinding.two.visibility = View.GONE
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                2 -> {
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                3 -> {
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }
            }
        }
    }

    //更新页码
    private fun upPagesView(pages: Int, current: Int) {
        LogUtils.i("======2")
        if (pages < 4) {
//            viewBinding.one.visibility = View.VISIBLE
            when (pages) {
                1 -> {
                    viewBinding.two.visibility = View.GONE
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                2 -> {
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                3 -> {
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }
            }
            when (current) {
                1 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.white
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                2 -> {
//                    viewBinding.two.visibility = View.VISIBLE
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.white
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                3 -> {
//                    viewBinding.three.visibility = View.VISIBLE
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.white
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                }
            }
        } else {
//            viewBinding.many.visibility = View.VISIBLE
            viewBinding.three.text = "3"
            when (current) {
                1 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.white
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                2 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.white
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                3 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            requireActivity(),
                            R.color.white
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                }

                else -> {
                    viewBinding.three.text = "$current"
                    if (pages == current) {
                        viewBinding.three.text = "${current - 1}"

                        viewBinding.one.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.black
                            )
                        )
                        viewBinding.two.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.black
                            )
                        )
                        viewBinding.three.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.black
                            )
                        )
                        viewBinding.many.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.white
                            )
                        )
                        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.many.setBackgroundResource(R.drawable.bg_sou_suo_page)

                    } else {
                        viewBinding.one.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.black
                            )
                        )
                        viewBinding.two.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.black
                            )
                        )
                        viewBinding.three.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.white
                            )
                        )
                        viewBinding.many.setTextColor(
                            ContextCompat.getColor(
                                requireActivity(),
                                R.color.black
                            )
                        )

                        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                        viewBinding.many.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    }
                }
            }
        }
    }

    //查询柜子  存储位置  默认第一个
    private fun getCabinet(tag: Int) {
        showLoading("查询中...")
        val disposable = ApiRepository.getCabinetList(ChemicalApp.subjectId!!)
            .subscribe({ data ->
                dismissLoading()
                if (tag == 0) {
                    mAdapterLeft.setNewInstance(data.toMutableList())
                    mAdapterRigh.setNewInstance(data[0].cabinetDoorVoList.toMutableList())
                } else {
                    val storageDialog =
                        StorageDialog(ct = requireActivity(),
                            listData = data!!,
                            lint = object : StorageDialog.IonClickListener {
                                override fun onClick(
                                    cabinetId: String,
                                    cabinetName: String,
                                    doorName: String,
                                    doorId: String,
                                    cabinetLockVoList: List<LockVoListBean>,
                                    layers: Int,
                                    lockNum: String,
                                ) {
                                    mCabinetId = cabinetId
                                    mCabinetName = cabinetName
                                    mDoorId = doorId
                                    mDoorName = doorName
                                    viewBinding.cabinetName.text = "$cabinetName"
                                }

                                override fun onClose() {
                                    if (mCabinetId != null) {
                                        mCabinetId = null
                                        mDoorId = null
                                        viewBinding.cabinetName.text = "化学品柜"
                                    }
                                }
                            })
                    if (!requireActivity().isFinishing && !requireActivity().isDestroyed) {
                        storageDialog.show()
                    }
                }

            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }

}