package fragment

import adapter.ArticleHomeItemAdapter
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.footer.BallPulseFooter
import com.scwang.smart.refresh.header.BezierRadarHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.wrapper.RefreshFooterWrapper
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydlcommon.base.BaseFragment
import com.yidianling.article.R
import data.ArticleBean
import http.ArticleHttp
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class ArticleHomeFragment : BaseFragment() {

    private lateinit var mSmartRefreshLayout: SmartRefreshLayout
    private lateinit var mLvArticleContent: RecyclerView
    private lateinit var mLlEmptyLayout: LinearLayout

    private var isRefreshing: Boolean = false
    private var isLoadingMore: Boolean = false

    private var mCurrentPage = 0
    private var mTotalPage = 0

    private var mTagId: Int = 0

    private lateinit var mAdapter: ArticleHomeItemAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTagId = arguments?.getInt(KEY_ARTICLE_TAG_ID, 0) ?: 0
    }

    override fun initDataAndEvent() {
        mSmartRefreshLayout = rootView.findViewById(R.id.smart_refresh_layout)
        mLvArticleContent = rootView.findViewById(R.id.rv_article_content)
        mLlEmptyLayout = rootView.findViewById(R.id.ll_empty)

        mSmartRefreshLayout.setRefreshHeader(BezierRadarHeader(activity))
        mSmartRefreshLayout.setRefreshFooter(BallPulseFooter(activity))

        mSmartRefreshLayout.autoRefresh()

        mAdapter = ArticleHomeItemAdapter(activity as Context)
        mAdapter.setOnItemClickListener(object : ArticleHomeItemAdapter.OnItemClickListener {
            override fun onItemClick(articleBean: ArticleBean) {
                YDLRouterManager.router("ydl-user://h5/h5?params={'url':'${articleBean.hUrl}'}")
            }
        })
        mLvArticleContent.layoutManager =
            LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
        mLvArticleContent.adapter = mAdapter

        isRefreshing = true

        mSmartRefreshLayout.setOnRefreshListener {
            isRefreshing = true
            if (mTagId == 0){
                getRecommendArticleList()
            }else{
                getArticleList(isRefreshing = true, isLoadMore = false)
            }
            it.finishRefresh()
        }

        mSmartRefreshLayout.setOnLoadMoreListener {
            isLoadingMore = true
            if (mTagId == 0){
                getRecommendArticleList()
            }else{
                getArticleList(isRefreshing = false, isLoadMore = true)
            }
            it.finishLoadMore()
        }

    }

    override fun initDataAndEventLazy() {

    }

    override fun layoutResId(): Int {
        return R.layout.article_fragment_layout
    }

    @SuppressLint("CheckResult")
    private fun getRecommendArticleList(loadMore: Boolean = false) {
        ArticleHttp.getInstance().getRecommendArticleList(
            perPageRows = 10, page = mCurrentPage
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (it.code == "200" && it.data != null) {
                    if (it.data.list.isNullOrEmpty()) {
                        mLlEmptyLayout.visibility = View.VISIBLE
                        mLvArticleContent.visibility = View.GONE
                    } else {
                        mLlEmptyLayout.visibility = View.GONE
                        mLvArticleContent.visibility = View.VISIBLE

                        val articles = it.data.list
                        if (articles != null) {
                            mAdapter.setData(articles)
                        }

                    }
                }else{
                    mLlEmptyLayout.visibility = View.VISIBLE
                    mLvArticleContent.visibility = View.GONE
                }
            }
    }


    @SuppressLint("CheckResult")
    private fun getArticleList(isRefreshing:Boolean = true,isLoadMore: Boolean = false) {
        ArticleHttp.getInstance().getArticleList(
            perPageRows = 10,
            page = if (isRefreshing) {
                1
            }else{
                mCurrentPage+1
            }, tagId = mTagId
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (it.code == "200" && it.data != null) {
                    if (it.data.list.isNullOrEmpty()) {
                        mLlEmptyLayout.visibility = View.VISIBLE
                        mLvArticleContent.visibility = View.GONE
                    } else {
                        mLlEmptyLayout.visibility = View.GONE
                        mLvArticleContent.visibility = View.VISIBLE

                        mCurrentPage = it.data.currentPage
                        mTotalPage = it.data.totalPage

                        mSmartRefreshLayout.setEnableLoadMore(mCurrentPage<mTotalPage)

                        val articles = it.data.list
                        if (articles != null) {
                            if (isRefreshing){
                                mAdapter.setData(articles)
                            }else{
                                mAdapter.addData(articles)
                            }
                        }
                    }
                }else{
                    mLlEmptyLayout.visibility = View.VISIBLE
                    mLvArticleContent.visibility = View.GONE
                }
            }
    }

    private fun refreshOrLoadingComplete() {
        if (isLoadingMore) {
            isLoadingMore = false
        }
        if (isRefreshing) {
            isRefreshing = false
        }
    }

    companion object {

        const val KEY_ARTICLE_TAG_ID = "key_article_tag_id"

        fun newInstance(tagId: Int): ArticleHomeFragment {
            val args = Bundle()
            args.putInt(KEY_ARTICLE_TAG_ID, tagId)
            val fragment = ArticleHomeFragment()
            fragment.arguments = args
            return fragment
        }
    }

}