package com.pan_american.android.ui.resource_management.guide_resource

import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.network.SelectorResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentGuideResourceSearchBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class GuideResourceSearchFragment : BaseFragment<FragmentGuideResourceSearchBinding>() {

    private var selectorItems = ArrayList<Selector>()

    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?
    ) = FragmentGuideResourceSearchBinding.inflate(layoutInflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initViews()

        initAreaSelector()
    }

    override fun initViews() {

        binding.departmentLocation.text = resources.getString(R.string.all)

        binding.commit.setText(resources.getString(R.string.search))
    }

    override fun initEvents() {

        binding.departmentLocation.setOnClickListener {

            val selectorList = ArrayList<Selector>()

            for (item in selectorItems) {
                selectorList.add(item)
            }

            val popView = View.inflate(OASystem.context, R.layout.popup_selector, null)
            popupWindow = PopupWindow(popView, RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)

            showPopupWindow {

                val searchView: LinearLayout = popView.findViewById(R.id.search_view)
                searchView.visibility = View.VISIBLE

                val searchText: EditText = popView.findViewById(R.id.search_text)

                selector = popView.findViewById(R.id.selector_list)

                selectorContainer = popView.findViewById(R.id.selector_refresh_container)
                selectorContainer.setEnableRefresh(false)
                selectorContainer.setEnableLoadMore(false)

                val layoutManager = LinearLayoutManager(OASystem.context)
                selector.layoutManager = layoutManager

                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.unitArea

                            if (binding.departmentLocation.text == data.unitArea) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.departmentLocation.text = unitArea

                                popupWindow.dismiss()
                            }
                        }
                    }

                searchText.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                    }

                    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                    }

                    override fun afterTextChanged(editable: Editable?) {

                        adapter.notifyItemRangeRemoved(0, selectorList.size)

                        selectorList.clear()

                        if (editable.isNullOrBlank()) {

                            for (item in selectorItems) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until selectorItems.size) {
                                selectorItems[i].apply {
                                    if (this.unitArea.contains(editable)) {
                                        selectorList.add(this)
                                    }
                                }
                            }
                        }

                        if (selectorList.size == 0) {
                            showMessage(resources.getString(R.string.no_data))
                        } else {
                            for (i in 0 until selectorList.size) {
                                adapter.notifyItemInserted(i)
                            }
                        }
                    }
                })

                popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
            }
        }

        binding.commit.setOnClickListener {
            //点击查询隐藏软键盘
            val inputMethodManager =
                requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (inputMethodManager.isActive) {
                inputMethodManager.hideSoftInputFromWindow(
                    requireActivity().window.decorView.windowToken, 0
                )
            }
            val bundle = Bundle().apply {
                putString("supplier_location", binding.departmentLocation.text.toString())
                putString("supplier_name", binding.departmentName.text.toString())
                putString("contacts_name", binding.contactsName.text.toString())
                putString("contacts_phone", binding.contactsPhone.text.toString())
            }

            val guideResourceListFragment = GuideResourceListFragment()
            guideResourceListFragment.arguments = bundle

            parentFragmentManager.beginTransaction().setCustomAnimations(
                R.anim.slide_right_in,
                R.anim.slide_left_out,
                R.anim.slide_left_in,
                R.anim.slide_right_out
            ).addToBackStack(null)
                .add(R.id.guide_resource_container, guideResourceListFragment)
                .commit()
        }
    }

    private fun initAreaSelector() {

        ///避免Fragment not attached to a context.
        if (!isAdded) {
            return
        }

        val apiService = ServiceCreator.create<APIService>()

        apiService.getGuideSelect().enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(
                call: Call<SelectorResponse>, response: Response<SelectorResponse>
            ) {
                val areaSelectorResponse = response.body()
                if (areaSelectorResponse != null) {
                    if (areaSelectorResponse.code == 200) {
                        for (item in areaSelectorResponse.data) {
                            selectorItems.add(item)
                        }

                        initEvents()

                    } else {
                        showMessage(areaSelectorResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<SelectorResponse>, t: Throwable) {
                showErrorInfo(R.string.base_resource_data_get_failed)
            }
        })
    }
}