package com.dlc.eboard.ui.notice

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.dlc.eboard.LabApp
import com.dlc.eboard.databinding.FragmentNoticeBinding
import com.rc.core.ui.fragment.RcLazyFragment
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.NoticeDetailVo

/**
 * 消息通知
 *
 * @author ReiChin_
 */
class NoticeFragment : RcLazyFragment<FragmentNoticeBinding>() {

    private lateinit var mLabId: String

    private var mNoticeList: List<NoticeDetailVo>? = null
    private var mIndex = 0

    companion object {
        fun newInstance(labId: String): NoticeFragment {
            val args = Bundle()
            args.putString("labId", labId)
            val fragment = NoticeFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentNoticeBinding {
        return FragmentNoticeBinding.inflate(inflater, container, false)
    }

    override fun initViews(savedInstanceState: Bundle?) {
        mLabId = requireArguments().getString("labId")!!

        viewBinding.prev.setOnClickListener {
            mNoticeList?.let {
                if (mIndex == 0) {
                    showToast("已经是第一条!")
                } else {
                    showNoticeInfo(it[--mIndex])
                }
            }
        }
        viewBinding.next.setOnClickListener {
            mNoticeList?.let {
                if (it.isNotEmpty()) {
                    if (it.size - 1 == mIndex) {
                        showToast("已经是最后一条!")
                    } else {
                        showNoticeInfo(it[++mIndex])
                    }
                }
            }
        }
    }

    override fun onLoadData() {
        queryNoticeMsgList()
    }

    private fun queryNoticeMsgList() {
        val disposable = ApiRepository.newMsg(LabApp.sLabConfig!!.labId, 1, 20)
            .subscribe({ response ->
                mNoticeList = response
                if (mNoticeList.isNullOrEmpty()) {
                    showNoticeInfo(null)
                } else {
                    showNoticeInfo(mNoticeList!![0])
                }
            }, { throwable ->
                mNoticeList = null
                throwable.printStackTrace()
                showNetError(throwable)
                showNoticeInfo(null)
            })
        addDisposable(disposable)
    }

    private fun showNoticeInfo(data: NoticeDetailVo?) {
        // 显示通知信息：通知发布人，发布时间，通知内容
//        viewBinding.acceptPerson.text = "某某机构"
//        viewBinding.issuePerson.text = data?.createBy
//        viewBinding.issueTime.text = data?.createTime
        viewBinding.noticeContent.text = data?.content
    }

    override fun loadDateCompleted() = !mNoticeList.isNullOrEmpty()

}