package com.pan_american.android.ui.personnel_module.materials_operate

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.entity.SimpleGroupInfo
import com.pan_american.android.data.model.common.network.SimpleGroupInfoRequest
import com.pan_american.android.data.model.common.network.SimpleGroupInfoResponse
import com.pan_american.android.data.model.personnel_module.materials_operate.entity.MaterialTypeData
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentMaterialHistorySearchBinding
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 MaterialHistorySearchFragment : BaseFragment<FragmentMaterialHistorySearchBinding>() {

    private var materialSearchBaseData = OASystem.materialBaseData

    private var materialTypeId = 0

    private var detailTypeIds = arrayListOf(0)

    private var groupIds = arrayListOf(0)

    private var verifyStatusIds = arrayListOf(-1)

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

    private val simpleGroupInfoRequest = SimpleGroupInfoRequest()

    private val simpleGroupInfoList = ArrayList<SimpleGroupInfo>()

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

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

        materialSearchBaseData.add(0, MaterialTypeData().apply {
            id = 0
            name = resources.getString(R.string.all)
        })

        for (item in materialSearchBaseData) {
            item.subTypeItems.add(0, MaterialTypeData.SubTypeItem().apply {
                id = 0
                sTid = item.id
                name = resources.getString(R.string.all)
            })
        }

        initViews()

        initEvents()
    }

    override fun initViews() {

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

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

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

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

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

    override fun initEvents() {
        binding.materialType.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<MaterialTypeData>().apply {
                    setData(OASystem.materialBaseData)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            if (data.id == materialTypeId) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }

                            text = data.name
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<MaterialTypeData> {
                    override fun onItemClick(position: Int) {

                        OASystem.materialBaseData[position].apply {

                            if (materialTypeId != id) {
                                materialTypeId = id

                                binding.materialType.text = name

                                detailTypeIds.clear()

                                detailTypeIds.add(0)

                                binding.detailType.text = resources.getString(R.string.all)
                            }

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }

        binding.detailType.setOnClickListener {
            val subTypeItem = ArrayList<MaterialTypeData.SubTypeItem>()

            showSelector {
                val adapter = ListAdapter.Builder<MaterialTypeData.SubTypeItem>().apply {
                    for (item in materialSearchBaseData) {
                        if (materialTypeId == item.id) {
                            subTypeItem.clear()

                            subTypeItem.addAll(item.subTypeItems)

                            setData(subTypeItem)
                        }
                    }

                    setLayoutId(R.layout.item_selector)

                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {

                            if (detailTypeIds.contains(data.id)) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }

                            text = data.name
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<MaterialTypeData.SubTypeItem> {
                    override fun onItemClick(position: Int) {

                        subTypeItem[position].apply {

                            if (id == 0) {

                                detailTypeIds.clear()

                                detailTypeIds.add(id)

                                binding.detailType.text = name

                            } else {

                                detailTypeIds.remove(0)

                                if (detailTypeIds.contains(id)) {
                                    detailTypeIds.remove(id)
                                } else {
                                    detailTypeIds.add(id)
                                }

                                var valueString = ""

                                var i = 0

                                while (i < detailTypeIds.size) {
                                    for (item in subTypeItem) {
                                        if (detailTypeIds[i] == item.id) {
                                            valueString += item.name
                                        }
                                    }

                                    i++

                                    if (i < detailTypeIds.size) {
                                        valueString += "\t\t"
                                    }
                                }

                                binding.detailType.text = valueString.trim()
                            }

                            popupWindow.dismiss()
                        }

                    }
                }
            }
        }

        binding.materialApplicationStartTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.material_application_start_time), binding.materialApplicationStartTime)
        }

        binding.materialApplicationEndTime.setOnClickListener {
            showDatePicker(resources.getString(R.string.material_application_end_time), binding.materialApplicationEndTime)
        }

        binding.associationGroup.setOnClickListener {
            simpleGroupInfoRequest.apply {
                pageIndex = 1
                pageSize = 10
                search = ""
            }

            simpleGroupInfoList.clear()

            simpleGroupInfoList.add(0, SimpleGroupInfo().apply {
                id = 0
                name = resources.getString(R.string.all)
            })

            getSimpleGroupInfoResource(1)
        }

        binding.verifyStatus.setOnClickListener {

            val verifyList = arrayListOf(
                Selector().apply {
                    id = -1
                    name = resources.getString(R.string.all)
                },
                Selector().apply {
                    id = 0
                    name = resources.getString(R.string.verify_wait) },
                Selector().apply {
                    id = 1
                    name = resources.getString(R.string.verify_passed) },
                Selector().apply {
                    id = 2
                    name = resources.getString(R.string.verify_rejected) })

            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(verifyList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            if (verifyStatusIds.contains(data.id)) {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color_blue,
                                        null
                                    )
                                )
                            } else {
                                setTextColor(
                                    ResourcesCompat.getColor(
                                        resources,
                                        R.color.text_color,
                                        null
                                    )
                                )
                            }

                            text = data.name
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                    override fun onItemClick(position: Int) {
                        verifyList[position].apply {

                            if (id == -1) {
                                verifyStatusIds.clear()

                                verifyStatusIds.add(id)

                                binding.verifyStatus.text = name



                            } else {

                                verifyStatusIds.remove(-1)

                                if (verifyStatusIds.contains(id)) {
                                    verifyStatusIds.remove(id)
                                } else {
                                    verifyStatusIds.add(id)
                                }

                                var valueString = ""

                                var i = 0

                                while (i < verifyStatusIds.size) {
                                    for (item in verifyList) {
                                        if (verifyStatusIds[i] == item.id) {
                                            valueString += item.name
                                        }
                                    }

                                    i++

                                    if (i < verifyStatusIds.size) {
                                        valueString += "\n\n"
                                    }
                                }

                                binding.verifyStatus.text = valueString.trim()
                            }

                            popupWindow.dismiss()
                        }
                    }
                }
            }
        }

        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 {
                if (detailTypeIds.contains(0)) {
                    putString("detail_type", "")
                } else {
                    putString("detail_type", detailTypeIds.toString().replace("[", "").replace("]", ""))
                }
                putString("material_name", binding.materialName.text.toString())
                putString("start_time", binding.materialApplicationStartTime.text.toString())
                putString("end_time", binding.materialApplicationEndTime.text.toString())
                if (groupIds.contains(0)) {
                    putString("group_id", "")
                } else {
                    putString("group_id", groupIds.toString().replace("[", "").replace("]", ""))

                }
                if (verifyStatusIds.contains(-1)) {
                    putString("verify_status", "")
                } else {
                    putString("verify_status", verifyStatusIds.toString().replace("[", "").replace("]", ""))
                }
            }

            val materialHistoryListFragment = MaterialHistoryListFragment()
            materialHistoryListFragment.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.material_history_container, materialHistoryListFragment)
                .commit()
        }
    }

    private fun getSimpleGroupInfoResource(type: Int) {
        apiService.getGroupNameWithSearch(simpleGroupInfoRequest).enqueue(object :
            Callback<SimpleGroupInfoResponse> {
            override fun onResponse(p0: Call<SimpleGroupInfoResponse>, response: Response<SimpleGroupInfoResponse>) {
                val resourceResponse = response.body()

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

                        for (item in resourceResponse.data) {
                            simpleGroupInfoList.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<SimpleGroupInfo>().apply {
                                        setData(simpleGroupInfoList)
                                        setLayoutId(R.layout.item_selector)
                                        addBindView { itemView, data ->
                                            itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                                                text = data.name

                                                if (groupIds.contains(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<SimpleGroupInfo> {
                                            override fun onItemClick(position: Int) {
                                                simpleGroupInfoList[position].apply {

                                                    if (id == 0) {
                                                        groupIds.clear()

                                                        groupIds.add(id)

                                                        binding.associationGroup.text = name
                                                    } else {

                                                        groupIds.remove(0)

                                                        if (groupIds.contains(id)) {
                                                            groupIds.remove(id)
                                                        } else {
                                                            groupIds.add(id)
                                                        }

                                                        var valueString = ""

                                                        var i = 0

                                                        while (i < groupIds.size) {

                                                            for (item in simpleGroupInfoList) {
                                                                if (groupIds[i] == item.id) {
                                                                    valueString += item.name
                                                                }
                                                            }

                                                            i ++

                                                            if (i < groupIds.size) {
                                                                valueString += "\n\n"
                                                            }
                                                        }

                                                        binding.associationGroup.text = valueString
                                                    }
                                                    popupWindow.dismiss()
                                                }
                                            }
                                        }

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

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

                                            simpleGroupInfoList.clear()

                                            getSimpleGroupInfoResource(2)
                                        }

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

                                            getSimpleGroupInfoResource(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, simpleGroupInfoList.size)

                                            simpleGroupInfoList.clear()

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

                                            getSimpleGroupInfoResource(2)
                                        }
                                    })

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

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

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

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

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

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

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

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

        return pageCount
    }
}