package com.pan_american.android.ui.customer_resource.related_invitee

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.model.customer_resource.related_invitee.network.RelatedInviteeCityDataResourceRequest
import com.pan_american.android.data.model.customer_resource.related_invitee.network.RelatedInviteeDataResourceRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentRelatedInviteeSearchBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RelatedInviteeSearchFragment : BaseFragment<FragmentRelatedInviteeSearchBinding>() {

    private val apiService = ServiceCreator.create<APIService>()

    private val countryDataRequest = RelatedInviteeDataResourceRequest()

    private val countryDataList = ArrayList<Selector>()

    private var countryId = 0

    private var countrySelected = false

    private val cityDataRequest = RelatedInviteeCityDataResourceRequest()

    private val cityDataList = ArrayList<Selector>()

    private val groupNameDataRequest = RelatedInviteeDataResourceRequest()

    private val groupNameList = ArrayList<Selector>()

    private val inviteeNameDataRequest = RelatedInviteeDataResourceRequest()

    private val inviteeNameList = ArrayList<Selector>()

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

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

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

        initEvents()
    }

    override fun initEvents() {
        binding.country.setOnClickListener {
            countryDataRequest.apply {
                pageIndex = 1
                pageSize = 12
                search = ""
            }

            countryDataList.clear()

            getCountryResource(1)
        }

        binding.area.setOnClickListener {
            if (!countrySelected) {
                showMessage(resources.getString(R.string.country_select_hint))
                return@setOnClickListener
            }

            cityDataRequest.apply {
                pageIndex = 1
                pageSize = 12
                search = ""
                countiesId = countryId
            }

            cityDataList.clear()

            getCityResource(1)
        }

        binding.groupName.setOnClickListener {
            groupNameDataRequest.apply {
                pageIndex = 1
                pageSize = 12
                search = ""
            }

            groupNameList.clear()

            getGroupNameResource(1)
        }

        binding.inviteeName.setOnClickListener {
            inviteeNameDataRequest.apply {
                pageIndex = 1
                pageSize = 12
                search = ""
            }

            inviteeNameList.clear()

            getInviteeNameResource(1)
        }

        binding.commit.setOnClickListener{

            //点击查询隐藏软键盘
            val inputMethodManager =
                requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (inputMethodManager.isActive) {
                inputMethodManager.hideSoftInputFromWindow(
                    requireActivity().window.decorView.windowToken, 0
                )
            }

            val relatedInviteeListFragment = RelatedInviteeListFragment()

            val bundle = Bundle().apply {
                putString("country", binding.country.text.toString())
                putString("city", binding.area.text.toString())
                putString("group_name", binding.groupName.text.toString())
                putString("invitee_name", binding.inviteeName.text.toString())
            }

            relatedInviteeListFragment.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.related_invitee_container, relatedInviteeListFragment).commit()
        }
    }

    private fun getCountryResource(type: Int) {
        apiService.getGroupRelatedDataSourceCountryName(countryDataRequest).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(p0: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val resourceResponse = response.body()

                if (resourceResponse != null) {
                    if (resourceResponse.code == 200) {

                        for (item in resourceResponse.data) {
                            countryDataList.add(item)
                        }

                        when(type) {
                            1 -> {

                                val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_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(true)
                                    selectorContainer.setEnableLoadMore(true)

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

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

                                                if (countryId == data.id) {
                                                    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) {
                                                countryDataList[position].apply {
                                                    binding.country.text = name

                                                    countryId = id

                                                    countrySelected = true

                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

                                    selectorContainer.setOnRefreshLoadMoreListener(object :
                                        OnRefreshLoadMoreListener {
                                        override fun onRefresh(p0: RefreshLayout) {
                                            countryDataRequest.pageIndex = 1

                                            selector.adapter!!.notifyItemRangeRemoved(0, countryDataList.size)

                                            countryDataList.clear()

                                            getCountryResource(2)
                                        }

                                        override fun onLoadMore(p0: RefreshLayout) {
                                            countryDataRequest.pageIndex += 1

                                            getCountryResource(3)
                                        }
                                    })

                                    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, countryDataList.size)

                                            countryDataList.clear()

                                            countryDataRequest.apply {
                                                pageIndex = 1
                                                search = editable.toString()
                                            }

                                            getCountryResource(2)
                                        }
                                    })

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

                                selectorContainer.setEnableLoadMore(countryDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            2 -> {
                                selectorContainer.finishRefresh()
                                selectorContainer.setEnableLoadMore(countryDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            3 -> {
                                selectorContainer.finishLoadMore()
                                selectorContainer.setEnableLoadMore(countryDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(countryDataList.size)
                            }
                        }

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

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

    private fun getCityResource(type: Int) {
        apiService.getGroupRelatedDataSourceCityName(cityDataRequest).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(p0: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val resourceResponse = response.body()

                if (resourceResponse != null) {
                    if (resourceResponse.code == 200) {

                        for (item in resourceResponse.data) {
                            cityDataList.add(item)
                        }

                        when(type) {
                            1 -> {

                                val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_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(true)
                                    selectorContainer.setEnableLoadMore(true)

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

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

                                                if (binding.area.text == data.name) {
                                                    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) {
                                                cityDataList[position].apply {
                                                    binding.area.text = name

                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

                                    selectorContainer.setOnRefreshLoadMoreListener(object :
                                        OnRefreshLoadMoreListener {
                                        override fun onRefresh(p0: RefreshLayout) {
                                            cityDataRequest.pageIndex = 1

                                            selector.adapter!!.notifyItemRangeRemoved(0, cityDataList.size)

                                            cityDataList.clear()

                                            getCityResource(2)
                                        }

                                        override fun onLoadMore(p0: RefreshLayout) {
                                            cityDataRequest.pageIndex += 1

                                            getCityResource(3)
                                        }
                                    })

                                    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, cityDataList.size)

                                            cityDataList.clear()

                                            cityDataRequest.apply {
                                                pageIndex = 1
                                                search = editable.toString()
                                            }

                                            getCityResource(2)
                                        }
                                    })

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

                                selectorContainer.setEnableLoadMore(cityDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            2 -> {
                                selectorContainer.finishRefresh()
                                selectorContainer.setEnableLoadMore(cityDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            3 -> {
                                selectorContainer.finishLoadMore()
                                selectorContainer.setEnableLoadMore(cityDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(cityDataList.size)
                            }
                        }

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

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

    private fun getGroupNameResource(type: Int) {
        apiService.getGroupRelatedDataSourceGroupName(groupNameDataRequest).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(p0: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val resourceResponse = response.body()

                if (resourceResponse != null) {
                    if (resourceResponse.code == 200) {

                        for (item in resourceResponse.data) {
                            groupNameList.add(item)
                        }

                        when(type) {
                            1 -> {

                                val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_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(true)
                                    selectorContainer.setEnableLoadMore(true)

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

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

                                                if (binding.groupName.text == data.name) {
                                                    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) {
                                                groupNameList[position].apply {
                                                    binding.groupName.text = name

                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

                                    selectorContainer.setOnRefreshLoadMoreListener(object :
                                        OnRefreshLoadMoreListener {
                                        override fun onRefresh(p0: RefreshLayout) {
                                            groupNameDataRequest.pageIndex = 1

                                            selector.adapter!!.notifyItemRangeRemoved(0, groupNameList.size)

                                            groupNameList.clear()

                                            getGroupNameResource(2)
                                        }

                                        override fun onLoadMore(p0: RefreshLayout) {
                                            groupNameDataRequest.pageIndex += 1

                                            getGroupNameResource(3)
                                        }
                                    })

                                    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, groupNameList.size)

                                            groupNameList.clear()

                                            groupNameDataRequest.apply {
                                                pageIndex = 1
                                                search = editable.toString()
                                            }

                                            getGroupNameResource(2)
                                        }
                                    })

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

                                selectorContainer.setEnableLoadMore(groupNameDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            2 -> {
                                selectorContainer.finishRefresh()
                                selectorContainer.setEnableLoadMore(groupNameDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            3 -> {
                                selectorContainer.finishLoadMore()
                                selectorContainer.setEnableLoadMore(groupNameDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(groupNameList.size)
                            }
                        }

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

            override fun onFailure(p0: Call<SelectorResponse>, p1: Throwable) {
                showErrorInfo(R.string.group_name_list_get_failed)
            }
        })
    }

    private fun getInviteeNameResource(type: Int) {
        apiService.getGroupRelatedDataSourceInviteeName(inviteeNameDataRequest).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(p0: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val resourceResponse = response.body()

                if (resourceResponse != null) {
                    if (resourceResponse.code == 200) {

                        for (item in resourceResponse.data) {
                            inviteeNameList.add(item)
                        }

                        when(type) {
                            1 -> {

                                val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_selector, null)
                                popupWindow = PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.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(true)
                                    selectorContainer.setEnableLoadMore(true)

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

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

                                                if (binding.inviteeName.text == data.unitName) {
                                                    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) {
                                                inviteeNameList[position].apply {
                                                    binding.inviteeName.text = name

                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

                                    selectorContainer.setOnRefreshLoadMoreListener(object :
                                        OnRefreshLoadMoreListener {
                                        override fun onRefresh(p0: RefreshLayout) {
                                            inviteeNameDataRequest.pageIndex = 1

                                            selector.adapter!!.notifyItemRangeRemoved(0, inviteeNameList.size)

                                            inviteeNameList.clear()

                                            getInviteeNameResource(2)
                                        }

                                        override fun onLoadMore(p0: RefreshLayout) {
                                            inviteeNameDataRequest.pageIndex += 1

                                            getInviteeNameResource(3)
                                        }
                                    })

                                    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, inviteeNameList.size)

                                            inviteeNameList.clear()

                                            inviteeNameDataRequest.apply {
                                                pageIndex = 1
                                                search = editable.toString()
                                            }

                                            getInviteeNameResource(2)
                                        }
                                    })

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

                                selectorContainer.setEnableLoadMore(inviteeNameDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            2 -> {
                                selectorContainer.finishRefresh()
                                selectorContainer.setEnableLoadMore(inviteeNameDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(0)
                            }

                            3 -> {
                                selectorContainer.finishLoadMore()
                                selectorContainer.setEnableLoadMore(inviteeNameDataRequest.pageIndex < getTotalPage(resourceResponse.count))
                                selector.adapter!!.notifyItemInserted(inviteeNameList.size)
                            }
                        }

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

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

    private fun getTotalPage(count: Int): Int {
        var pageCount = count / 10

        if (count % 10 > 0) {
            pageCount += 1
        }

        return pageCount
    }
}