package com.cheng.blzb.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import androidx.fragment.app.FragmentManager
import com.cheng.blzb.R
import com.cheng.blzb.bean.SearchOptionEntity
import com.cheng.blzb.databinding.PopAboutTipBinding
import com.cheng.blzb.databinding.PopupSearchOptionsBinding
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.guide.GuideFragment
import com.cheng.blzb.ui.fragment.mine.about.AppConfigFragment
import com.cheng.blzb.ui.fragment.search.list.SearchOptionChildAdapter
import com.cheng.blzb.ui.fragment.search.list.SearchOptionParentAdapter
import com.cheng.blzb.utils.DateUtils
import com.example.base.decoration.DividerItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.getYYYYMMDD
import com.example.base.extensions.gone
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.utils.DensityUtils
import java.util.Calendar

object PopupDialog {

    fun showAboutTip(context: Context,v:View){
        val view = LayoutInflater.from(context).inflate(R.layout.pop_about_tip,null,false)
        val binding = PopAboutTipBinding.bind(view)

        binding.tvTip1.onClick {
            PublicActivity.start(context, AppConfigFragment::class.java)
        }

        binding.tvTip2.onClick {
            PublicActivity.start(context, GuideFragment::class.java)
        }

        val popWindow = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        popWindow.isClippingEnabled = false
        popWindow.isFocusable = true
        popWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        val location = IntArray(2)
        v.getLocationOnScreen(location)
        val y: Int = location[1] + v.height
        val height = context.resources.displayMetrics.heightPixels - y
        popWindow.showAsDropDown(v, 0, 0)
    }

    fun showSearchAreaOptions(context: Context, v: View, cityList: List<SearchOptionEntity.OptionItem>, onDismiss: () -> Unit, callback: (List<SearchOptionEntity.OptionItem>) -> Unit) {
        val view = LayoutInflater.from(context).inflate(R.layout.popup_search_options, null, false)
        val binding = PopupSearchOptionsBinding.bind(view)

        val parentAdapter = SearchOptionParentAdapter()
        binding.rvParent.adapter = parentAdapter

        val childAdapter = SearchOptionChildAdapter(true)
        binding.rvChild.adapter = childAdapter

        val optionList = SearchOptionEntity.getAreaOptionList()
        if (cityList.isNotEmpty()) {
            optionList[0].isChecked = false
            optionList[0].items[0].isChecked = false
            optionList.forEach { option ->
                option.items.forEach { item ->
                    if (cityList.find { it.id == item.id } != null) {
                        item.isChecked = true
                        if (optionList.find { it.isChecked } == null) {
                            option.isChecked = true
                        }
                    }
                }
                val selectedList = option.items.filter { item -> item.id != 0 }
                if (selectedList.isNotEmpty() && selectedList.all { item -> item.isChecked }) {
                    option.items[0].isChecked = true
                }
            }
        } else {
            optionList[0].isChecked = true
            optionList[0].items[0].isChecked = true
        }
        parentAdapter.setList(optionList)
        childAdapter.setList(optionList.find { it.isChecked }?.items)

        parentAdapter.setOnItemClickListener { _, _, i ->
            val item = parentAdapter.getItem(i)
            parentAdapter.data.find { it.isChecked }?.isChecked = false
            item.isChecked = true
            parentAdapter.notifyDataSetChanged()

            childAdapter.setList(item.items)
        }

        childAdapter.setOnItemClickListener { _, _, i ->
            val item = childAdapter.getItem(i)
            item.isChecked = !item.isChecked
            if (item.isChecked) {
                if (item.id == 0) {
                    childAdapter.data.forEach { it.isChecked = true }
                } else {
                    if (childAdapter.data.filter { it.id != 0 }.all { it.isChecked }) {
                        childAdapter.data[0].isChecked = true
                    }
                }
            } else {
                if (item.id == 0) {
                    childAdapter.data.forEach { it.isChecked = false }
                } else {
                    if (childAdapter.data[0].isChecked) {
                        childAdapter.data[0].isChecked = false
                    }
                }
            }

            if (parentAdapter.data[0].isChecked) {
                for (i in 1 until parentAdapter.data.size) {
                    parentAdapter.getItem(i).items.forEach {
                        it.isChecked = false
                    }
                }
            } else {
                if (parentAdapter.data[0].items[0].isChecked) {
                    parentAdapter.data[0].items[0].isChecked = false
                }
            }

            childAdapter.notifyDataSetChanged()
        }

        val popWindow = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        popWindow.isClippingEnabled = false
        popWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popWindow.setOnDismissListener {
            onDismiss.invoke()
        }

        binding.btnReset.onClick {
            val optionList = SearchOptionEntity.getAreaOptionList()
            optionList[0].isChecked = true
            parentAdapter.setList(optionList)
            childAdapter.setList(optionList[0].items)
        }

        binding.btnNext.onClick {
            val list = mutableListOf<SearchOptionEntity.OptionItem>()
            parentAdapter.data.forEachIndexed { index, option ->
                if (index != 0) {
                    list.addAll(option.items.filter { it.isChecked && it.id != 0 })
                }
            }
            if (!parentAdapter.data[0].items[0].isChecked && list.isEmpty()) {
                toast("请选择地区")
                return@onClick
            }
            callback.invoke(list)
            popWindow.dismiss()
        }

        val location = IntArray(2)
        v.getLocationOnScreen(location)
        popWindow.showAsDropDown(v, 0, 0)
    }

