package com.pan_american.android.ui.group_invite_official.invite_data

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.group_invite_official.invite_data.network.InviteDataResourceRequest
import com.pan_american.android.data.model.group_invite_official.invite_data.network.InviteDataResourceResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentInviteDataSearchBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class InviteDataSearchFragment : BaseFragment<FragmentInviteDataSearchBinding>() {

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

    private var countryData = ArrayList<String>()

    private var inviterData = ArrayList<String>()

    private var domainData = ArrayList<String>()

    private var contactData = ArrayList<String>()

    private var groupNameData = ArrayList<Selector>()

    private var userNameData = ArrayList<Selector>()

    private var groupId = 0

    private var createUserId = 0

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

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

        getInviteDataResource()

    }

    override fun initEvents() {
        binding.inviteCountry.setOnClickListener {
            val selectorList = ArrayList<String>()

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

            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(false)
                selectorContainer.setEnableLoadMore(false)

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

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

                            if (binding.inviteCountry.text == data) {
                                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<String> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.inviteCountry.text = this

                                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 countryData) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until countryData.size) {
                                countryData[i].apply {
                                    if (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.inviteeName.setOnClickListener {
            val selectorList = ArrayList<String>()

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

            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(false)
                selectorContainer.setEnableLoadMore(false)

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

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

                            if (binding.inviteeName.text == data) {
                                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<String> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.inviteeName.text = this

                                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 inviterData) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until inviterData.size) {
                                inviterData[i].apply {
                                    if (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.contractName.setOnClickListener {
            val selectorList = ArrayList<String>()

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

            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(false)
                selectorContainer.setEnableLoadMore(false)

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

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

                            if (binding.contractName.text == data) {
                                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<String> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.contractName.text = this

                                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 contactData) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until contactData.size) {
                                contactData[i].apply {
                                    if (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.groupName.setOnClickListener {
            val selectorList = ArrayList<Selector>()

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

            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(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.teamName

                            if (groupId == 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) {
                            selectorList[position].apply {
                                binding.groupName.text = teamName

                                groupId = id

                                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 groupNameData) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until groupNameData.size) {
                                groupNameData[i].apply {
                                    if (teamName.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.createUser.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(userNameData)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.cnName

                            if (createUserId == 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) {
                        userNameData[position].apply {
                            binding.createUser.text = cnName
                            createUserId = id
                        }

                        popupWindow.dismiss()
                    }
                }
            }
        }

        binding.industry.setOnClickListener {
            val selectorList = ArrayList<String>()

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

            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(false)
                selectorContainer.setEnableLoadMore(false)

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

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

                            if (binding.industry.text == data) {
                                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<String> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {
                                binding.industry.text = this

                                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 domainData) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until domainData.size) {
                                domainData[i].apply {
                                    if (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.inviteStartTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.start_time_select_hint), binding.inviteStartTime)
        }

        binding.inviteEndTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.end_time_select_hint), binding.inviteEndTime)
        }

        binding.commit.setOnClickListener {

            val inviteDataListFragment = InviteDataListFragment()

            val bundle = Bundle().apply {
                putString("country", if (binding.inviteCountry.text.equals(resources.getString(R.string.all))) {
                    ""
                } else {
                    binding.inviteCountry.text.toString()
                })
                putString("unitName", if (binding.inviteeName.text.equals(resources.getString(R.string.all))) {
                    ""
                } else {
                    binding.inviteeName.text.toString()
                })
                putString("contact", if (binding.contractName.text.equals(resources.getString(R.string.all))) {
                    ""
                } else {
                    binding.contractName.text.toString()
                })
                putString("delegation", if (groupId == 0) {
                    "0"
                } else {
                    groupId.toString()
                })
                putString("field", if (binding.industry.text.equals(resources.getString(R.string.all))) {
                    ""
                } else {
                    binding.industry.text.toString()
                })
                putInt("createUserId", createUserId)
                putString("startCreateTime", binding.inviteStartTime.text.toString())
                putString("endCreateTime", binding.inviteEndTime.text.toString())
            }

            inviteDataListFragment.arguments = bundle

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

            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.invite_data_fragment_container, inviteDataListFragment).commit()
        }
    }

    private fun getInviteDataResource() {

        if (!isAdded) {
            return
        }

        apiService.getInviteDataResource(InviteDataResourceRequest()).enqueue(object : Callback<InviteDataResourceResponse> {
            override fun onResponse(
                call: Call<InviteDataResourceResponse>,
                response: Response<InviteDataResourceResponse>
            ) {
                val resourceResponse = response.body()

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

                        countryData.add(resources.getString(R.string.all))

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

                        inviterData.add(resources.getString(R.string.all))

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

                        domainData.add(resources.getString(R.string.all))

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

                        contactData.add(resources.getString(R.string.all))

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

                        groupNameData.add(Selector().apply {
                            id = 0
                            teamName = resources.getString(R.string.all)
                        })

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

                        userNameData.add(Selector().apply {
                            id = 0
                            cnName = resources.getString(R.string.all)
                        })

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

                        initEvents()
                    }
                }
            }

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