package com.dlc.laboratory.ui.safety

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.eboard.R
import com.dlc.eboard.databinding.FragmentSafetyRegulationListBinding
import com.dlc.eboard.ui.rule.SafetyRegulationDetailActivity
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.core.ui.widget.decoration.NoLastLineItemDecoration
import com.rc.core.util.ScreenAdapter
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.SafeBook

/**
 * 实验室安全制度-列表
 *
 * @author ReiChin_
 */
class SafetyRegulationListFragment : RcBaseFragment<FragmentSafetyRegulationListBinding>() {

    companion object {
        private const val FIRST_PAGE = 1
        private const val PAGE_SIZE = 15

        const val TAG = "SafetyRegulationListFragment"
    }

    private val mAdapter by lazy { SafetyRegulationAdapter() }

    private var mRefresh = false
    private var mCurrentPage = FIRST_PAGE
    private var mSystemFlag = "1"

    override fun onResume() {
        super.onResume()
        ScreenAdapter.setCustomDensity(requireActivity())
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ) = FragmentSafetyRegulationListBinding.inflate(inflater, container, false)

    override fun initViews(savedInstanceState: Bundle?) {
        // 学校制度
        viewBinding.schoolSystem.setOnClickListener {
            loadData(true, "1")
        }

        // 学院制度
        viewBinding.collegeSystem.setOnClickListener {
            loadData(true, "2")
        }

        // 中心制度
        viewBinding.centerSystem.setOnClickListener {
            loadData(true, "3")
        }

        initRecyclerView()

        if (mAdapter.data.isEmpty()) {
            loadData(true)
        }
    }

    private fun initRecyclerView() {
        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItem(position)
            val intent = Intent(requireContext(), SafetyRegulationDetailActivity::class.java)
            intent.putExtra("data", item)
            requireContext().startActivity(intent)
//            val activity = requireActivity()
//            if (activity is SafetyRegulationActivity) {
//                activity.switchDetailFragment(item)
//            }
        }
        viewBinding.content.layoutManager = LinearLayoutManager(requireContext())
        mAdapter.loadMoreModule.setOnLoadMoreListener {
            val dataSize = mAdapter.data.size
            if (dataSize < PAGE_SIZE) {
                mAdapter.loadMoreModule.loadMoreEnd(false)
            } else {
                if (dataSize % PAGE_SIZE != 0) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mCurrentPage++
                    loadData(false)
                }
            }
        }
        mAdapter.loadMoreModule.isAutoLoadMore = true
        // 当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        mAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
        mAdapter.animationEnable = true
        mAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom)

        NoLastLineItemDecoration(requireContext(), DividerItemDecoration.VERTICAL).apply {
            setDrawable(
                ContextCompat.getDrawable(
                    requireContext(),
                    R.drawable.shape_item_divider
                )!!
            )
        }.let {
            viewBinding.content.addItemDecoration(it)
        }

        viewBinding.content.adapter = mAdapter
    }

    private fun loadData(refresh: Boolean, systemFlag: String = mSystemFlag) {
        mSystemFlag = systemFlag
        if (refresh) {
            mCurrentPage = FIRST_PAGE
        }
        mRefresh = refresh
        showLoading("查询中...")
        val disposable = ApiRepository.safeBookList(mSystemFlag)
            .subscribe({ data ->
                dispatchLoadDataSuccess(data)
            }, { throwable ->
                dispatchLoadDataFailure(throwable)
            })
        addDisposable(disposable)
    }

    private fun dispatchLoadDataSuccess(data: List<SafeBook>?) {
        if (isDetached) return

        dismissLoading()

        if (mRefresh) {
            if (data.isNullOrEmpty()) {
                mAdapter.setEmptyView(R.layout.view_list_empty)
            }
            mAdapter.setNewInstance(data?.toMutableList())
            mAdapter.loadMoreModule.loadMoreComplete()
            if (null == data || data.size < PAGE_SIZE) {
                mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
            }
        } else {
            if (null == data || data.size < PAGE_SIZE) {
                if (null != data) {
                    mAdapter.addData(data)
                }
                mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
            } else {
                mAdapter.addData(data)
                mAdapter.loadMoreModule.loadMoreComplete()
            }
        }
    }

    private fun dispatchLoadDataFailure(throwable: Throwable) {
        if (isDetached) return

        dismissLoading()

        if (mRefresh) {
            mAdapter.setEmptyView(R.layout.view_list_empty)
        } else {
            mCurrentPage = if (mCurrentPage-- < FIRST_PAGE) FIRST_PAGE else mCurrentPage
            mAdapter.loadMoreModule.loadMoreEnd(goneLoadMoreView())
        }
        throwable.printStackTrace()
        showNetError(throwable)
    }

    private fun goneLoadMoreView() = false

}

private class SafetyRegulationAdapter :
    BaseQuickAdapter<SafeBook, BaseViewHolder>(R.layout.item_safety_regulation),
    LoadMoreModule {

    override fun convert(holder: BaseViewHolder, item: SafeBook) {
        holder.setText(R.id.text, item.name)
    }

}