package fragment

import adapter.ArticleHomeItemAdapter
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.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseFragment
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
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 mRvArticleContent: RecyclerView
    private lateinit var mLlEmptyLayout: LinearLayout

    private var mCurrentPage = 1
    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 layoutResId(): Int {
        return R.layout.article_fragment_layout
    }

    override fun initDataAndEventLazy() {

    }
    override fun initDataAndEvent() {
        mSmartRefreshLayout = rootView.findViewById(R.id.smart_refresh_layout)

        mRvArticleContent = rootView.findViewById(R.id.rv_article_content)
        mLlEmptyLayout = rootView.findViewById(R.id.ll_empty)

        mSmartRefreshLayout.setRefreshHeader(ClassicsHeader(activity))
        mSmartRefreshLayout.setRefreshFooter(ClassicsFooter(activity))

        mAdapter = ArticleHomeItemAdapter(activity as Context)
        mAdapter.setOnItemClickListener(object : ArticleHomeItemAdapter.OnItemClickListener {
            override fun onItemClick(articleBean: ArticleBean) {
                ActionCountUtils.record("article_list_main_page","article_list_detail_click")
                YDLRouterManager.router(
                    IYDLRouterConstant.ROUTER_H5_H5,
                    YDLRouterParams().putExtra(IYDLRouterConstant.EXTRA_URL, articleBean.listAllUrl!!), ""
                )
            }
        })
        mRvArticleContent.layoutManager =
            LinearLayoutManager(activity, RecyclerView.VERTICAL, false)
        mRvArticleContent.adapter = mAdapter

        mSmartRefreshLayout.autoRefresh()

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


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

    }

    override fun onResume() {
        super.onResume()
        mSmartRefreshLayout.autoRefresh()
    }



    private fun getRecommendArticleList(isRefresh: Boolean = true, isLoadMore: Boolean = false) {
        ArticleHttp.getInstance().getRecommendArticleList(
            perPageRows = 10, page = if (isRefresh) {
                1
            } else {
                mCurrentPage + 1
            }
        )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if (it.code == "200" && it.data != null) {
                    if (it.data.list.isNullOrEmpty()) {
                        mLlEmptyLayout.visibility = View.VISIBLE
                        mRvArticleContent.visibility = View.GONE
                    } else {
                        mLlEmptyLayout.visibility = View.GONE
                        mRvArticleContent.visibility = View.VISIBLE
                        mCurrentPage = it.data.currentPage
                        mTotalPage = it.data.totalPage
                        mSmartRefreshLayout.setEnableLoadMore(mCurrentPage<mTotalPage)
                        val articles = it.data.list
                        if (articles != null) {
                            if (isRefresh) {
                                mAdapter.setData(articles)
                            }
                            if (isLoadMore) {
                                mAdapter.addData(articles)
                            }
                        }
                    }
                } else {
                    mLlEmptyLayout.visibility = View.VISIBLE
                    mRvArticleContent.visibility = View.GONE
                }
            }
    }



    private fun getArticleList(isRefresh: Boolean = true, isLoadMore: Boolean = false) {
        ArticleHttp.getInstance().getArticleList(
            perPageRows = 10,
            page = if (isRefresh) {
                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
                        mRvArticleContent.visibility = View.GONE
                    } else {
                        mLlEmptyLayout.visibility = View.GONE
                        mRvArticleContent.visibility = View.VISIBLE
                        mCurrentPage = it.data.currentPage
                        mTotalPage = it.data.totalPage
                        mSmartRefreshLayout.setEnableLoadMore(mCurrentPage<mTotalPage)
                        val articles = it.data.list
                        if (articles != null) {
                            if (isRefresh) {
                                mAdapter.setData(articles)
                            }
                            if (isLoadMore) {
                                mAdapter.addData(articles)
                            }
                        }
                    }
                } else {
                    mLlEmptyLayout.visibility = View.VISIBLE
                    mRvArticleContent.visibility = View.GONE
                }
            }, {
                mLlEmptyLayout.visibility = View.VISIBLE
                mRvArticleContent.visibility = View.GONE
            })
    }

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

}