package com.pan_american.android.ui.resource_management.airplane_three_code

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.FragmentAirplaneThreeCodeSearchBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class AirplaneThreeCodeSearchFragment : BaseFragment<FragmentAirplaneThreeCodeSearchBinding>() {

    private var selectorItems = ArrayList<Selector>()

    private var listInit = false

    private var inStack = false

    //当前界面的数据保存
    private var airplaneCity = ""

    private var threeCode = ""

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

    override fun onStart() {
        super.onStart()

        initAreaSelector()
        initViews()
        if (listInit) {
            initEvents()
        }
    }

    override fun onStop() {
        super.onStop()

        //保存当前界面的数据
        airplaneCity = binding.airplaneCity.text.toString()
        threeCode = binding.threeCode.text.toString()
        inStack = true

    }

    override fun initViews() {
        if (inStack) {
            binding.airplaneCity.text = airplaneCity
            binding.threeCode.setText(threeCode)

            inStack = false
        } else {
            binding.airplaneCity.text = resources.getString(R.string.all)
        }
    }

    override fun initEvents() {
        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("airplane_city", binding.airplaneCity.text.toString())
                putString("three_code", binding.threeCode.text.toString())
            }

            val airplaneThreeCodeListFragment = AirplaneThreeCodeListFragment()
            airplaneThreeCodeListFragment.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)
                .replace(R.id.airplane_three_code_container, airplaneThreeCodeListFragment).commit()
        }

        binding.airplaneCity.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)

                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.city

                            if (binding.airplaneCity.text == data.city) {
                                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.airplaneCity.text = city

                                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.city.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)
            }
        }
    }

    private fun initAreaSelector() {

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

        if (!listInit) {
            val apiService = ServiceCreator.create<APIService>()
            apiService.getAirplaneSelect().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)
                            }
                            listInit = true

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

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