package com.gh.gamecenter.subject

import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.GlobalActivityManager
import com.gh.gamecenter.common.base.fragment.LazyFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.json.json
import com.gh.gamecenter.common.utils.SensorsBridge
import com.gh.gamecenter.core.utils.PageSwitchDataHelper
import com.gh.gamecenter.databinding.FragmentSubjectBinding
import com.gh.gamecenter.entity.SubjectSettingEntity
import com.gh.gamecenter.subject.rows.SubjectRowsFragment
import com.gh.gamecenter.subject.tab.SubjectTabFragment
import com.gh.gamecenter.subject.tile.SubjectTileFragment
import com.halo.assistant.HaloApp

open class SubjectFragment : LazyFragment() {

    private var mBinding: FragmentSubjectBinding? = null
    private var mViewModel: SubjectViewModel? = null

    override fun getRealLayoutId() = R.layout.fragment_subject

    override fun onRealLayoutInflated(inflatedView: View) {
        super.onRealLayoutInflated(inflatedView)
        mBinding = FragmentSubjectBinding.bind(inflatedView)
    }

    override fun onFragmentFirstVisible() {
        // 是否为专题合集详情子页面
        val isColumnCollection = arguments?.getBoolean(EntranceConsts.KEY_IS_COLUMN_COLLECTION) ?: false
        // 专题合集详情子页面不需要显示菜单
        if (!isColumnCollection) initMenu(R.menu.menu_download)

        mViewModel = provideViewModel()

        super.onFragmentFirstVisible()

        PageSwitchDataHelper.popLastPageData()?.let {
            arguments?.putSerializable(LAST_PAGE_DATA, it)
        }

        // 获取专题配置
        mViewModel?.subjectSettingLD?.observe(this, Observer {
            mBinding?.loadingContainer?.reuseLlLoading?.visibility = View.GONE
            if (it == null) {
                mBinding?.noConnectionContainer?.reuseNoConnection?.visibility = View.VISIBLE
            } else {
                showAdLabel(it.adIconActive)
                initContentView(it)
            }
        })

        if (!isColumnCollection) {// 专题合集详情子页面不需要显示专题名称
            // 获取专题名称
            mViewModel?.subjectNameLD?.observe(this) {
                setNavigationTitle(it)
            }
            logPageShow()
        }
    }

    private fun logPageShow() {
        val tabIndex = arguments?.getInt(EntranceConsts.KEY_TAB_INDEX, -1) ?: -1
        val tabName = arguments?.getString(EntranceConsts.KEY_TAB_NAME, "") ?: ""
        val multiTabNavId = arguments?.getString(EntranceConsts.KEY_MULTI_TAB_NAV_ID, "") ?: ""
        val multiTabNavName = arguments?.getString(EntranceConsts.KEY_MULTI_TAB_NAV_NAME, "") ?: ""
        val bottomTabName = arguments?.getString(EntranceConsts.KEY_BOTTOM_TAB_NAME, "") ?: ""
        mBaseHandler.postDelayed({
            SensorsBridge.trackEvent("ColumnDetailPageShow", json {
                "game_column_name" to mViewModel?.subjectData?.subjectName
                "game_column_id" to mViewModel?.subjectData?.subjectId
                "page_name" to GlobalActivityManager.getCurrentPageEntity().pageName
                "page_id" to GlobalActivityManager.getCurrentPageEntity().pageId
                "page_business_id" to GlobalActivityManager.getCurrentPageEntity().pageBusinessId
                "last_page_name" to GlobalActivityManager.getLastPageEntity().pageName
                "last_page_id" to GlobalActivityManager.getLastPageEntity().pageId
                "last_page_business_id" to GlobalActivityManager.getLastPageEntity().pageBusinessId
                "bottom_tab" to bottomTabName
                "several_tab_page_name" to multiTabNavName
                "several_tab_page_id" to multiTabNavId
                "position" to tabIndex
                "tab_content" to tabName
                "source_entrance" to mEntrance
            })
        }, 3000L)
    }

    override fun initRealView() {
        super.initRealView()

        mBinding?.loadingContainer?.reuseLlLoading?.setOnClickListener {}
        mBinding?.noConnectionContainer?.reuseNoConnection?.setOnClickListener {
            mBinding?.loadingContainer?.reuseLlLoading?.visibility = View.VISIBLE
            mBinding?.noConnectionContainer?.reuseNoConnection?.visibility = View.GONE
            mViewModel?.initData()
        }
    }

    private fun initContentView(entity: SubjectSettingEntity) {
        val transaction = childFragmentManager.beginTransaction()
        val tag: String
        val fragment: Fragment = when {
            "tile" == entity.typeEntity.layout -> {
                tag = SubjectTileFragment::class.java.name
                childFragmentManager.findFragmentByTag(tag)
                    ?: SubjectTileFragment()
            }

            "rows" == entity.typeEntity.layout -> {
                tag = SubjectRowsFragment::class.java.name
                childFragmentManager.findFragmentByTag(tag)
                    ?: SubjectRowsFragment()
            }

            else -> {
                tag = SubjectTabFragment::class.java.name
                childFragmentManager.findFragmentByTag(tag)
                    ?: SubjectTabFragment()
            }
        }
        val bundle = arguments
        bundle?.putParcelable(EntranceConsts.KEY_SUBJECT_DATA, mViewModel?.subjectData)
        bundle?.putParcelable(EntranceConsts.KEY_SUBJECT_SETTING_DATA, entity)
        fragment.arguments = bundle
        transaction.replace(R.id.subject_content, fragment, tag)
        transaction.commitAllowingStateLoss()
    }

    protected open fun provideViewModel(): SubjectViewModel {
        val factory = SubjectViewModel.Factory(
            HaloApp.getInstance().application,
            arguments?.getParcelable(EntranceConsts.KEY_SUBJECT_DATA),
        )
        return ViewModelProviders.of(this, factory).get(SubjectViewModel::class.java)
    }

    companion object {
        const val LAST_PAGE_DATA = "last_page_data"
    }

}