package com.gh.gamecenter.energy.view

import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.base.adapter.FragmentAdapter
import com.gh.gamecenter.common.base.fragment.BaseLazyFragment
import com.gh.gamecenter.common.callback.ConfirmListener
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.provider.IDirectProvider
import com.gh.gamecenter.core.utils.*
import com.gh.gamecenter.energy.HaloApp
import com.gh.gamecenter.energy.R
import com.gh.gamecenter.energy.databinding.FragmentEnergyCenterBinding
import com.gh.gamecenter.energy.databinding.TabItemEnergyBinding
import com.gh.gamecenter.energy.entity.CommodityCategoryEntity
import com.gh.gamecenter.energy.entity.SignStatusEntity
import com.gh.gamecenter.energy.utils.DialogUtils
import com.gh.gamecenter.energy.utils.IntegralLogHelper
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserManager
import com.gh.gamecenter.login.user.UserViewModel
import com.google.android.material.bottomsheet.BottomSheetBehavior
import kotlin.math.abs


class EnergyCenterFragment : BaseLazyFragment() {

    private var mBinding: FragmentEnergyCenterBinding? = null
    private var mUserViewModel: UserViewModel? = null
    private var mEnergyUserViewModel: EnergyUserViewModel? = null
    private var mEnergyCenterViewModel: EnergyCenterViewModel? = null
    private val mTitleList = listOf("赚光能", "兑换区")
    private var mTabList = arrayListOf<TextView>()
    private var mFragmentsList = ArrayList<Fragment>()
    private var mCategoryList = ArrayList<CommodityCategoryEntity>()
    private var mUserInfo: UserInfoEntity? = null
    private var mEnergy = 0L
    private var mSignStatus: SignStatusEntity? = null
    private var mInitTabIndex = 0
    private var mBehavior: BottomSheetBehavior<RelativeLayout>? = null
    private var mCallBack: (() -> Unit)? = null

    override fun getLayoutId() = 0

    override fun getInflatedLayout() =
        FragmentEnergyCenterBinding.inflate(layoutInflater).apply { mBinding = this }.root

    override fun onFragmentResume() {
        super.onFragmentResume()

        if (NetworkUtils.isNetworkConnected(requireContext())) {
            if (UserManager.getInstance().isLoggedIn) {
                mEnergyUserViewModel?.getUserEnergy()
                refreshTaskList()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mInitTabIndex = arguments?.getInt(EntranceConsts.KEY_TAB_INDEX) ?: 0
        if (mInitTabIndex != 0 && mInitTabIndex != 1) mInitTabIndex = 0

        mEnergyCenterViewModel = viewModelProvider()
        mUserViewModel = viewModelProvider(UserViewModel.Factory(HaloApp.getInstance()))
        mEnergyUserViewModel =
            viewModelProvider(EnergyUserViewModel.Factory(HaloApp.getInstance(), UserManager.getInstance().userId))
    }

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

        arrayListOf(
            mBinding?.backIv,
            mBinding?.userEnergyContainer,
            mBinding?.energyRuleTv,
            mBinding?.signIv,
            mBinding?.inviteIv
        ).forEach {
            it?.setOnClickListener(this)
        }

        mEnergyCenterViewModel?.categories?.observeNonNull(viewLifecycleOwner) {
            mCategoryList.clear()
            mCategoryList.addAll(it)
            initViewpager()
        }

        mUserViewModel?.loginObsUserinfo?.observeNonNull(viewLifecycleOwner) {
            if (it.data != null) {
                mUserInfo = it.data
                mEnergyUserViewModel?.userId = UserManager.getInstance().userId
                mEnergyUserViewModel?.getSignInfo()
                mEnergyUserViewModel?.getUserEnergy()
                refreshTaskList()
            }
        }

        mEnergyUserViewModel?.energy?.observeNonNull(viewLifecycleOwner) {
            mEnergy = it
            mBinding?.userEnergy?.text = it.toString()
        }

        mEnergyUserViewModel?.sign?.observeNonNull(this) {
            mSignStatus = it
            DialogUtils.showSignSuccessDialog(requireContext(), object : ConfirmListener {
                override fun onConfirm() {
                    mEnergyUserViewModel?.getUserEnergy()
                    refreshTaskList()
                }
            })
        }

        mEnergyUserViewModel?.signStatus?.observeNonNull(this) {
            mSignStatus = it
            // 今天未签到且需要自动签到才调用签到接口
            if (!it.todaySignIn && !ClickUtils.isFastDoubleClick(990)) {
                mEnergyUserViewModel?.signIn()
            }
        }

        mBinding?.run {
//            background.layoutParams = background.layoutParams.apply {
//                val screenWidth = resources.displayMetrics.widthPixels
//                height = screenWidth * 400 / 360
//            }

            val screenHeight = when {
                Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 -> {
                    resources.displayMetrics.heightPixels
                }

                Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                    DisplayMetrics()
                        .apply { requireActivity().display?.getRealMetrics(this) }
                        .heightPixels
                }

                else -> {
                    @Suppress("DEPRECATION")
                    DisplayMetrics()
                        .apply { requireActivity().windowManager.defaultDisplay.getRealMetrics(this) }
                        .heightPixels
                }
            }

            mBehavior = BottomSheetBehavior.from(bottomSheet)
//            val toolbarHeight = screenHeight - DisplayUtils.getStatusBarHeight(resources) - 48F.dip2px()
            mBehavior?.peekHeight = screenHeight - 320F.dip2px()

//            val layoutParams = bottomSheet.layoutParams
//            layoutParams.height = toolbarHeight
//            bottomSheet.layoutParams = layoutParams

            mBehavior?.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
                override fun onStateChanged(bottomSheet: View, newState: Int) {

                    if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                        mBinding?.topContainer?.visibility = View.VISIBLE
                    } else {
                        mBinding?.topContainer?.visibility = View.INVISIBLE
                    }

                    if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                        mBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
                    }

                    if (mCallBack != null && newState == BottomSheetBehavior.STATE_EXPANDED) {
                        mCallBack?.invoke()
                        mCallBack = null
                    }
                }

