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

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.View
import android.view.ViewTreeObserver
import android.view.animation.RotateAnimation
import androidx.constraintlayout.widget.ConstraintLayout
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentSearchBinding
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.manager.DialogEnum
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.TipDialog
import com.cheng.blzb.ui.fragment.merchant.MerchantFragment
import com.cheng.blzb.ui.fragment.search.list.SearchListFragment
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.BaseFragment
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

class SearchFragment: BaseFragment<FragmentSearchBinding, SearchViewModel>() {
    private val type by lazy { arguments?.getInt("type") ?: 0 }

    private val historyAdapter by lazy { HistoryKeywordAdapter() }
    private val recommendAdapter by lazy { RecommendKeywordAdapter() }

    private val hotTypeAdapter by lazy { HotTypeAdapter() }

    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()
        binding.tvTitle.typeface = Constants.pmzdbt

        val historyLayoutManager = FlexboxLayoutManager(requireContext())
        historyLayoutManager.flexDirection = FlexDirection.ROW
        historyLayoutManager.flexWrap = FlexWrap.WRAP
        historyLayoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvHistory.layoutManager = historyLayoutManager
        binding.rvHistory.adapter = historyAdapter

        val recommendLayoutManager = FlexboxLayoutManager(requireContext())
        recommendLayoutManager.flexDirection = FlexDirection.ROW
        recommendLayoutManager.flexWrap = FlexWrap.WRAP
        recommendLayoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvRecommend.layoutManager = recommendLayoutManager
        binding.rvRecommend.adapter = recommendAdapter

        binding.rvHot.adapter = hotTypeAdapter
        hotTypeAdapter.setList(UserConfigManager.getBidTypes())
    }

    override fun initData() {
        super.initData()
        mViewModel.getHotKeywordList("")
    }

    override fun initListener() {
        super.initListener()
        binding.ivTopBg.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                (binding.tvTitle.layoutParams as ConstraintLayout.LayoutParams).topMargin = (binding.ivTopBg.height * 100f / 300f).toInt()
                (binding.layoutSearch.layoutParams as ConstraintLayout.LayoutParams).topMargin = (binding.ivTopBg.height * 200f / 300f).toInt()
                binding.ivTopBg.viewTreeObserver.addOnGlobalLayoutListener(this)
            }
        })

        binding.etSearch.addTextChangedListener(textWatcher)

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

        binding.btnSearch.onClick {
            val keyword = binding.etSearch.text.toString().trim()
            if (TextUtils.isEmpty(keyword)) {
                toast("请输入搜索关键词")
                return@onClick
            }
            if (type == 0) {
                PublicActivity.start(requireContext(), SearchListFragment::class.java, Pair("keyword", keyword))
            } else {
                PublicActivity.start(requireContext(), MerchantFragment::class.java, Pair("keyword", keyword))
            }
            historyAdapter.setList(SearchHistoryManager.addHistory(keyword))
            binding.layoutHistory.visible()
        }

        binding.ivClearHistory.onClick {
            val f = TipDialog.newInstance("温馨提示", "确定清空搜索历史？")
            f.setOnSelectListener {
                if (it == DialogEnum.CLICK_OK) {
                    SearchHistoryManager.clear()
                    historyAdapter.setList(emptyList())
                    binding.layoutHistory.gone()
                }
            }
            f.show(childFragmentManager, TipDialog::class.java.simpleName)
        }

        binding.ivRefreshRecommend.onClick {
            startRotate()
            mViewModel.getHotKeywordList(if (recommendAdapter.data.isNotEmpty()) recommendAdapter.data.last() else "")
        }

        historyAdapter.setOnItemClickListener { _, _, i ->
            val item = historyAdapter.getItem(i)
            if (type == 0) {
                PublicActivity.start(requireContext(), SearchListFragment::class.java, Pair("keyword", item))
            } else {
                PublicActivity.start(requireContext(), MerchantFragment::class.java, Pair("keyword", item))
            }
            binding.etSearch.setText(item)
            historyAdapter.setList(SearchHistoryManager.updateHistory(item))
        }

        recommendAdapter.setOnItemClickListener { _, _, i ->
            val item = recommendAdapter.getItem(i)
            if (type == 0) {
                PublicActivity.start(requireContext(), SearchListFragment::class.java, Pair("keyword", item))
            } else {
                PublicActivity.start(requireContext(), MerchantFragment::class.java, Pair("keyword", item))
            }
            binding.etSearch.setText(item)
            historyAdapter.setList(SearchHistoryManager.addHistory(item))
            binding.layoutHistory.visible()
        }

        hotTypeAdapter.setOnItemClickListener { _, _, i ->
            val item = hotTypeAdapter.getItem(i)
            PublicActivity.start(requireContext(), SearchListFragment::class.java, Pair("typeId", item.id))
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.recommendLiveData.observe(this) {
            recommendAdapter.setList(it)
        }
    }

    private fun startRotate() {
        if (binding.ivRefreshRecommend.animation != null) {
            binding.ivRefreshRecommend.animation.cancel()
        }
        val anim = RotateAnimation(0f, 360f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f)
        anim.duration = 1000
        binding.ivRefreshRecommend.startAnimation(anim)
    }

    override fun onResume() {
        super.onResume()
        if (SearchHistoryManager.getHistory().isNotEmpty()) {
            historyAdapter.setList(SearchHistoryManager.getHistory())
            binding.layoutHistory.visible()
        }
    }

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