package com.duben.happyplaylet.ui.fragment

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 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.happyplaylet.R
import com.duben.happyplaylet.ad.AdManager
import com.duben.happyplaylet.ad.banner.BannerManager
import com.duben.happyplaylet.common.AppConfig
import com.duben.happyplaylet.common.Constant
import com.duben.happyplaylet.manager.LocalVedioManager
import com.duben.happyplaylet.manager.TrackManager
import com.duben.happyplaylet.manager.UserManager
import com.duben.happyplaylet.mvp.model.*
import com.duben.happyplaylet.mvp.presenters.HomePresenter
import com.duben.happyplaylet.mvp.views.HomeView
import com.duben.happyplaylet.ui.activitys.NineActivity
import com.duben.happyplaylet.ui.activitys.VipActivity
import com.duben.happyplaylet.ui.adapter.HomeVideoPageAdapter
import com.duben.happyplaylet.ui.adapter.ImageTitleAdapter
import com.duben.happyplaylet.ui.adapter.TopAdapter
import com.duben.happyplaylet.ui.fragment.base.LazyLoadBaseFragment
import com.duben.happyplaylet.utils.AppPreferencesManager
import com.duben.happyplaylet.utils.SpanUtils
import com.duben.library.utils.GlideUtils
import com.duben.library.utils.nodoubleclick.AntiShake
import kotlinx.android.synthetic.main.fragment_main.*
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 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()

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

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

    /**
     * 跳转到主页面
     */
    private fun goToMainActivity() {
        val firstVedio = AppPreferencesManager.get().getBoolean(Constant.IS_FIRST_VEDIO, false)
        if (firstVedio) {
            if (UserManager.getInstance().newFlag && !UserManager.getInstance().vipFlag) {
                readyGo(VipActivity::class.java)
            }
        } else {
            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)
            }

            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()
            }
        }
    }

    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.get(position)
                    )
                }
            }
        })


        vpAdapter = HomeVideoPageAdapter(tabsData, this)
        vp2.adapter = vpAdapter
        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 ->
                    LocalVedioManager.startVedioDetailActivityForType(
                        requireActivity(),
                        data.list.get(position)
                    )
                }
        }
    }

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

    override fun getSoltVedioSuc(data: IndexList?) {
        AppPreferencesManager.get().put(Constant.IS_FIRST_VEDIO, true)
        if (data != null && data.vedioMsg != null) {
            LocalVedioManager.startVedioDetailActivityForType(requireActivity(), data.vedioMsg)
        } else {
            if (UserManager.getInstance().newFlag && !UserManager.getInstance().vipFlag) {
                readyGo(VipActivity::class.java)
            }
        }
    }

    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
        }

        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()
        }
    }

}