package com.example.chemical.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 com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.databinding.FragmentQueryOneBinding
import com.example.chemical.ui.adapter.CustomSpinnerTwoAdapter
import com.example.chemical.ui.adapter.InquiryItemAdapter
import com.example.chemical.ui.inquiry.InquiryActivity
import com.example.chemical.weidith.ChemicalTypeDialog
import com.example.chemical.weidith.EdContThDialog
import com.example.chemical.weidith.EdContTwoDialog
import com.rc.core.log.RcLog
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.bean.ChemicalTypeBean
import com.rc.httpcore.bean.HxpStockWaitListBean
import com.rc.httpcore.client.ApiRepository


class QueryOneFragment : RcBaseFragment<FragmentQueryOneBinding>() {

    // 创建一个空的可变 Map 对象   进行初始查询
    private val mAdapterUse by lazy { InquiryItemAdapter() }  //化学品信息
    private var mChemicalCategory: String? = null  //类别
    private var mChemicalLevel: String? = null     //级别
    private var mPages = 1  //总页码
    private var mDataPage = -1  //返回得总条数
    private var page = 1
    private var pageSize = 10
    private var mCabinetId: String? = null
    private var mDoorId: String? = null
    private val sPrinDate: MutableList<String> = mutableListOf()
    companion object {
        fun newInstance(): QueryOneFragment {
            return QueryOneFragment()
        }
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentQueryOneBinding {
        return FragmentQueryOneBinding.inflate(inflater, container, false)
    }

    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.rvUse?.layoutManager = LinearLayoutManager(requireActivity())
        viewBinding.rvUse?.adapter = mAdapterUse
        val sPinner = viewBinding.spLev
        getUseList()
        //类别
        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) {
//                                showToast("${data.label}  ${data.itemId}")
                                viewBinding.chemType.text = "${data.label}"
//                                viewBinding.chemType.tag = "${data.value}"
                                mChemicalCategory = data.value
                            }
                        })
                    if (!requireActivity().isFinishing && !requireActivity().isDestroyed) {
                        if (!chemDialog.isShowing) {
                            chemDialog.show()
                        }
                    }
                }, { throwable ->
                    dismissLoading()
                    showNetError(throwable)

                })
            addDisposable(disposable)
        }
        sPrinDate.add("级别")
        sPrinDate.add("管控")
        sPrinDate.add("非管控")

        val customAdapter = CustomSpinnerTwoAdapter(requireActivity(), sPrinDate!!)
        sPinner.adapter = customAdapter
        sPinner.setSelection(0)
        sPinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                // 当用户选择某一项时被调用
                RcLog.info("=======当前选择下标 ${sPrinDate!![position]}")
                mChemicalLevel = when (position) {
                    1 -> {
                        //管控
                        "$position"
                    }
                    2 -> {
                        //非管控
                        "$position"
                    }
                    else -> {
                        null
                    }
                }
                // 在这里可以使用 selectedPosition 来执行相应的操作
            }

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

//
//        viewBinding.spLev.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
//            override fun onItemSelected(
//                parent: AdapterView<*>?,
//                view: View?,
//                position: Int,
//                id: Long
//            ) {
//                // 处理选项选择事件
////                val selectedItem = parent?.getItemAtPosition(position).toString()
//                mChemicalLevel = when (position) {
//                    1 -> {
//                        //管控
//                        "$position"
//                    }
//                    2 -> {
//                        //非管控
//                        "$position"
//                    }
//                    else -> {
//                        null
//                    }
//                }
//            }
//
//            override fun onNothingSelected(parent: AdapterView<*>?) {
//                // 处理未选择任何选项情况
//            }
//        }

        mAdapterUse.setOnItemClickListener { adapter, view, position ->
            val hxpStockWaitListBean = mAdapterUse.data[position]
            (activity as InquiryActivity).goQueryTwoFragment(
//                mAdapterUse.data[position].id!!,
                mAdapterUse.data[position].chemicalId!!,
                hxpStockWaitListBean
            )
        }
        viewBinding.re3.setOnClickListener {
            getUseList()
        }

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

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

        viewBinding.edCont.setOnClickListener {
            val edDialog = EdContThDialog(requireActivity(), object : EdContThDialog.IClickLit {
                override fun onClickClo(str: String?) {
                    if (str != null) {
                        viewBinding.edCont.text = "$str"
                    } else {
                        page = 1
                        getUseList()
                    }
                }
            })
            edDialog.show()
        }
        //列表查询  EdContDialog
        viewBinding.reQuy.setOnClickListener {
            page = 1
            getUseList()
        }

        viewBinding.resetting.setOnClickListener {
            page = 1
            mCabinetId = null
            mDoorId = null
            mChemicalCategory = null
            mChemicalLevel = null
            viewBinding.chemType.text = "类别"
            viewBinding.edCont.text = ""
            sPinner.setSelection(0)
            getUseList()
        }
    }

    // 在 Fragment 中隐藏当前 Fragment
    private fun hideCurrentFragment() {
        val transaction = requireActivity().supportFragmentManager.beginTransaction()
        transaction.hide(this)
        transaction.commit()
    }

    fun upDatas(cabinetId: String?, doorId: String?) {
        mCabinetId = cabinetId
        mDoorId = doorId
        page = 1
        pageSize = 10
        getUseList()
    }

    //获取化学品信息
    private fun getUseList() {
        showLoading("查询中...")
        val mutableMap = mutableMapOf<String, String>()
        mutableMap["subId"] = ChemicalApp.subjectId!!
        val searchValue = viewBinding.edCont.text.toString()
        if (searchValue.isNotEmpty()) {
            mutableMap["searchValue"] = searchValue
        }
        if (mChemicalCategory != null) {
            mutableMap["chemicalCategory"] = mChemicalCategory!!
        }
        if (mChemicalLevel != null) {  //级别，1是管控，2是非管控
            mutableMap["chemicalLevel"] = "$mChemicalLevel"
        }
        if (mCabinetId != null) {
            mutableMap["cabinetId"] = "$mCabinetId"
        }
        if (mDoorId != null) {
            mutableMap["doorId"] = "$mDoorId"
        }

        mutableMap["page"] = "$page"
        mutableMap["pageSize"] = "$pageSize"
        val disposable = ApiRepository.indexStockList(mutableMap)
            .subscribe({ data ->
                dismissLoading()
                mDataPage = data.pages  //总页
                if (data.records != null && data.records.size == 0) {
                    mAdapterUse.data.clear()
                    mAdapterUse.notifyDataSetChanged()
                    initPagesView(data.pages)
                }
                RcLog.info("=====一共几条$mDataPage  ${data.current}")
                if (data.pages != 0) {
                    if (data.pages > 1 && data.current > 1) {
                        //当前需要更新页码
                        upPagesView(data.pages, data.current)
                        mAdapterUse.setList(data.records.toMutableList())
                    } else {
                        mAdapterUse.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) {
        RcLog.info("======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)
                    }
                }
            }
        }
    }

    interface OnButtonClickListener {
        fun onButtonClicked()
    }

    private var buttonClickListener: OnButtonClickListener? = null

    fun setOnButtonClickListener(listener: OnButtonClickListener) {
        buttonClickListener = listener
    }
}