package com.yidian.shenghuoquan.bgoods.ui.coupon

import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.orhanobut.hawk.Hawk
import com.yidian.bcommon.HawkConfig
import com.yidian.bcommon.XBirdPageConstants
import com.yidian.bcommon.XEventConfig
import com.yidian.bcommon.XRouterPathConstants
import com.yidian.bcommon.mvvm.BaseMvvmActivity
import com.yidian.shenghuoquan.bgoods.R
import com.yidian.shenghuoquan.bgoods.databinding.CommodityActivityCommodityManagementBinding
import com.yidian.shenghuoquan.bgoods.ui.coupon.fragment.CommodityListFragment
import com.yidian.shenghuoquan.bgoods.ui.coupon.viewmodel.CommodityManagementViewModel
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageManager
import com.yidian.xpage.XPageViewProtocol
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * author: yinjiacheng
 * date: 7/1/21 8:05 PM
 * description: 商品管理
 */
class CommodityManagementActivity : BaseMvvmActivity<CommodityActivityCommodityManagementBinding, CommodityManagementViewModel>(),
  XPageViewProtocol {

  companion object {
    // 审核中 tabId
    private const val ID_COMMODITY_AUDIT = 2
  }

  private var auditPageIndex: Int = -1

  override val layoutId: Int = R.layout.commodity_activity_commodity_management

  override val vm: CommodityManagementViewModel by viewModels()

  override fun initView() {
    vm.commodityStatusList.observe(this, {
      // ViewPager2设置适配器
      binding.vpCommodityList.adapter = object : FragmentStateAdapter(this) {
        override fun getItemCount() = it.size

        override fun createFragment(position: Int): Fragment {
          return CommodityListFragment.newInstance(it[position])
        }
      }

      // TabLayout设置tab切换监听
      binding.tlCommodityList.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
          // 刷新商品列表
          // 判空处理对应fragment未创建的情况
          supportFragmentManager.findFragmentByTag("f${tab?.position}")?.let { fragment ->
            (fragment as CommodityListFragment).refreshCommodityList()
          }
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {

        }

        override fun onTabReselected(tab: TabLayout.Tab?) {

        }

      })

      // TabLayout与ViewPager2绑定
      TabLayoutMediator(
        binding.tlCommodityList, binding.vpCommodityList
      ) { tab, position ->
        tab.text = it[position].name
      }.attach()

      // 记录审核中页面下标
      it.forEachIndexed { index, commodityStatus ->
        if (commodityStatus.tabId == ID_COMMODITY_AUDIT) {
          auditPageIndex = index
        }
      }
    })
    // 请求商品状态列表
    vm.requestCommodityStatusList()

    //发布商品
    binding.tvCommodityPublish.setOnClickListener {
      // 跳转商品发布页面 新发布商品不传id
      val pageUrl = XBirdPageConstants.COMMODITY_PUBLISH_COMMODITY + "?life_account_id=${Hawk.get(HawkConfig.LifeAccountId, "")}"
      XPageManager.push(XRouterPathConstants.COMMON_WEB_VIEW_ACTIVITY, hashMapOf(Pair(XBirdPageConstants.PAGE_URL, pageUrl)))
    }
  }

  override fun getXPageName(): String {
    return XRouterPathConstants.COMMODITY_MANAGEMENT
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    XEventManager.register(this)
  }

  override fun onDestroy() {
    super.onDestroy()
    XEventManager.unRegister(this)
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.COMMODITY_PUBLISH_SUCCESS -> {
        // 商品发布成功 跳转审核中列表并刷新列表
        binding.vpCommodityList.currentItem = auditPageIndex
        (supportFragmentManager.findFragmentByTag("f$auditPageIndex") as CommodityListFragment).refreshCommodityList()
      }
    }
  }

}
