package com.cheng.blzb.ui.fragment.home.zzdb

import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.ViewOutlineProvider
import android.view.ViewTreeObserver
import androidx.constraintlayout.widget.ConstraintLayout
import com.cheng.blzb.R
import com.cheng.blzb.databinding.FragmentZzdbBinding
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.fragment.home.zzdb.detail.ZZDBDetailFragment
import com.cheng.blzb.utils.KeyboardUtils
import com.example.base.extensions.getColor
import com.example.base.extensions.onClick
import com.example.base.ui.BaseFragment
import com.example.base.widget.EmptyView
import com.example.base.widget.PageStatus

class ZZDBFragment: BaseFragment<FragmentZzdbBinding, ZZDBViewModel>() {
    private val mAdapter by lazy { ZZDBAdapter() }
    private val mEmptyView by lazy { EmptyView(requireContext()) }

    private var keyword = ""

    private var page = 1

    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()
        mTitleBar?.setBackgroundColor(getColor(R.color.windowBackground))
        mTitleBar?.background?.alpha = 0

        binding.mRecyclerView.adapter = mAdapter
        mEmptyView.setNoDataLogo(R.mipmap.ic_empty_data)
        mAdapter.setEmptyView(mEmptyView)

        binding.ivTopBg.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                (binding.layoutContent.layoutParams as ConstraintLayout.LayoutParams).topMargin = (binding.ivTopBg.height * 199f / 231f).toInt()
                binding.layoutContent.setupWith(binding.root).setFrameClearDrawable(binding.layoutContent.background).setBlurRadius(5f)
                binding.layoutContent.outlineProvider = ViewOutlineProvider.BACKGROUND
                binding.layoutContent.setClipToOutline(true)
                binding.ivTopBg.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }

    override fun initData() {
        super.initData()
        mViewModel.getAgencyList(page, "")
    }

    override fun initListener() {
        super.initListener()
        binding.mRefreshLayout.setOnRefreshListener {
            page = 1
            mViewModel.getAgencyList(page, keyword)
        }

        binding.mRefreshLayout.setOnLoadMoreListener {
            page++
            mViewModel.getAgencyList(page, keyword)
        }

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

        binding.etSearch.addTextChangedListener(textWatcher)

        binding.etSearch.setOnEditorActionListener { _, _, event ->
            if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                page = 1
                keyword = binding.etSearch.text.toString().trim()
                mViewModel.getAgencyList(page, keyword)
                KeyboardUtils.hideSoftInput(requireActivity())
                return@setOnEditorActionListener true
            }
            false
        }

        mAdapter.setOnItemClickListener { _, _, i ->
            PublicActivity.start(requireContext(), ZZDBDetailFragment::class.java, Pair("item", mAdapter.getItem(i)))
        }

        binding.nestedScrollView.setOnScrollChangeListener { _, _, scrollY, _, _ ->
            val offset = (binding.layoutContent.layoutParams as ConstraintLayout.LayoutParams).topMargin - binding.mTitleBar.height
            mTitleBar?.background?.alpha = ((scrollY / offset.toFloat()).coerceAtMost(1f) * 255f).toInt()
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.listLiveData.observe(this) {
            if (page == 1) {
                mAdapter.setList(it)
                binding.mRefreshLayout.finishRefresh()
            } else {
                mAdapter.addData(it)
                binding.mRefreshLayout.finishLoadMore()
            }
            binding.mRefreshLayout.setNoMoreData(it.size < 20)

            if (mAdapter.data.isNotEmpty()) {
                mEmptyView.setStatus(PageStatus.GONG)
            } else {
                mEmptyView.setStatus(PageStatus.NO_DATA)
            }
        }
    }

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