    @SuppressLint("NotifyDataSetChanged")
    fun showSearchTimeOptions(context: Context, v: View, manager: FragmentManager, time: SearchOptionEntity.OptionItem?, onDismiss: () -> Unit, callback: (SearchOptionEntity.OptionItem) -> Unit) {
        val view = LayoutInflater.from(context).inflate(R.layout.popup_search_options, null, false)
        val binding = PopupSearchOptionsBinding.bind(view)

        binding.rvParent.gone()
        binding.layoutCustomTime.visible()

        var startTime = 0L
        var endTime = 0L

        val adapter = SearchOptionChildAdapter(false)
        binding.rvChild.adapter = adapter
        binding.rvChild.addItemDecoration(DividerItemDecoration(DensityUtils.dp2px(16f), DensityUtils.dp2px(16f), color = getColor(R.color.color_eeeeee)))

        val optionList = SearchOptionEntity.getTimeOptionList()[0]
        if (time != null) {
            if (time.id == -1) {
                optionList.items[0].isChecked = false
            } else {
                optionList.items.forEach {
                    it.isChecked = it.id == time.id
                }
            }
            if (time.id != 0) {
                startTime = time.startTime.toLong() * 1000
                endTime = time.endTime.toLong() * 1000
                binding.tvStartTime.text = startTime.getYYYYMMDD()
                binding.tvEndTime.text = endTime.getYYYYMMDD()
            }
        }
        adapter.setList(optionList.items)

        val popWindow = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        popWindow.isClippingEnabled = false
        popWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popWindow.setOnDismissListener {
            onDismiss.invoke()
        }

        adapter.setOnItemClickListener { _, _, i ->
            val item = adapter.getItem(i)
            adapter.data.find { it.isChecked }?.isChecked = false
            item.isChecked = true
            adapter.notifyDataSetChanged()

            if (item.id == 0) {
                startTime = 0L
                endTime = 0L
                binding.tvStartTime.text = ""
                binding.tvEndTime.text = ""
            } else {
                val calendar = Calendar.getInstance()
                when(item.id) {
                    1-> calendar.add(Calendar.DATE, -2)
                    2-> calendar.add(Calendar.DATE, -6)
                    3-> calendar.add(Calendar.MONTH, -1)
                    4-> calendar.add(Calendar.MONTH, -3)
                    5-> calendar.add(Calendar.YEAR, -1)
                }
                startTime = DateUtils.getDayStartTime(calendar.timeInMillis) * 1000
                endTime = DateUtils.getDayEndTime() * 1000
                binding.tvStartTime.text = startTime.getYYYYMMDD()
                binding.tvEndTime.text = endTime.getYYYYMMDD()
            }
        }

        binding.tvStartTime.onClick {
            val f = DatePickerDialog.newInstance("开始时间")
            f.setOnSelectListener {
                startTime = DateUtils.getDayStartTime(it) * 1000
                if (endTime in 1..<startTime) {
                    toast("开始时间不能大于结束时间")
                } else {
                    binding.tvStartTime.text = it.getYYYYMMDD()
                    optionList.items.find { item -> item.isChecked }?.isChecked = false
                    adapter.notifyDataSetChanged()
                }
            }
            f.show(manager, DatePickerDialog::class.java.simpleName)
        }

        binding.tvEndTime.onClick {
            val f = DatePickerDialog.newInstance("结束时间")
            f.setOnSelectListener {
                endTime = DateUtils.getDayEndTime(it) * 1000
                if (endTime < startTime) {
                    toast("结束时间不能小于开始时间")
                } else {
                    binding.tvEndTime.text = it.getYYYYMMDD()
                    optionList.items.find { item -> item.isChecked }?.isChecked = false
                    adapter.notifyDataSetChanged()
                }
            }
            f.show(manager, DatePickerDialog::class.java.simpleName)
        }

        binding.btnReset.onClick {
            startTime = 0
            endTime = 0
            binding.tvStartTime.text = ""
            binding.tvEndTime.text = ""

            adapter.setList(SearchOptionEntity.getTimeOptionList()[0].items)
        }

        binding.btnNext.onClick {
            var option = adapter.data.find { it.isChecked }
            if (option != null) {
                option.startTime = if (option.id == 0) "" else "${startTime / 1000}"
                option.endTime = if (option.id == 0) "" else "${endTime / 1000}"
            } else {
                if (startTime == 0L) {
                    toast("请选择开始时间")
                    return@onClick
                }
                if (endTime == 0L) {
                    toast("请选择结束时间")
                    return@onClick
                }
                option = SearchOptionEntity.OptionItem(-1, startTime = "${startTime / 1000}", endTime = "${endTime / 1000}")
            }
            callback.invoke(option)
            popWindow.dismiss()
        }

        val location = IntArray(2)
        v.getLocationOnScreen(location)
        popWindow.showAsDropDown(v, 0, 0)
    }

