package com.gh.gamecenter.qa.answer.detail

import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.common.util.SyncDataBetweenPageHelper
import com.gh.gamecenter.common.utils.observeNonNull
import com.gh.gamecenter.common.utils.viewModelProviderFromParent
import com.gh.gamecenter.databinding.FragmentAnswerDetailContainerBinding
import com.gh.gamecenter.common.base.fragment.ToolbarFragment


class AnswerDetailContainerFragment : ToolbarFragment() {

    private lateinit var mFragmentAdapter: AnswerDetailFragmentStatePagerAdapter
    private lateinit var mContainerViewModel: AnswerDetailContainerViewModel
    private lateinit var mBinding: FragmentAnswerDetailContainerBinding
    private val fragments = ArrayList<AnswerDetailFragment>()

    // 是否已经传了 argument 给第一个子 fragment
    private var mHasPassedOneTimeArgumentToChild = false

    override fun getLayoutId(): Int = 0

    override fun getInflatedLayout(): View {
        return FragmentAnswerDetailContainerBinding.inflate(LayoutInflater.from(requireContext()), null, false).apply {
            mBinding = this
        }.root
    }

    override fun onMenuItemClick(menuItem: MenuItem?) {
        fragmentManager?.fragments?.let {
            for (fragment in it) {
                if (fragment is AnswerDetailFragment && fragment.isResumed) {
                    fragment.onMenuItemClick(menuItem!!)
                }
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mContainerViewModel = viewModelProviderFromParent()

        val answerId = arguments?.getString(EntranceConsts.KEY_ANSWER_ID) ?: ""
        if (!mContainerViewModel.answerIdList.contains(answerId)) {
            mContainerViewModel.answerIdList.add(answerId)
        }
        val tag = "android:switcher:${mBinding.viewpager.id}:"
        mFragmentAdapter = AnswerDetailFragmentStatePagerAdapter(parentFragmentManager) { id, position ->
            var fragment = childFragmentManager.findFragmentByTag("${tag}${position}") as? AnswerDetailFragment
            if (fragment == null) {
                fragment = AnswerDetailFragment().apply {
                    if (mHasPassedOneTimeArgumentToChild) {
                        this@AnswerDetailContainerFragment.arguments?.putBoolean(
                            EntranceConsts.KEY_SHOW_ANSWER_COMMENT,
                            false
                        )
                        this@AnswerDetailContainerFragment.arguments?.putBoolean(
                            EntranceConsts.KEY_RECOMMENDS_CONTENTS,
                            false
                        )
                    }

                    // 将外部的 argument 传给里面的 fragment
                    this.arguments = this@AnswerDetailContainerFragment.arguments
                    this.arguments?.putString(EntranceConsts.KEY_ANSWER_ID, id)
                    mHasPassedOneTimeArgumentToChild = true
                    fragments.add(this)
                }
            }
            fragment
        }
        mFragmentAdapter.answerIdList = ArrayList(mContainerViewModel.answerIdList)

        mBinding.viewpager.adapter = mFragmentAdapter

        mContainerViewModel.answerListChange.observeNonNull(this) {
            mFragmentAdapter.answerIdList = ArrayList(mContainerViewModel.answerIdList)
            try {
                mFragmentAdapter.notifyDataSetChanged()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        mContainerViewModel.scroll.observeNonNull(this) {
            val currentItem = mBinding.viewpager.currentItem
            when (it) {
                AnswerDetailContainerViewModel.SCROLL_TO_NEXT_ANSWER -> {
                    if (currentItem == mContainerViewModel.answerIdList.size) {
                        toast("到底了")
                        return@observeNonNull
                    } else {
                        mBinding.viewpager.currentItem = currentItem + 1
                    }
                }
                AnswerDetailContainerViewModel.SCROLL_TO_PREVIOUS_ANSWER -> {
                    if (currentItem == mContainerViewModel.answerIdList.size) {
                        toast("到顶了")
                        return@observeNonNull
                    } else {
                        mBinding.viewpager.currentItem = currentItem - 1
                    }
                }
            }
        }
    }

    override fun onBackPressed(): Boolean {
        val answerDetail = fragments[0].mViewModel.answerDetail
        if (SyncDataBetweenPageHelper.setResultAndFinish(requireActivity(), answerDetail)) {
            return true
        }
        return super.onBackPressed()
    }

}