package com.cheng.blzb.ui.dialog

import android.annotation.SuppressLint
import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.databinding.DialogSelectAreaBinding
import com.cheng.blzb.manager.UserConfigManager
import com.example.base.extensions.getColor
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.utils.DensityUtils
import com.example.base.utils.ScreenUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class SelectAreaDialog : DialogFragment() {
    private val isSingle by lazy { arguments?.getBoolean("isSingle") ?: false }
    private val showAll by lazy { arguments?.getBoolean("showAll") ?: false }

    private var mOnBackListener: ((List<AreaEntity>) -> Unit)? = null     //回调事件

    private lateinit var binding: DialogSelectAreaBinding

    override fun onStart() {
        super.onStart()
        val window = dialog?.window
        val windowParams = window?.attributes
        windowParams?.dimAmount = 0.7f
        windowParams?.width = ScreenUtils.getWindowSize().x
        windowParams?.gravity = Gravity.BOTTOM
        windowParams?.windowAnimations = R.style.dialog_bottom
        dialog?.window?.attributes = windowParams
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val view = layoutInflater.inflate(R.layout.dialog_select_area, null)

        binding = DialogSelectAreaBinding.bind(view)

        val listStr = arguments?.getString("list")
        val defaultCityList = if (!TextUtils.isEmpty(listStr)) {
            Gson().fromJson(listStr, object : TypeToken<List<AreaEntity>>() {}.type)
        } else emptyList<AreaEntity>()

        val areaAdapter = AreaAdapter()
        binding.rvParent.adapter = areaAdapter

        val cityAdapter = CityAdapter()
        binding.rvChild.adapter = cityAdapter

        val areaList = UserConfigManager.getAreaList()
        if (!isSingle) {
            areaList.add(0, AreaEntity(0, name = "全国地区"))
            areaList.forEach { it.children.add(0, AreaEntity(0, name = "全部")) }
            if (defaultCityList.size == UserConfigManager.getCityList().size) {
                areaList[0].isChecked = true
                areaList[0].children[0].isChecked = true
            } else {
                areaList.forEach { area ->
                    area.children.forEach { child ->
                        if (defaultCityList.find { city -> city.id == child.id } != null) {
                            child.isChecked = true
                            if (areaList.find { it.isChecked } == null) {
                                area.isChecked = true
                            }
                        }
                    }
                    val selectedList = area.children.filter { item -> item.id != 0 }
                    if (selectedList.isNotEmpty() && selectedList.all { item -> item.isChecked }) {
                        area.children[0].isChecked = true
                    }
                }
            }
        } else {
            if (showAll) {
                areaList.add(0, AreaEntity(0, name = "全国地区", children = mutableListOf(AreaEntity(0, name = "全国"))))
                if (defaultCityList.isEmpty()) {
                    areaList[0].isChecked = true
                    areaList[0].children[0].isChecked = true
                }
            }
            if (!showAll || areaList.isNotEmpty()) {
                areaList.forEach { area ->
                    area.children.forEach { child ->
                        child.isChecked = defaultCityList.find { city -> city.id == child.id } != null
                        if (areaList.find { it.isChecked } == null) {
                            area.isChecked = true
                        }
                    }
                }
            }
        }
        if (areaList.find { it.isChecked } == null) {
            areaList[0].isChecked = true
        }
        areaAdapter.setList(areaList)
        cityAdapter.setList(areaList.find { it.isChecked }?.children)

        areaAdapter.setOnItemClickListener { _, _, position ->
            val item = areaAdapter.getItem(position)
            areaList.find { it.isChecked }?.isChecked = false
            item.isChecked = true
            areaAdapter.notifyDataSetChanged()

            cityAdapter.setList(item.children)
        }

        cityAdapter.setOnItemClickListener { _, _, position ->
            val item = cityAdapter.getItem(position)
            if (isSingle) {
                areaList.forEach { area ->
                    area.children.find { it.isChecked }?.isChecked = false
                }
                item.isChecked = true
            } else {
                item.isChecked = !item.isChecked
                if (item.isChecked) {
                    if (item.id == 0) {
                        cityAdapter.data.forEach { it.isChecked = true }
                    } else {
                        if (cityAdapter.data.filter { it.id != 0 }.all { it.isChecked }) {
                            cityAdapter.data[0].isChecked = true
                        }
                    }
                } else {
                    if (item.id == 0) {
                        cityAdapter.data.forEach { it.isChecked = false }
                    } else {
                        if (cityAdapter.data[0].isChecked) {
                            cityAdapter.data[0].isChecked = false
                        }
                    }
                }

                if (areaAdapter.data[0].isChecked) {
                    for (i in 1 until areaAdapter.data.size) {
                        areaAdapter.getItem(i).children.forEach {
                            it.isChecked = false
                        }
                    }
                } else {
                    if (areaAdapter.data[0].children[0].isChecked) {
                        areaAdapter.data[0].children[0].isChecked = false
                    }
                }
            }
            cityAdapter.notifyDataSetChanged()
        }

        binding.btnNext.onClick {
            val selectedCityList = mutableListOf<AreaEntity>()
            if (areaAdapter.data[0].children[0].id == 0 && areaAdapter.data[0].children[0].isChecked) {
                areaAdapter.data.forEach {
                    selectedCityList.addAll(it.children.filter { item -> item.id != 0 })
                }
            } else {
                areaAdapter.data.forEach {
                    selectedCityList.addAll(it.children.filter { item -> item.isChecked && item.id != 0 })
                }
            }
            if (selectedCityList.isEmpty()) {
                toast("请选择地区")
                return@onClick
            }
            mOnBackListener?.invoke(selectedCityList)
            dismiss()
        }

        binding.ivClose.onClick { dismiss() }

        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        return dialog
    }

    fun setOnSelectListener(listener: ((List<AreaEntity>) -> Unit)) {
        mOnBackListener = listener
    }

    companion object {
        fun newInstance(list: List<AreaEntity> = emptyList(), isSingle: Boolean = false, showAll: Boolean = false): SelectAreaDialog {
            val arg = Bundle()
            arg.putString("list", Gson().toJson(list))
            arg.putBoolean("isSingle", isSingle)
            arg.putBoolean("showAll", showAll)
            val fragment = SelectAreaDialog()
            fragment.arguments = arg
            return fragment
        }
    }

    class AreaAdapter() : BaseQuickAdapter<AreaEntity, BaseViewHolder>(R.layout.listitem_search_option_parent) {
        @SuppressLint("NotifyDataSetChanged")
        override fun convert(holder: BaseViewHolder, item: AreaEntity) {
            holder.setText(R.id.tv_name, item.name)
            holder.setVisible(R.id.view_tag, item.isChecked)
            holder.itemView.setBackgroundColor(if (item.isChecked) Color.WHITE else Color.TRANSPARENT)
            /*holder.setText(R.id.tv_title, item.name)

            val rvOptions = holder.getView<RecyclerView>(R.id.rv_options)
            if (rvOptions.adapter == null) {
                rvOptions.layoutManager = GridLayoutManager(context, 3)
                rvOptions.addItemDecoration(GridSpaceItemDecoration(3, DensityUtils.dp2px(8f), DensityUtils.dp2px(8f)))
                val adapter = CityItemAdapter()
                rvOptions.adapter = adapter
            }
            val itemAdapter = rvOptions.adapter as CityItemAdapter
            itemAdapter.setList(item.children)
            itemAdapter.setOnItemClickListener { _, _, i ->
                val childItem = itemAdapter.getItem(i)
                if (!isSingle) {
                    if (holder.layoutPosition == 0) {
                        data.forEach {
                            it.children.forEach { item -> item.isChecked = false }
                        }
                        childItem.isChecked = true
                        notifyDataSetChanged()
                    } else {
                        childItem.isChecked = !childItem.isChecked
                        if (childItem.id == 0) {
                            item.children.forEach { item -> item.isChecked = childItem.isChecked }
                        } else {
                            if (!childItem.isChecked) {
                                item.children[0].isChecked = false
                            } else {
                                if (item.children.filter { item -> item.isChecked }.size == item.children.size - 1) {
                                    item.children[0].isChecked = true
                                }
                            }
                        }
                        data[0].children[0].isChecked = false
                        notifyDataSetChanged()
                    }
                } else {
                    data.forEach {
                        it.children.find { item -> item.isChecked }?.isChecked = false
                    }
                    childItem.isChecked = true
                    notifyDataSetChanged()
                }
            }*/
        }
    }

    class CityAdapter : BaseQuickAdapter<AreaEntity, BaseViewHolder>(R.layout.listitem_search_option_child) {
        override fun convert(holder: BaseViewHolder, item: AreaEntity) {
            holder.setText(R.id.tv_name, item.name)
            holder.setTextColor(R.id.tv_name, if (item.isChecked) getColor(R.color.color_125ffe) else getColor(R.color.color_1a1a1a))
            holder.setVisible(R.id.iv_check, item.isChecked)
            holder.itemView.layoutParams.height = DensityUtils.dp2px(40f)
            holder.itemView.setPadding(DensityUtils.dp2px(30f), 0, DensityUtils.dp2px(25f), 0)
            /*holder.setText(R.id.tv_name, item.name)
            holder.setTextColor(R.id.tv_name, if (item.isChecked) getColor(R.color.color_ff493c) else getColor(R.color.color_1a1a1a))
            holder.getView<TextView>(R.id.tv_name).typeface = if (item.isChecked) Typeface.DEFAULT_BOLD else Typeface.DEFAULT

            holder.itemView.setBackgroundResource(R.drawable.shape_f7f7f7_cor4)*/
        }
    }
}