package com.cheng.blzb.ui.fragment.merchant

import android.annotation.SuppressLint
import android.graphics.Typeface
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.angcyo.tablayout.delegate.ViewPager1Delegate
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.common.EventConstants
import com.cheng.blzb.databinding.FragmentMerchantBinding
import com.cheng.blzb.impl.TextWatcherImpl
import com.cheng.blzb.manager.EventReportManager
import com.cheng.blzb.manager.SearchHistoryManager
import com.cheng.blzb.ui.base.BasePageAdapter
import com.cheng.blzb.ui.dialog.SelectAreaDialog
import com.cheng.blzb.ui.fragment.merchant.list.MerchantGoodsListFragment
import com.cheng.blzb.utils.KeyboardUtils
import com.example.base.extensions.onClick
import com.example.base.ui.BaseFragment


/**
 * 合作商
 */
class MerchantFragment : BaseFragment<FragmentMerchantBinding, MerchantViewModel>() {
    private val keyword by lazy { arguments?.getString("keyword") ?: "" }

    private val tabText = listOf("全部", "服务", "产品", "其他")

    private val fragmentList by lazy { mutableListOf<Fragment>() }
    private val pageAdapter by lazy { BasePageAdapter(childFragmentManager, tabText, fragmentList) }

    private var city: AreaEntity? = AreaEntity(0, name = "全国")

    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.GONE else View.VISIBLE
        }
    }

    override fun initView() {
        super.initView()
        initFragment()
        binding.viewPager.adapter = pageAdapter
        binding.viewPager.offscreenPageLimit = fragmentList.size
        binding.tabLayout.setupViewPager(ViewPager1Delegate.install(binding.viewPager, binding.tabLayout))
    }

    private fun initFragment() {
        fragmentList.add(MerchantGoodsListFragment.newInstance(""))
        fragmentList.add(MerchantGoodsListFragment.newInstance("1"))
        fragmentList.add(MerchantGoodsListFragment.newInstance("2"))
        fragmentList.add(MerchantGoodsListFragment.newInstance("3"))
    }

    override fun initData() {
        super.initData()
        binding.etSearch.setText(keyword)
        fragmentList.forEach {
            val fragment = it as MerchantGoodsListFragment
            fragment.setKeyword(keyword)
        }
    }

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

        binding.tvCity.onClick {
            val f = SelectAreaDialog.newInstance(if (city != null) listOf(city!!) else emptyList(), true, showAll = true)
            f.setOnSelectListener {
                city = if (it.size == 1) it[0] else null
                binding.tvCity.text = if (city != null) city!!.name else "全国"
                fragmentList.forEach { f ->
                    val fragment = f as MerchantGoodsListFragment
                    fragment.setCity(if (city != null) "${city!!.id}" else "")
                }
            }
            f.show(childFragmentManager, "")
        }

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

        binding.etSearch.setOnEditorActionListener { _, _, event ->
            if (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                val keyword = binding.etSearch.text.toString().trim()
                fragmentList.forEach {
                    val fragment = it as MerchantGoodsListFragment
                    fragment.setKeyword(keyword)
                }
                SearchHistoryManager.addHistory(keyword)
                KeyboardUtils.hideSoftInput(requireActivity())
                return@setOnEditorActionListener true
            }
            false
        }

        binding.tabLayout.observeIndexChange { fromIndex, toIndex, _, _ ->
            binding.viewPager.currentItem = toIndex
            if (fromIndex != -1) {
                (binding.tabLayout.getChildAt(fromIndex) as TextView).typeface = Typeface.DEFAULT
                (binding.tabLayout.getChildAt(fromIndex) as TextView).setBackgroundResource(R.drawable.shape_push_bid_type_default)
            }
            (binding.tabLayout.getChildAt(toIndex) as TextView).typeface = Constants.douyinsansB
            (binding.tabLayout.getChildAt(toIndex) as TextView).setBackgroundResource(R.drawable.shape_push_bid_type_checked)
            EventReportManager.eventReport(EventConstants.GOODS_TYPE_CHECK, "", (binding.tabLayout.getChildAt(toIndex) as TextView).text.toString())
        }
    }

    override fun initObserve() {
        super.initObserve()
    }

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