package com.dlc.chemical.ui.operate

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityOperateRecordBinding
import com.dlc.chemical.ui.common.CommonListActivity
import com.dlc.chemical.ui.common.PageQuickAdapter
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.OperRecordReq
import com.rc.httpcore.vo.response.AioUserecordVo
import io.reactivex.disposables.Disposable

/**
 * 操作记录
 *
 * @author ReiChin_
 */
class OperateRecordActivity : CommonListActivity<AioUserecordVo, ActivityOperateRecordBinding>(),
    TitleBar.TitleListener {

    override val mAdapter by lazy { OperateRecordAdapter() }
    override val mSrlRefresh by lazy { viewBinding.swipeRefreshLayout }
    override val mRvContent by lazy { viewBinding.recyclerView }
    override val mTvPageInfo by lazy { viewBinding.pageInfo }
    override val mTvPagePrev by lazy { viewBinding.pagePrev }
    override val mTvPageNext by lazy { viewBinding.pageNext }

    override fun createViewBinding() = ActivityOperateRecordBinding.inflate(layoutInflater)

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

        viewBinding.tagUse.setOnClickListener {
            switchTarget(true)
        }
        viewBinding.tagRevert.setOnClickListener {
            switchTarget(false)
        }
        switchTarget(true)
    }

    private fun switchTarget(targetUse: Boolean) {
        viewBinding.tagUse.isChecked = targetUse
        viewBinding.tagRevert.isChecked = !targetUse
        viewBinding.listHeaderUse.visibility = if (targetUse) View.VISIBLE else View.GONE
        viewBinding.listHeaderRevert.visibility = if (targetUse) View.GONE else View.VISIBLE
        mAdapter.mViewType =
            if (targetUse) OperateRecordAdapter.VIEW_TYPE_USE else OperateRecordAdapter.VIEW_TYPE_REVERT
        loadData(true)
    }

    override fun queryData(): Disposable? {
        val param = OperRecordReq()
        param.pageNum = mCurrentPage
        param.pageSize = PAGE_SIZE
        // 1 领用（默认），2 归还
        param.type = if (viewBinding.tagUse.isChecked) "1" else "2"

        return ApiRepository.queryRecordList(param)
            .subscribe({
                dismissLoading()
                dispatchLoadDataSuccess(it.rows, it.total)
            }, { throwable ->
                dismissLoading()
                dispatchLoadDataFailure(throwable)
            })
    }

    override fun createItemDecoration(): RecyclerView.ItemDecoration? = null

    override fun onHomeViewClicked(view: View) {
        finish()
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

}

class OperateRecordAdapter : PageQuickAdapter<AioUserecordVo>(0) {

    companion object {
        const val VIEW_TYPE_USE = 1
        const val VIEW_TYPE_REVERT = 2
    }

    var mViewType: Int = VIEW_TYPE_USE

    override fun getDefItemViewType(position: Int): Int {
        return mViewType
    }

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val layoutId =
            if (mViewType == VIEW_TYPE_USE) R.layout.item_operate_record_use
            else R.layout.item_operate_record_revert
        return createBaseViewHolder(parent, layoutId)
    }

    override fun convert(holder: BaseViewHolder, item: AioUserecordVo) {
        if (mViewType == VIEW_TYPE_USE) {
            convertUse(holder, item)
        } else {
            convertRevert(holder, item)
        }
    }

    private fun convertUse(holder: BaseViewHolder, item: AioUserecordVo) {
        holder.setText(R.id.cabinetName, item.cabinetName)
            .setText(R.id.chemicalNum, item.chemicalNum)
            .setText(R.id.chemicalName, item.chemicalName)
            .setText(
                R.id.collectStockNum,
                "${item.collectStockNum ?: "0.0"}${item.chemicalUnit ?: "g"}"
            )
            .setText(R.id.collectTime, item.collectTime)
            .setText(R.id.useStatus, item.decodeUseStatus())
            .setTextColor(R.id.useStatus, formatUseStatusTextColor(item.useStatus))
    }

    /*
     * 1-使用中，0-已归还，2-超时未归还
     * 使用中：#2296FB 超时未归还：#FF3131 已归还：#333333
     */
    private fun formatUseStatusTextColor(useStatus: String?): Int {
        return when (useStatus) {
            "0" -> Color.parseColor("#FF333333")
            "1" -> Color.parseColor("#FF2296FB")
            "2" -> Color.parseColor("#FFFF3131")
            else -> Color.parseColor("#FF333333")
        }
    }

    private fun convertRevert(holder: BaseViewHolder, item: AioUserecordVo) {
        val chemicalUnit = item.chemicalUnit ?: "g"
        holder.setText(R.id.cabinetName, item.cabinetName)
            .setText(R.id.chemicalNum, item.chemicalNum)
            .setText(R.id.chemicalName, item.chemicalName)
            .setText(
                R.id.returnStockNum,
                "${item.collectStockNum ?: "0.0"}${chemicalUnit} / ${item.returnStockNum ?: "0.0"}${chemicalUnit}"
            )
            .setText(R.id.useStockNum, item.useStockNum ?: "0.0${chemicalUnit}")
            .setText(R.id.returnTime, item.returnTime)
    }

}