package com.yidianling.medical.im

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.base.config.HttpConfig
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.Utils
import com.yidianling.im.R
import com.yidianling.medical.im.adapter.MedicalSystemListAdapter
import com.yidianling.medical.widgets.LoadMoreView
import com.yidianling.uikit.custom.http.ServiceImpl
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.medical_system_list_activity.*
import kotlinx.coroutines.*
import java.util.*

/**
 * 系统消息列表
 * @author liupeng
 * */
class MedicalSystemListActivity : BaseActivity(), SwipeRefreshLayout.OnRefreshListener,
    BaseQuickAdapter.RequestLoadMoreListener {
    private lateinit var mEmptyView: View
    private lateinit var mAdapter: MedicalSystemListAdapter

    companion object {
        private var currPage: Int = 1
        private const val pageSize: Int = 20

        @JvmStatic
        fun start(context: Context) {
            val starter = Intent(context, MedicalSystemListActivity::class.java)
            context.startActivity(starter)
        }
    }

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

    override fun initDataAndEvent() {
        initStatus()
        iv_back.setOnClickListener { finish() }
        mEmptyView = LayoutInflater.from(this@MedicalSystemListActivity).inflate(R.layout.list_empty_view, null, false)
        mAdapter = MedicalSystemListAdapter()
        system_list.layoutManager =
            LinearLayoutManager(this@MedicalSystemListActivity, LinearLayoutManager.VERTICAL, false)
        system_list.adapter = mAdapter

        mAdapter.setOnItemClickListener { _, view, position ->
            if (Utils.isFastClick()) {
                //防止连击
                return@setOnItemClickListener
            }
            val itemBean = mAdapter.data[position]
            when (itemBean.bizType) {
                "1" -> {
                    //1-问诊订单
                    NewH5Activity.start(
                        view!!.context, H5Params(
                            "${HttpConfig.MEDICAL_H5URL}ct/inquiry/order/details?orderId=${itemBean?.bizId}&hideNavBar=1",
                            null
                        )
                    )

                }
                "2" -> {
                    //2-处方单
                    NewH5Activity.start(
                        view!!.context, H5Params(
                            "${HttpConfig.MEDICAL_H5URL}ct/prescription/details?recipeId=${itemBean?.bizId}",
                            null
                        )
                    )
                }
                "3" -> {
                    // 3-药品订单
                    NewH5Activity.start(
                        view!!.context, H5Params(
                            "${HttpConfig.MEDICAL_H5URL}ct/drug/order/details?drugOrderId=${itemBean?.bizId}&hideNavBar=1",
                            null
                        )
                    )
                }
            }
            mAdapter.data[position].read = true
            mAdapter.notifyDataSetChanged()
            itemBean?.msgId?.let { setSystemRead(it) }

        }
        mAdapter.setLoadMoreView(LoadMoreView())
        mAdapter.setOnLoadMoreListener(this@MedicalSystemListActivity, system_list)
        system_swipe_refresh_layout?.setOnRefreshListener(this)

        system_swipe_refresh_layout?.setColorSchemeColors(
            ContextCompat.getColor(this@MedicalSystemListActivity, R.color.platform_main_theme)
        )
        system_swipe_refresh_layout?.setProgressViewOffset(false, 0, 200)
        currPage = 1
        getSystemList()

    }

    /**
     * 系统消息阅读
     * */
    private fun setSystemRead(msgId: Int) {
        ServiceImpl.instance.systemRead(msgId)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe()
    }

    @SuppressLint("CheckResult")
    private fun getSystemList() {
        ServiceImpl.instance.getSystemPageList(currPage, pageSize, null)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->
                if ("200" == response.code) {
                    system_swipe_refresh_layout.isRefreshing = false

                    val list = response.data.rows
                    if (currPage == 1) {
                        //第一页数据
                        if (list.isNotEmpty()) {
                            if (list.size < pageSize) {
                                mAdapter.setNewData(list)
                                mAdapter.removeAllFooterView()
                                mAdapter.loadMoreEnd(false)
                            } else {
                                currPage++
                                mAdapter.setNewData(list)
                                mAdapter.removeAllFooterView()
                                mAdapter.loadMoreComplete()
                            }
                        } else {
                            mAdapter.loadMoreEnd(false)
                            val netError = mEmptyView.findViewById<TextView>(R.id.im_net_error)
                            netError.text = "暂无系统消息～"
                            mAdapter.emptyView = mEmptyView
                        }
                    } else {
                        //非第一页数据
                        if (list.isEmpty()) {
                            mAdapter.loadMoreEnd(false)
                        } else {
                            if (list.size < pageSize) {
                                mAdapter.addData(list)
                                mAdapter.loadMoreEnd(false)
                            } else {
                                mAdapter.addData(list)
                                if (currPage == response.data.totalPage) {
                                    mAdapter.loadMoreEnd(false)
                                } else {
                                    currPage++
                                    mAdapter.loadMoreComplete()
                                }
                            }
                        }
                    }
                } else {
                    system_swipe_refresh_layout.isRefreshing = false
                    mAdapter.loadMoreFail()
                    mAdapter.emptyView = mEmptyView
                }
            }, { e ->
                e.printStackTrace()
                system_swipe_refresh_layout.isRefreshing = false
                mAdapter.loadMoreFail()
                val netError = mEmptyView.findViewById<TextView>(R.id.im_net_error)
                val reLoad = mEmptyView.findViewById<TextView>(R.id.im_reLoad)
                netError.text = "网络异常，请稍后再试"
                reLoad.visibility = View.VISIBLE
                mAdapter.emptyView = mEmptyView
            })
    }


    override fun onRefresh() {
        currPage = 1
        getSystemList()

    }

    override fun onLoadMoreRequested() {
        getSystemList()
    }

    private fun initStatus() {
        StatusBarUtils.setTransparentForImageView(this@MedicalSystemListActivity, null)
        StatusBarUtils.statusBarLightMode(this@MedicalSystemListActivity)
    }


}