package com.duben.microtribe.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.duben.microtribe.R
import com.duben.microtribe.ad.express.ExpressAdCallback
import com.duben.microtribe.ad.express.MainExpressManager
import com.duben.microtribe.common.Constant
import com.duben.microtribe.manager.LocalVedioManager
import com.duben.microtribe.mvp.model.*
import com.duben.microtribe.mvp.presenters.PicContentPresenter
import com.duben.microtribe.mvp.views.PicContentView
import com.duben.microtribe.ui.fragment.base.LazyLoadBaseFragment
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.duben.microtribe.common.AppConfig
import com.duben.microtribe.ui.adapter.NewHotStyleAdapter
import com.duben.microtribe.utils.CommonUtils
import kotlinx.android.synthetic.main.fragment_movie.*

class MovieFragment : LazyLoadBaseFragment(), PicContentView, OnLoadMoreListener {

    private var mType = 0
    private var mPosition = 0 // 首页-第一个tab-第一个recyclerview Item

    companion object {
        private const val VIDEO_TYPE = "VIDEO_TYPE"
        private const val VIDEO_POSITION = "VIDEO_POSITION"

        fun newInstance(type: Int, position: Int): Fragment {
            val args = Bundle()
            args.putInt(VIDEO_TYPE, type)
            args.putInt(VIDEO_POSITION, position)
            val fragment = MovieFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private val picContentPresenter by lazy { PicContentPresenter() }

    private var hotPage = 1 // 分页
    private var hotPageSize = Constant.PAGE_SIZE // 分页

    private lateinit var hotStyleAdapter: NewHotStyleAdapter

    override fun getContentViewLayoutID() = R.layout.fragment_movie

    override fun initViewsAndEvents() {
        picContentPresenter.attachView(this)

        initView()
        initListener()

        arguments?.let {
            mType = it.getInt(VIDEO_TYPE, mType)
            mPosition = it.getInt(VIDEO_POSITION, mPosition)
        }
    }

    override fun onResume() {
        super.onResume()
//        hotPageSize = if (UserManager.getInstance().vipFlag) 12 else 9
        hotPageSize = 9
        onRefresh()
    }

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

    fun onRefresh() {
        if (AppConfig.fragmentClickFlag == Constant.FRAGMENT_CLICK_ONE) {
            println("mcg _______")
            hotPage = 1
            srlMainPage.resetNoMoreData()
            MainExpressManager.instance.destroy()
            loadAd()
            picContentPresenter.getHomePageImageList(mType, hotPage, hotPageSize)
        }

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        hotPage = ++hotPage
        picContentPresenter.getHomePageImageList(mType, hotPage, hotPageSize)
    }

    override fun getHomePageImageListSuc(data: BannerList) {
        if (activity == null || requireActivity().isFinishing) {
            srlMainPage?.finishRefresh(true)
            return
        }

        if (::hotStyleAdapter.isInitialized) {
            if (hotPage == 1) {
                srlMainPage.finishRefresh(true)
                hotStyleAdapter.setNewInstance(getAdapterData(data.list))
            } else {
                if (data.list.size < hotPageSize) {
                    srlMainPage.finishLoadMoreWithNoMoreData()
                } else {
                    loadAd()
                    srlMainPage.finishLoadMore()
                }
                hotStyleAdapter.addData(getAdapterData(data.list))
            }
        }
    }

    override fun getHomePageImageListFail() {}

    private fun initView() {
        rv_pic_list.layoutManager = LinearLayoutManager(context)
        hotStyleAdapter = NewHotStyleAdapter()
        hotStyleAdapter.animationEnable = false
        rv_pic_list.adapter = hotStyleAdapter
        val emptyView =
                LayoutInflater.from(requireContext()).inflate(R.layout.item_empty_data, null)
        hotStyleAdapter.setEmptyView(emptyView)
        hotStyleAdapter.setOnCustomChildClickListener(object :
                NewHotStyleAdapter.OnCustomChildClickListener {
            override fun onCustomChildClick(view: View, vedioBean: VedioBean) {
                LocalVedioManager.startVedioDetailActivityForType(
                        requireActivity(),
                        vedioBean
                )
            }
        })
    }

    private fun initListener() {
        srlMainPage.setEnableRefresh(false)
        srlMainPage.setOnLoadMoreListener(this)
    }

    private fun getAdapterData(list: List<VedioBean>): MutableList<VideoMultiItemEntity3> {
        val data = mutableListOf<VideoMultiItemEntity3>()
        val subList = CommonUtils.getSubList(3, list)
        for (itemEntity3s in subList) {
            data.add(VideoMultiItemEntity3(MULTI_ITEM_1, itemEntity3s, null))
        }
        return data
    }

    private fun loadAd() {
        MainExpressManager.instance.loadAd(object : ExpressAdCallback {
            override fun loadSuccess(adView: FrameLayout?) {

            }

            override fun renderSuccess(adView: FrameLayout?): Boolean {
                adView?.let { addAdView(it) }
                return false
            }

            override fun loadFail() {
            }
        })
    }

    private fun addAdView(adView: FrameLayout) {
        // 默认每各9个加1个
        var insertIndex = 3

        val allData = hotStyleAdapter.data
        if (allData != null && allData.size > 0) {
            for (i in allData.size - 1 downTo 0) {
                if (allData[i].itemType == MULTI_ITEM_3) {
                    insertIndex += 4
                }
            }
            if (insertIndex >= allData.size) {
                insertIndex = allData.size
            }

            if (allData[allData.lastIndex].itemType == MULTI_ITEM_3) return

            val data = VideoMultiItemEntity3(MULTI_ITEM_3, null, adView)
            hotStyleAdapter.addData(insertIndex, data)
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        MainExpressManager.instance.destroy()
    }

}