package com.duben.microtribe.ui.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.duben.microtribe.R
import com.duben.microtribe.ad.AdManager
import com.duben.microtribe.ad.banner.BannerManager
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.common.Constant
import com.duben.microtribe.manager.LocalVedioManager
import com.duben.microtribe.manager.TrackManager
import com.duben.microtribe.manager.UserManager
import com.duben.microtribe.mvp.model.*
import com.duben.microtribe.mvp.presenters.HomePresenter
import com.duben.microtribe.mvp.views.HomeView
import com.duben.microtribe.ui.adapter.HomeVideoPageAdapter
import com.duben.microtribe.ui.adapter.ImageTitleAdapter
import com.duben.microtribe.ui.adapter.TopAdapter
import com.duben.microtribe.ui.fragment.base.LazyLoadBaseFragment
import com.duben.microtribe.utils.AppPreferencesManager
import com.duben.microtribe.utils.SpanUtils
import com.duben.library.utils.GlideUtils
import com.duben.library.utils.json.JsonUtil
import com.duben.library.utils.nodoubleclick.AntiShake
import com.duben.microtribe.ui.activitys.*
import kotlinx.android.synthetic.main.fragment_main.*
import java.lang.reflect.Field
import java.util.*
import kotlin.concurrent.schedule

/**
 * 描述：首页
 * 作者：孟崔广
 * 时间：2023/6/29 11:30
 */
class MainFragment : LazyLoadBaseFragment(), HomeView, View.OnClickListener, OnRefreshListener {

    companion object {
        var mSelectTabIndex = -1
    }

    private val tabsData = mutableListOf<HotStyleTypesBean>()
    private val bannerList = mutableListOf<BannerBean>()
    private val topList = mutableListOf<VedioBean>()
    private var vpAdapter: HomeVideoPageAdapter? = null
    private var topAdapter: TopAdapter? = null
    private var recommendVedioBean: RecoBean? = null


    private val homePresenter by lazy { HomePresenter() }
    private val userManager by lazy { UserManager.getInstance() }

    override fun getContentViewLayoutID() = R.layout.fragment_main

    override fun initViewsAndEvents() {
        homePresenter.attachView(this)
    }

    override fun onFragmentFirstVisible() {
        initVp()
        initListener()
        loadData()

        AppPreferencesManager.get().put(Constant.VEDIO_MAIN_COUNT, 0)

        if (!UserManager.getInstance().vipFlag) {
            AdManager.instance.preLoadAd(requireActivity())
        }

        Handler(Looper.getMainLooper()).postDelayed({
            goToMainActivity()
        }, 300)
    }

    /**
     * 跳转到主页面
     */
    private fun goToMainActivity() {
//        if (UserManager.getInstance().newFlag && !UserManager.getInstance().vipFlag) {
//            homePresenter.getRecommendVedio()
//
//            val bundle = Bundle()
//            bundle.putBoolean(VipActivity.IS_MAIN, true)
//            readyGo(VipActivity::class.java, bundle)
//        } else {
//            homePresenter.getSoltVedio()
//        }

//        if (UserManager.getInstance().newFlag && !UserManager.getInstance().vipFlag) {
//            val bundle = Bundle()
//            bundle.putBoolean(VipActivity.IS_MAIN, true)
//            readyGo(VipActivity::class.java, bundle)
//        }
        homePresenter.getSoltVedio()
    }

    override fun onDestroy() {
        super.onDestroy()
        homePresenter.detachView()
    }

