package com.gh.gamecenter.simulatorgame

import android.app.Dialog
import android.graphics.Paint
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.lifecycle.Observer
import androidx.viewpager.widget.PagerAdapter
import com.gh.gamecenter.common.base.fragment.BaseFragment_TabLayout
import com.gh.gamecenter.core.AppExecutor
import com.gh.gamecenter.common.constant.Constants
import com.gh.common.util.*
import com.gh.common.util.DirectUtils.directToLinkPage
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.common.view.BugFixedPopupWindow
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.databinding.DialogSimulaorGameGuideBinding
import com.gh.gamecenter.databinding.FragmentSimulatorGameBinding
import com.gh.gamecenter.databinding.PopupSimulatorGuideBinding
import com.gh.gamecenter.common.base.fragment.ToolbarFragment

class SimulatorGameFragment : ToolbarFragment() {

    private lateinit var mViewModel: SimulatorGameViewModel
    private var mTypeAliasList = ArrayList<String>()
    private var mFragmentsList = ArrayList<Fragment>()
    private var mCurrentPage = 0
    private val mBinding by lazy { FragmentSimulatorGameBinding.inflate(layoutInflater) }

    override fun getLayoutId() = 0

    override fun getInflatedLayout() = mBinding.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel = viewModelProviderFromParent()
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getSimulators()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initMenu(R.menu.menu_simulator_manager)
    }

    fun refresh() {
        mViewModel.getSimulators()
    }

    override fun onMenuItemClick(menuItem: MenuItem) {
        super.onMenuItemClick(menuItem)
        if (menuItem.itemId == R.id.menu_simulator_manager) {
            startActivity(SimulatorManagementActivity.getIntent(requireContext()))
            MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击模拟器管理")
            NewFlatLogUtils.logSimulatorManagerClick()
        }
    }

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

        mViewModel.simulators.observe(viewLifecycleOwner, Observer { list ->
            mCurrentPage = 0
            mTypeAliasList.clear()
            mFragmentsList.clear()
            if (list.isEmpty()) {
                // 只剩一个tab然后删除了该tab所有游戏后刷新adapter
                mBinding.fragmentViewPager.adapter?.notifyDataSetChanged()
                if (mViewModel.isSimulatorGameFirstLoad) {
                    mViewModel.simulatorGameLoadSuccess.postValue(false)
                    mViewModel.isSimulatorGameFirstLoad = false
                }
                mBinding.reuseNoneData.reuseNoneData.visibility = View.VISIBLE
                mBinding.reuseNoneData.reuseNoneData.setBackgroundColor(R.color.background_white.toColor(requireContext()))
                mBinding.reuseNoneData.reuseResetLoadTv.text = "下载模拟器游戏"
                val param = mBinding.reuseNoneData.reuseResetLoadTv.layoutParams
                param.width = DisplayUtils.dip2px(180F)
                mBinding.reuseNoneData.reuseResetLoadTv.layoutParams = param
                AdHelper.getAdForLocation(AdHelper.LOCATION_SIMULATOR_GAME)?.let { ad ->
                    mBinding.reuseNoneData.reuseResetLoadTv.run {
                        visibility = View.VISIBLE
                        text = ad.title
                        paint.isAntiAlias = true
                        setOnClickListener {
                            MtaHelper.onEvent("广告位统计", "模拟器游戏", ad.title)
                            directToLinkPage(requireContext(), ad.toLinkEntity(), "(模拟器游戏-广告位)", "")
                        }
                    }
                }
            } else {
                mBinding.reuseNoneData.reuseNoneData.visibility = View.GONE
                list.forEachIndexed { index, entity ->
                    mBinding.fragmentTabContainer.goneIf(list.size == 1)
                    mTypeAliasList.add(entity.typeAlias)
                    mFragmentsList.add(childFragmentManager.findFragmentByTag("android:switcher:${mBinding.fragmentViewPager.id}:$index")
                        ?: SimulatorGameListFragment().apply { with(bundleOf(EntranceConsts.KEY_SIMULATOR to entity)) })
                }

                if (mBinding.fragmentViewPager.adapter != null) {
                    // 删除了一个tab里面所有游戏后刷新adapter
                    mBinding.fragmentViewPager.adapter?.notifyDataSetChanged()
                    updateTabLayout()
                } else {
                    initViewPager()
                }
            }
        })
        mViewModel.simulatorGameLoadSuccess.observe(viewLifecycleOwner, Observer {
            AppExecutor.uiExecutor.executeWithDelay(Runnable {
                tryCatchInRelease { showSimulatorGuide(it) }
            }, 500)
        })
    }

    private fun initViewPager() {
        mBinding.fragmentViewPager.run {
            offscreenPageLimit = mFragmentsList.size
            adapter = object : FragmentStatePagerAdapter(childFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
                override fun getItem(position: Int) = mFragmentsList[position]

                override fun getCount() = mFragmentsList.size

                override fun getItemPosition(`object`: Any) = PagerAdapter.POSITION_NONE

                override fun getPageTitle(position: Int): CharSequence? {
                    return if (mTypeAliasList.size > position) {
                        mTypeAliasList[position]
                    } else super.getPageTitle(position)
                }
            }
            doOnPageSelected {
                MtaHelper.onEvent("我的光环_新", "模拟器游戏", "点击${mTypeAliasList[it]}")
                NewFlatLogUtils.logSimulatorGamePageTabClick(mTypeAliasList[it])
                // mCurrentPage < mFragmentsList.size 是为了防止数组越界
                if (mCurrentPage != it && mCurrentPage < mFragmentsList.size) {
                    (mFragmentsList.safelyGetInRelease(mCurrentPage) as? SimulatorGameListFragment)?.resetPage()
                    mCurrentPage = it
                }
            }
        }
        mBinding.fragmentTabLayout.setupWithViewPager(mBinding.fragmentViewPager)
        mBinding.fragmentTabIndicator.run {
            setupWithTabLayout(mBinding.fragmentTabLayout)
            setupWithViewPager(mBinding.fragmentViewPager)
        }

        updateTabLayout()
        BaseFragment_TabLayout.initTabStyle(mBinding.fragmentTabLayout, mBinding.fragmentViewPager.currentItem)
    }

    private fun updateTabLayout() {
        for (i in 0 until mBinding.fragmentTabLayout.tabCount) {
            val tab = mBinding.fragmentTabLayout.getTabAt(i) ?: continue
            val tabTitle = if (tab.text != null) tab.text.toString() else ""
            val tabView = BaseFragment_TabLayout.createDefaultTabCustomView(requireContext(), tabTitle)
            tab.customView = tabView
        }
    }

    private fun showSimulatorGuide(hasSimulatorGame: Boolean = false) {
        val isSimulatorGuide = SPUtils.getBoolean(Constants.SP_SIMULATOR_GUIDE, false)
        val isSimulatorGameGuide = SPUtils.getBoolean(Constants.SP_SIMULATOR_GAME_GUIDE, false)

        if (!isSimulatorGuide) {
            val binding = PopupSimulatorGuideBinding.inflate(LayoutInflater.from(requireContext()), null, false)
            val popupWindow = BugFixedPopupWindow(
                binding.root,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            popupWindow.apply {
                isTouchable = true
                isFocusable = true
            }
            (binding.simulatorGuideView.layoutParams as RelativeLayout.LayoutParams).apply {
                topMargin = 50f.dip2px()
                binding.simulatorGuideView.layoutParams = this
            }
            popupWindow.showAtLocation(requireActivity().window.decorView, Gravity.TOP, 0, 0)
            binding.guideCloseIv.setOnClickListener {
                SPUtils.setBoolean(Constants.SP_SIMULATOR_GUIDE, true)
                popupWindow.dismiss()
                if (hasSimulatorGame) {
                    showSimulatorGameGuide()
                }
            }
            binding.root.setOnClickListener { binding.guideCloseIv.performClick() }
            return
        }

        if (!isSimulatorGameGuide) {
            showSimulatorGameGuide()
        }
    }

    private fun showSimulatorGameGuide() {
        if (mFragmentsList.isNullOrEmpty()) return
        val simulatorGameListFragment = mFragmentsList[mCurrentPage] as SimulatorGameListFragment
        val itemView = simulatorGameListFragment.getFirstItemView() ?: return
        val location = IntArray(2)
        itemView.getLocationInWindow(location)
        val dialog = Dialog(requireContext(), R.style.DialogWindowTransparent)
        val binding = DialogSimulaorGameGuideBinding.inflate(LayoutInflater.from(requireContext()), null, false)
        dialog.setContentView(binding.root)
        val bitmap = itemView.getBitmapFromView()
        binding.simulatorGameSnapshot.setImageBitmap(bitmap)
        (binding.snapshotContainer.layoutParams as RelativeLayout.LayoutParams).apply {
            topMargin = location[1] - DisplayUtils.getStatusBarHeight(requireContext().resources)
            binding.snapshotContainer.layoutParams = this
        }
        dialog.show()
        val window = dialog.window
        if (window != null) {
            val params = window.attributes
            params.width = requireContext().resources.displayMetrics.widthPixels
            window.attributes = params
            window.setGravity(Gravity.TOP)
        }

        binding.root.setOnClickListener {
            dialog.dismiss()
        }
        dialog.setOnDismissListener {
            SPUtils.setBoolean(Constants.SP_SIMULATOR_GAME_GUIDE, true)
        }
    }

}