                override fun onSlide(bottomSheet: View, slideOffset: Float) {
                    mBinding?.run {
                        if (slideOffset > 0.95) {
                            collapsedBg.visibility = View.GONE
                            expandedBg.visibility = View.VISIBLE
                        } else {
                            collapsedBg.visibility = View.VISIBLE
                            expandedBg.visibility = View.GONE
                        }
                    }
                }
            })
        }
    }

    private fun refreshTaskList() {
        if (mFragmentsList.isNotEmpty()) {
            (mFragmentsList[0] as TaskFragment).onLoadRefresh()
        }
    }

    private fun initViewpager() {
        mBinding?.run {
            mFragmentsList.clear()
            val tag = "android:switcher:${viewpager.id}:"
            val taskFragment = childFragmentManager.findFragmentByTag("${tag}0") ?: TaskFragment()
            val commodityListFragment = childFragmentManager.findFragmentByTag("${tag}1")
                ?: CommodityFragment().apply {
                    val bundle = Bundle()
                    bundle.putString(EntranceConsts.KEY_ENTRANCE, "光能中心")
                    if (mCategoryList.isNotEmpty()) {
                        bundle.putParcelable(EntranceConsts.KEY_CATEGORY, mCategoryList[0])
                        bundle.putParcelableArrayList(EntranceConsts.KEY_CATEGORY_LIST, mCategoryList)
                    }
                    arguments = bundle
                }
            mFragmentsList.add(taskFragment)
            mFragmentsList.add(commodityListFragment)

            viewpager.offscreenPageLimit = mFragmentsList.size
            viewpager.adapter =
                FragmentAdapter(childFragmentManager, mFragmentsList, mTitleList)
            viewpager.doOnScroll(
                onPageSelected = { position ->
                    updateTabTextStyle(position, 0F)
                },
                onPageScrolled = { position, positionOffset, _ ->
                    if (position + 1 != mTabList.size) {
                        mTabList[position].run {
                            textSize = (DEFAULT_TAB_TEXT_SIZE + ((1 - positionOffset) * 4)).roundTo(1)
//                                setTextColor(ColorUtils.blendARGB(TAB_DEFAULT_COLOR, TAB_SELECTED_COLOR, 1 - positionOffset))
                        }
                        mTabList[position + 1].run {
                            textSize = (DEFAULT_TAB_TEXT_SIZE + ((positionOffset) * 4)).roundTo(1)
//                                setTextColor(ColorUtils.blendARGB(TAB_DEFAULT_COLOR, TAB_SELECTED_COLOR, positionOffset))
                        }

                        // 多 tab 切换的时候可能会出现某些 tab 的文字没有回归到原始大小的问题的问题 (positionOffset 不保证连续)
                        for ((index, tabTv) in mTabList.withIndex()) {
                            if (abs(index - position) >= 2) {
                                if (tabTv.textSize != DEFAULT_TAB_TEXT_SIZE) {
                                    tabTv.textSize = DEFAULT_TAB_TEXT_SIZE
//                                        tabTv.setTextColor(TAB_DEFAULT_COLOR)
                                }
                            }
                        }
                    }

                    updateTabTextStyle(position, positionOffset)
                }
            )

            tabLayout.setupWithViewPager(viewpager)
            indicatorView.run {
                setupWithTabLayout(tabLayout)
                setupWithViewPager(viewpager)
                setIndicatorWidth(18)
            }

            for (i in 0 until tabLayout.tabCount) {
                val tab = tabLayout.getTabAt(i) ?: continue
                val tabTitle = if (tab.text != null) tab.text.toString() else ""
                val tabViewBinding = generateTabView(tabTitle)
                mTabList.add(tabViewBinding.tabTitle)
                tab.customView = tabViewBinding.root
                tab.view.setPadding(0, 0, 0, 0)
            }

            viewpager.currentItem = mInitTabIndex
            tabLayout.getTabAt(mInitTabIndex)?.let { updateTabTextStyle(mInitTabIndex, 0F) }
            if (mInitTabIndex == 1) setNestedScrollingEnabledForIndex(mInitTabIndex)

            // 处理BottomSheetBehavior的ViewPager嵌套RecyclerView滑动冲突问题
            viewpager.addOnPageChangeListener {
                if (it == 0) {
                    IntegralLogHelper.log("click_tab_energy_mission", LOCATION)
                } else {
                    IntegralLogHelper.log("click_tab_exchange", LOCATION)
                }

                setNestedScrollingEnabledForIndex(it)
            }
        }
    }

    private fun updateTabTextStyle(selectedPosition: Int, positionOffset: Float) {
        for ((index, titleTv) in mTabList.withIndex()) {
            if (index == selectedPosition) {
//                titleTv.setTextColor(TAB_SELECTED_COLOR)
                if (positionOffset == 0F) {
                    titleTv.setTypeface(null, Typeface.NORMAL)
                    titleTv.setTypeface(titleTv.typeface, Typeface.BOLD)
                }
            } else {
//                titleTv.setTextColor(TAB_DEFAULT_COLOR)
                if (positionOffset == 0F) {
                    titleTv.setTypeface(null, Typeface.NORMAL)
                }
            }
        }
    }

    private fun generateTabView(title: String): TabItemEnergyBinding {
        val binding = TabItemEnergyBinding.inflate(LayoutInflater.from(requireContext()))
        binding.tabTitle.run {
            text = title
            textSize = DEFAULT_TAB_TEXT_SIZE
            setTextColor(TAB_TEXT_COLOR)
        }
        binding.invisibleTabTitle.run {
            text = title
            textSize = DEFAULT_TAB_TEXT_SIZE
        }
        return binding
    }

    private fun setNestedScrollingEnabledForIndex(index: Int) {
        (mFragmentsList[0] as TaskFragment).setNestedScrollingEnabled(index == 0)
        (mFragmentsList[1] as CommodityFragment).setNestedScrollingEnabled(index == 1)
        mBinding?.bottomSheet?.requestLayout()
    }

    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.backIv -> requireActivity().finish()

            R.id.userEnergyContainer -> {
                IntegralLogHelper.run {
                    log("click_energy_record", LOCATION, "光能中心-光能值")
                    log("view_energy_record", "光能明细")
                }

                ifLogin("光能中心-光能值") {
                    val directUtils =
                        ARouter.getInstance().build(RouteConsts.provider.directUtils).navigation() as? IDirectProvider
                    directUtils?.directToEnergyRecord(requireContext())
                }
            }

            R.id.energyRuleTv -> {
                IntegralLogHelper.run {
                    log("click_energy_rule", LOCATION)
                    log("view_energy_rule", "光能规则")
                }
                val directUtils =
                    ARouter.getInstance().build(RouteConsts.provider.directUtils).navigation() as? IDirectProvider
                directUtils?.directToEnergyRulePage(requireContext())
            }

            R.id.signIv -> {
                ifLogin("光能中心-每日签到") {
                    mSignStatus?.run {
                        DialogUtils.showEnergySignDialog(requireContext(), sevenDaySerialSign)
                    }
                }
            }

            R.id.inviteIv -> {
                IntegralLogHelper.run {
                    log("click_invite_friend", LOCATION)
                    log("view_invite_friend", "邀请好友页")
                }

                ifLogin("光能中心-邀请好友") {
                    val directUtils =
                        ARouter.getInstance().build(RouteConsts.provider.directUtils).navigation() as? IDirectProvider
                    directUtils?.directToInviteFriends(requireContext())
                }
            }
        }
    }

    private fun dealSignIn() {
        IntegralLogHelper.log("click_sign", LOCATION)
        mEnergyUserViewModel?.signIn()
    }

    fun openBottomSheet(callback: () -> Unit) {
        if (mBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) {
            callback.invoke()
        } else {
            mCallBack = callback
            mBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
        }
    }

    override fun onDarkModeChanged() {
        super.onDarkModeChanged()
        mBinding?.run {
            root.setBackgroundColor(R.color.background_white.toColor(requireContext()))
            contentContainer.setBackgroundColor(R.color.background_white.toColor(requireContext()))
        }
    }

    companion object {
        const val LOCATION = "光能中心"
        var TAB_TEXT_COLOR: Int = R.color.text_00DBA4.toColor()
        var DEFAULT_TAB_TEXT_SIZE = 16F
    }
}