    override fun onFragmentResume() {
        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_ONE) {
            if (AntiShake.check(banner?.id)) return

//            if (!UserManager.getInstance().vipFlag) {
//                BannerManager.loadAd(requireActivity(), fl_main_banner)
//            }
//            BannerManager.loadAd(requireActivity(), fl_main_banner)

            if (AppConfig.exitLoginMainRefresh) {
                AppConfig.exitLoginMainRefresh = false
                loadData()
            }
            banner?.start()
            setWatchingStatus()

            if (TextUtils.isEmpty(userManager?.userID)) {
                //获取游客登录数据
                homePresenter.userLogin()
            } else {
                homePresenter.topTabs()
                homePresenter.orders()
                TrackManager.getInstance().getMyInfo()
//                showRecommendAct()
            }

            AppConfig.showVipAdDialog=false
        }
    }

    override fun onFragmentPause() {
        banner?.stop()
    }

    private fun initListener() {
        srlMainPage.setOnRefreshListener(this)
        iv_main_watching_close.setOnClickListener(this)
        tv_main_watching_goto.setOnClickListener(this)
        ll_lucky.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        if (AntiShake.check(v?.id)) return

        when (v?.id) {
            R.id.iv_main_watching_close -> {
                LocalVedioManager.closeCacheVedio()
                ll_main_watching_root.visibility = View.GONE
            }
            R.id.tv_main_watching_goto -> {
                val cacheVedio = LocalVedioManager.getCacheVedio()
                if (cacheVedio != null) {
                    LocalVedioManager.startVedioDetailActivityForType(requireActivity(), cacheVedio)
                }
            }
            R.id.ll_lucky -> {
                readyGo(NineActivity::class.java)
            }
        }
    }


    private fun loadData() {
        Timer().schedule(200) {
            requireActivity().runOnUiThread {
                if (AntiShake.check(rv_main_list?.id)) return@runOnUiThread

                if (!TextUtils.isEmpty(userManager?.userID)) {
                    homePresenter.getHomeV1Types()
                }
            }
        }
    }

    private fun initVp() {
        topAdapter = TopAdapter(topList)
        val ma = LinearLayoutManager(requireContext())
        ma.orientation = LinearLayoutManager.HORIZONTAL
        rv_main_list.layoutManager = ma
        rv_main_list.adapter = topAdapter
        topAdapter?.setOnItemClickListener(object : TopAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {
                if (topList.size > 0) {
                    LocalVedioManager.startVedioDetailActivityForType(
                            requireActivity(),
                            topList[position]
                    )
                }
            }
        })


        vpAdapter = HomeVideoPageAdapter(tabsData, this)
        vp2.adapter = vpAdapter
        vp2.desensitization()
        TabLayoutMediator(tablayout, vp2) { tab, position ->
            // 初始化Tab
            tab.id = position
            if (tabsData.size > 0) {
                tab.customView = getTabView(tabsData[position].type)
            }
        }.attach()
        tablayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                updateTab(tab, true)
                mSelectTabIndex = tab!!.id
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                updateTab(tab, false)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
        vp2.offscreenPageLimit = 100
    }

    private fun updateTab(tab: TabLayout.Tab?, isSelected: Boolean) {
        tab?.customView?.let {
            val text = it.findViewById<TextView>(R.id.item_tv)
            if (isSelected) {
                text.setTextColor(ContextCompat.getColor(requireContext(), R.color.red))
            } else {
                text.setTextColor(ContextCompat.getColor(requireContext(), R.color.color_8D8F90))
            }
        }
    }

    private fun getTabView(text: String): View {
        val view = LayoutInflater.from(requireContext()).inflate(R.layout.item_video_tab, null)
        view.findViewById<TextView>(R.id.item_tv).text = text
        return view
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        vpAdapter?.run {
            if (getFragments().isNotEmpty()) {
                val fragment = getFragments()[mSelectTabIndex]
                if (fragment != null) {
                    (fragment as MovieFragment).onRefresh()
                    refreshLayout.finishRefresh()
                }
            }
        }
    }

    fun setWatchingStatus() {
        if (LocalVedioManager.isCacheVedio()) {
            ll_main_watching_root.visibility = View.VISIBLE
            ll_main_watching_root.setOnClickListener { }
            val cacheVedio = LocalVedioManager.getCacheVedio()
            if (cacheVedio != null) {
                GlideUtils.loadImageViewGifForCenterCrop(
                        requireContext(),
                        cacheVedio.coverImage,
                        iv_main_watching_pic
                )
                tv_main_watching_name.text = cacheVedio.title
                tv_main_watching_text1.text = "上次观看至第${cacheVedio.seeIndex}集"
                if (cacheVedio.orderTags != null && cacheVedio.orderTags.size > 0) {
                    val sb = StringBuilder()
                    for (i in 0 until cacheVedio.orderTags.size) {
                        sb.append(cacheVedio.orderTags.get(i) + " ")
                    }
                    tv_main_watching_text2.text = "${sb}"
                }
            }
        } else {
            ll_main_watching_root.visibility = View.GONE
        }
    }

    override fun getHomeV1MsgSuc(data: HotStyleTypesList) {
        tabsData.clear()
        tabsData.addAll(data.list)
        if (tabsData.isNotEmpty()) {
            mSelectTabIndex = 0
            vpAdapter?.notifyDataSetChanged()
        }
    }

    override fun topTabsSuc(data: BannerList?) {
        if (data != null && data.list != null && data.list.size > 0) {
            bannerList.clear()
            for (i in 0 until data.list.size) {
                val bean = BannerBean()
                bean.title = data.list.get(i).topTabsReamrk
                bean.imageRes = data.list.get(i).typeImg
                bannerList.add(bean)
            }

            banner.addBannerLifecycleObserver(this)
                    .setAdapter(ImageTitleAdapter(bannerList))
                    .setOnBannerListener { data2, position ->
                        val banner = data.list.get(position)
                        if (banner.createType == 4) {
                            // 九宫格
                            val bundle = Bundle()
                            bundle.putBoolean(NineActivity.IS_AD_SHOW, true)
                            readyGo(NineActivity::class.java, bundle)
                        } else {
                            LocalVedioManager.startVedioDetailActivityForType(
                                    requireActivity(),
                                    banner
                            )
                        }

                    }
        }
    }

    override fun ordersSuc(data: BannerList?) {
        topList.clear()
        if (data != null) {
            topList.addAll(data.list)
        }
        topAdapter?.notifyDataSetChanged()
    }

    override fun getSoltVedioSuc(data: IndexList?) {
        val firstVedio = AppPreferencesManager.get().getBoolean(Constant.IS_FIRST_VEDIO, true)
        if (data != null && data.vedioMsg != null && firstVedio) {
            AppPreferencesManager.get().put(Constant.IS_FIRST_VEDIO, false)
            LocalVedioManager.startVedioDetailActivityForType(requireActivity(), data.vedioMsg)
        } else {
            if (UserManager.getInstance().newFlag && !UserManager.getInstance().vipFlag) {
//                homePresenter.getRecommendVedio()

                val bundle = Bundle()
                bundle.putBoolean(VipActivity.IS_MAIN, true)
                readyGo(VipActivity::class.java, bundle)
            }
        }
    }

    override fun getRecommendVedioSuc(data: RecoBean?) {
        this.recommendVedioBean = data
    }


    override fun showTurnSuc(data: NineShowBean) {
        AppPreferencesManager.get().put(Constant.LUCKY_FLAG, data.isShow)

        if (!data.isShow || UserManager.getInstance().vipFlag) {
            ll_lucky.visibility = View.GONE
            return
        } else {
            ll_lucky.visibility = View.VISIBLE
            context?.let { GlideUtils.loadRoundImageViewGif(it, R.drawable.ic_nine, iv_lucky_gif) }
        }

        val complete = data.complete
        val need = data.need
        if (complete >= need) {
            tv_lucky_status.text = SpanUtils()
                    .append("可领取")
                    .setForegroundColor(resources.getColor(R.color.apk_uninstalled))
                    .create()
        } else {
            tv_lucky_status.text = SpanUtils()
                    .append(complete.toString())
                    .setForegroundColor(resources.getColor(R.color.red))
                    .append("/")
                    .append(need.toString())
                    .create()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
//        if (isHidden) {
//            vpAdapter?.getFragments()?.get(mSelectTabIndex)?.onPause()
//        } else {
//            vpAdapter?.getFragments()?.get(mSelectTabIndex)?.onResume()
//        }
    }

    override fun onFragmentResume(firstResume: Boolean) {
        super.onFragmentResume(firstResume)

        vpAdapter?.getFragments()?.get(mSelectTabIndex)?.onResume()
    }

    override fun onPause() {
        super.onPause()
        vpAdapter?.getFragments()?.get(mSelectTabIndex)?.onPause()
    }

    /**
     * 展示推荐弹窗
     */
    private fun showRecommendAct() {
//        if (data == null || data.vedio3 == null) return


        if (UserManager.getInstance().newFlag && !UserManager.getInstance().vipFlag) {
            // 1、第一次打开app并关闭付费页进首页时出现一次
            val mainFirstRecommend =
                    AppPreferencesManager.get().getBoolean(Constant.MAIN_FIRST_RECOMMEND, false)
            if (!mainFirstRecommend) {
                if (AppConfig.enterVipAct) {
                    AppConfig.enterVipAct = false
                    AppPreferencesManager.get().put(Constant.MAIN_FIRST_RECOMMEND, true)

                    Handler(Looper.getMainLooper()).postDelayed({
                        AppPreferencesManager.get().put(Constant.VEDIO_MAIN_COUNT, 0)

                        readyGo(RecommendBannerActivity::class.java)
                    }, 300)

                    return
                }

            }

            // 2、每3次弹出推荐剧
            val adCount = AppPreferencesManager.get().getInt(Constant.VEDIO_MAIN_COUNT, 0)
            AppPreferencesManager.get().put(Constant.VEDIO_MAIN_COUNT, adCount + 1)
            if (mainFirstRecommend && adCount >= 3) {
                Handler(Looper.getMainLooper()).postDelayed({
                    AppPreferencesManager.get().put(Constant.VEDIO_MAIN_COUNT, 0)

                    readyGo(RecommendBannerActivity::class.java)
                }, 300)
            }

//                // 2、用户第一次打开app未签约付费，而是看了十次广告以上的，则在下一次打开app时关闭启动付费页面后弹出推荐弹框一次
//                val mainTwoRecommend =
//                    AppPreferencesManager.get().getBoolean(Constant.MAIN_TWO_RECOMMEND, false)
//                val adCount = AppPreferencesManager.get().getInt(Constant.VEDIO_AD_COUNT, 0)
//                if (!mainTwoRecommend && adCount > data.vedio3.adShowCount) {
//                    AppPreferencesManager.get().put(Constant.MAIN_TWO_RECOMMEND, true)
//                    Handler(Looper.getMainLooper()).postDelayed({
//                        val bundle = Bundle()
//                        bundle.putString(Constant.RECOMMEND_BEAN, JsonUtil.toJson(data.vedio3))
//                        readyGo(RecommendActivity::class.java, bundle)
//                    }, 300)
//                }

        }

    }

    fun ViewPager2.desensitization() {
        //动态设置ViewPager2 灵敏度
        try {
            val recyclerViewField: Field = ViewPager2::class.java.getDeclaredField("mRecyclerView")
            recyclerViewField.isAccessible = true
            val recyclerView = recyclerViewField.get(this) as RecyclerView
            val touchSlopField: Field = RecyclerView::class.java.getDeclaredField("mTouchSlop")
            touchSlopField.isAccessible = true
            val touchSlop = touchSlopField.get(recyclerView) as Int
            touchSlopField.set(recyclerView, touchSlop * 3) //6 is empirical value
        } catch (ignore: java.lang.Exception) {
        }
    }
}