    fun showSearchSortOptions(context: Context, v: View, sort: SearchOptionEntity.OptionItem?, onDismiss: () -> Unit, callback: (SearchOptionEntity.OptionItem) -> Unit) {
        val view = LayoutInflater.from(context).inflate(R.layout.popup_search_options, null, false)
        val binding = PopupSearchOptionsBinding.bind(view)

        binding.rvParent.gone()

        val adapter = SearchOptionChildAdapter(false)
        binding.rvChild.adapter = adapter
        binding.rvChild.addItemDecoration(DividerItemDecoration(DensityUtils.dp2px(16f), DensityUtils.dp2px(16f), color = getColor(R.color.color_eeeeee)))

        val optionList = SearchOptionEntity.getSortOptionList()[0]
        if (sort != null) {
            optionList.items.forEach {
                it.isChecked = it.id == sort.id
            }
        }
        adapter.setList(optionList.items)

        val popWindow = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        popWindow.isClippingEnabled = false
        popWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popWindow.setOnDismissListener {
            onDismiss.invoke()
        }

        adapter.setOnItemClickListener { _, _, i ->
            val item = adapter.getItem(i)
            adapter.data.find { it.isChecked }?.isChecked = false
            item.isChecked = true
            adapter.notifyDataSetChanged()
        }

        binding.btnReset.onClick { adapter.setList(SearchOptionEntity.getSortOptionList()[0].items) }

        binding.btnNext.onClick {
            val option = adapter.data.find { it.isChecked }
            if (option != null) {
                callback.invoke(option)
                popWindow.dismiss()
            }
        }

        val location = IntArray(2)
        v.getLocationOnScreen(location)
        popWindow.showAsDropDown(v, 0, 0)
    }

    fun showSearchTypeOptions(context: Context, v: View, typeList: List<SearchOptionEntity.OptionItem>, onDismiss: () -> Unit, callback: (List<SearchOptionEntity.OptionItem>) -> Unit) {
        val view = LayoutInflater.from(context).inflate(R.layout.popup_search_options, null, false)
        val binding = PopupSearchOptionsBinding.bind(view)

        binding.rvParent.gone()

        val adapter = SearchOptionChildAdapter(false)
        binding.rvChild.adapter = adapter
        binding.rvChild.addItemDecoration(DividerItemDecoration(DensityUtils.dp2px(16f), DensityUtils.dp2px(16f), color = getColor(R.color.color_eeeeee)))

        val optionList = SearchOptionEntity.getTypeOptionList()[0]
        if (typeList.isNotEmpty()) {
            if (typeList.size == optionList.items.size - 1) {
                optionList.items[0].isChecked = true
            } else {
                optionList.items.forEach { item ->
                    if (typeList.find { it.id == item.id } != null) {
                        item.isChecked = true
                    }
                }
            }
        } else {
            optionList.items[0].isChecked = true
        }
        adapter.setList(optionList.items)

        val popWindow = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true)
        popWindow.isClippingEnabled = false
        popWindow.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        popWindow.setOnDismissListener {
            onDismiss.invoke()
        }

        adapter.setOnItemClickListener { _, _, i ->
            val item = adapter.getItem(i)
            item.isChecked = !item.isChecked
            if (item.id == 0) {
                adapter.data.forEach { if (it.id != 0) it.isChecked = false }
            } else {
                adapter.data[0].isChecked = false
            }
            adapter.notifyDataSetChanged()
        }

        binding.btnReset.onClick {
            val list = SearchOptionEntity.getTypeOptionList()[0].items
            list[0].isChecked = true
            adapter.setList(list)
        }

        binding.btnNext.onClick {
            val list = adapter.data.filter { it.isChecked && it.id != 0 }
            callback.invoke(list)
            popWindow.dismiss()
        }

        val location = IntArray(2)
        v.getLocationOnScreen(location)
        popWindow.showAsDropDown(v, 0, 0)
    }
}