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

import android.graphics.Typeface
import android.os.Build
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.MerchantGoodsEntity
import com.cheng.blzb.common.Constants
import com.cheng.blzb.databinding.FragmentMerchantHomeBinding
import com.cheng.blzb.ui.base.BasePageAdapter
import com.cheng.blzb.ui.fragment.merchant.list.MerchantGoodsListFragment
import com.example.base.ui.BaseFragment

class MerchantHomeFragment : BaseFragment<FragmentMerchantHomeBinding, MerchantHomeViewModel>() {
    private var goodsInfo: MerchantGoodsEntity? = null

    private val tabText = listOf("全部", "服务", "产品", "其他")
    private val fragmentList by lazy { mutableListOf<Fragment>() }
    private val pageAdapter by lazy {
        BasePageAdapter(
            childFragmentManager,
            tabText,
            fragmentList,
            FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
        )
    }

    override fun initView() {
        super.initView()
        mTitleBar?.background = null

        goodsInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("item", MerchantGoodsEntity::class.java)
        } else {
            arguments?.getSerializable("item") as? MerchantGoodsEntity
        }
        binding.tvTitle.text = goodsInfo?.company?.company_name

        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("", goodsInfo!!.user_id))
        fragmentList.add(MerchantGoodsListFragment.newInstance("1", goodsInfo!!.user_id))
        fragmentList.add(MerchantGoodsListFragment.newInstance("2", goodsInfo!!.user_id))
        fragmentList.add(MerchantGoodsListFragment.newInstance("3", goodsInfo!!.user_id))
    }

    override fun initListener() {
        super.initListener()
        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)
        }
    }
}