package com.cheng.blzb.ui.fragment.search.list

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import androidx.core.animation.addListener
import com.cheng.blzb.R
import com.cheng.blzb.bean.BidItemEntity
import com.cheng.blzb.bean.SearchOptionEntity
import com.cheng.blzb.databinding.FragmentSearchListBinding
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.manager.SearchHistoryManager
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.PopupDialog
import com.cheng.blzb.ui.fragment.bid.BidAdapter
import com.cheng.blzb.ui.fragment.bid.detail.BidDetailFragment
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.utils.KeyboardUtils
import com.example.base.extensions.getColor
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.ui.list.ListFragment

class SearchListFragment : ListFragment<FragmentSearchListBinding, SearchListViewModel, BidItemEntity>() {
    private val keyword by lazy { arguments?.getString("keyword") ?: "" }
    private val typeId by lazy { arguments?.getString("typeId") ?: "" }

    private val cityList = mutableListOf<SearchOptionEntity.OptionItem>()
    private val typeList = mutableListOf<SearchOptionEntity.OptionItem>()
    private var timeOption: SearchOptionEntity.OptionItem? = null
    private var sortOption: SearchOptionEntity.OptionItem? = null

    private var item: BidItemEntity? = null

    override fun noDataClick() {

    }

    override fun bindAdapter() = BidAdapter(true)

    private val textWatcher = object : TextWatcherImpl() {
        @SuppressLint("SetTextI18n")
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            binding.ivClearText.visibility = if (TextUtils.isEmpty(s)) View.INVISIBLE else View.VISIBLE
        }
    }

    override fun initView() {
        super.initView()

        mEmptyView.setNoDataLogo(R.mipmap.ic_empty_data)
    }

    override fun initData() {
        super.initData()
        binding.etSearch.setText(keyword)

        mViewModel.params["query"] = keyword
        mViewModel.params["sort"] = UserConfigManager.getSearchSort()
        if (!TextUtils.isEmpty(typeId)) {
            val type = UserConfigManager.getBidTypes().find { it.id == typeId }
            if (type != null) {
                typeList.add(SearchOptionEntity.OptionItem(type.id.toInt(), type.name, true))
                mViewModel.params["typeId"] = typeList.map { item -> item.id }.joinToString(",")
            }
        }
        firstLoad()
    }

    override fun initListener() {
        super.initListener()
        binding.etSearch.addTextChangedListener(textWatcher)

        binding.etSearch.setOnEditorActionListener { _, _, event ->
            if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                val keyword = binding.etSearch.text.toString().trim()
                if (TextUtils.isEmpty(keyword)) {
                    toast("请输入搜索关键词")
                    return@setOnEditorActionListener true
                }
                KeyboardUtils.hideSoftInput(requireActivity())
                SearchHistoryManager.addHistory(keyword)
                mViewModel.params["query"] = keyword
                firstLoad()
                KeyboardUtils.hideSoftInput(requireActivity())
                return@setOnEditorActionListener true
            }
            false
        }

        binding.ivClearText.onClick {
            binding.etSearch.setText("")
        }

        binding.btnArea.onClick {
            binding.btnArea.setTextColor(getColor(R.color.color_125ffe))
            binding.btnArea.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_up, 0)
            PopupDialog.showSearchAreaOptions(requireContext(), binding.layoutOptions, cityList, {
                binding.viewMask.gone()
                binding.btnArea.setTextColor(getColor(R.color.color_1a1a1a))
                binding.btnArea.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_down, 0)
            }, {
                cityList.clear()
                cityList.addAll(it)

                mViewModel.params["cityId"] = it.map { item -> item.id }.joinToString(",")
                firstLoad()
            })
            showMask()
        }

        binding.btnTime.onClick {
            binding.btnTime.setTextColor(getColor(R.color.color_125ffe))
            binding.btnTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_up, 0)
            PopupDialog.showSearchTimeOptions(requireContext(), binding.layoutOptions, childFragmentManager, timeOption, {
                binding.viewMask.gone()
                binding.btnTime.setTextColor(getColor(R.color.color_1a1a1a))
                binding.btnTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_down, 0)
            }, {
                timeOption = it
                mViewModel.params["start_time"] = it.startTime
                mViewModel.params["end_time"] = it.endTime
                firstLoad()
            })
            showMask()
        }

        binding.btnSort.onClick {
            binding.btnSort.setTextColor(getColor(R.color.color_125ffe))
            binding.btnSort.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_up, 0)
            PopupDialog.showSearchSortOptions(requireContext(), binding.layoutOptions, sortOption, {
                binding.viewMask.gone()
                binding.btnSort.setTextColor(getColor(R.color.color_1a1a1a))
                binding.btnSort.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_down, 0)
            }, {
                sortOption = it
                if (it.id == 0) {
                    mViewModel.params["sort"] = UserConfigManager.getSearchSort()
                } else {
                    if (UserConfigManager.getSearchSort() == "issue_time DESC") {
                        mViewModel.params["sort"] = "issue_time ASC"
                    } else {
                        mViewModel.params["sort"] = "issue_time DESC"
                    }
                }
                firstLoad()
            })
            showMask()
        }

        binding.btnType.onClick {
            binding.btnType.setTextColor(getColor(R.color.color_125ffe))
            binding.btnType.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_up, 0)
            PopupDialog.showSearchTypeOptions(requireContext(), binding.layoutOptions, typeList, {
                binding.viewMask.gone()
                binding.btnType.setTextColor(getColor(R.color.color_1a1a1a))
                binding.btnType.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_option_arrow_down, 0)
            }, {
                typeList.clear()
                typeList.addAll(it)
                mViewModel.params["typeId"] = it.map { item -> item.id }.joinToString(",")
                firstLoad()
            })
            showMask()
        }

        mAdapter.setOnItemClickListener { _, _, i ->
            item = mAdapter.getItem(i)
            mViewModel.checkAuth()
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.authLiveData.observe(this) {
            if (it.auth) {
                PublicActivity.start(
                    requireContext(),
                    BidDetailFragment::class.java,
                    Pair("id", item!!.id),
                    Pair("info_source", item!!.info_source)
                )
            } else {
                PublicActivity.start(requireContext(), VipFragment::class.java, Pair("origin", "view_bid"))
            }
        }
    }

    private fun showMask() {
        val anim = ObjectAnimator.ofFloat(binding.viewMask, "alpha", 0f, 1f)
        anim.duration = 200
        anim.addListener(onStart = {
            binding.viewMask.visible()
        })
        anim.startDelay = 100
        anim.start()
    }

    override fun onDestroyView() {
        binding.etSearch.removeTextChangedListener(textWatcher)
        super.onDestroyView()
    }
}