package com.dlc.chemical.ui.query

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityQueryChemicalsBinding
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.CommonListActivity
import com.dlc.chemical.ui.common.ModuleEnum
import com.dlc.chemical.ui.common.PageQuickAdapter
import com.dlc.chemical.ui.input.InputStoreActivity
import com.dlc.chemical.ui.output.OutputStoreActivity
import com.dlc.chemical.ui.tag.TagManagementActivity
import com.dlc.chemical.ui.use.UseActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.core.log.RcLog
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.ChemicalReq
import com.rc.httpcore.vo.response.CabinetBean
import com.rc.httpcore.vo.response.ChemicalBean
import io.reactivex.disposables.Disposable

/**
 * 查询化学品
 *
 * @author ReiChin_
 */
class QueryChemicalsActivity : CommonListActivity<ChemicalBean, ActivityQueryChemicalsBinding>(),
    TitleBar.TitleListener {

    override val mAdapter by lazy { QueryChemicalsAdapter(detailText(), byStockQuery()) }
    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 }

    private var mCabinetBean: CabinetBean? = null

    private fun detailText(): String {
        return when (mModuleEnum) {
            ModuleEnum.INPUT_STORE,
            ModuleEnum.USE,
            ModuleEnum.OUTPUT_STORE,
            ModuleEnum.TAG_MANAGEMENT -> "确认"
            ModuleEnum.QUERY -> "详情"
            else -> "详情"
        }
    }

    private fun moduleText(): String {
        return when (mModuleEnum) {
            ModuleEnum.INPUT_STORE,
            ModuleEnum.USE,
            ModuleEnum.OUTPUT_STORE,
            ModuleEnum.TAG_MANAGEMENT -> "选择化学品"
            ModuleEnum.QUERY -> "查询化学品"
            else -> "选择化学品"
        }
    }

    private lateinit var mModuleEnum: ModuleEnum

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

    override fun beforeSetContentView() {
        mModuleEnum = intent.getSerializableExtra("moduleEnum") as ModuleEnum
    }

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        mAdapter.addChildClickViewIds(R.id.detail)

        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

        viewBinding.moduleName.text = moduleText()
        viewBinding.tagGroup.visibility =/*
            if (ModuleEnum.TAG_MANAGEMENT == mModuleEnum) View.VISIBLE else*/ View.GONE

        // 机柜筛选
        viewBinding.selectCabinet.setOnClickListener {
            queryCabinetList { data ->
                val defSelectedBean = mCabinetBean ?: data[0]
                SelectCabinetDialog(this, data, defSelectedBean) { cBean ->
                    mCabinetBean = cBean
                    viewBinding.selectCabinet.text = cBean.cabinetName
                    loadData(true)
                }.show()
            }
        }

        // 查询
        viewBinding.search.setOnClickListener {
            hintKeyBoard()
            loadData(true)
        }
        // 重置
        viewBinding.reset.setOnClickListener {
            viewBinding.keyword.text = null
            viewBinding.selectCabinet.text = "选择机柜"
            mCabinetBean = null

            loadData(true)
        }
        viewBinding.tagRFID.setOnClickListener {
            loadData(true)
        }
        viewBinding.tagQRCode.setOnClickListener {
            loadData(true)
        }
    }

    /*
     * 查询机柜
     */
    private fun queryCabinetList(callback: (data: MutableList<CabinetBean>) -> Unit) {
        showLoading("查询中...")
        val disposable = ApiRepository.queryCabinetList()
            .subscribe({ response ->
                dismissLoading()
                val data = mutableListOf<CabinetBean>()
                data.add(CabinetBean.createDefCabinetBean())
                data.addAll(response)
                callback.invoke(data)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    override fun onResume() {
        super.onResume()
        loadData(true)
    }

    override fun autoLoadData() = false

    override fun queryData(): Disposable? {
        val param = ChemicalReq()
        param.pageNum = mCurrentPage
        param.pageSize = PAGE_SIZE
        param.chemicalName = viewBinding.keyword.text.toString().trim()
        if (CabinetBean.DEF_CABINET_ID != mCabinetBean?.id) {
            param.cabinetId = mCabinetBean?.id
        }
        if (ModuleEnum.USE == mModuleEnum) {
            param.qType = "1"
        }
//        if (ModuleEnum.TAG_MANAGEMENT == mModuleEnum) {
//            param.labelType =
//                if (viewBinding.tagRFID.isChecked) TagType.RFID.type else TagType.QR_CODE.type
//        }

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

    /*
     * 是否查询已入库的化学品
     */
    private fun byStockQuery(): Boolean {
        return when (mModuleEnum) {
            ModuleEnum.INPUT_STORE -> false
            ModuleEnum.TAG_MANAGEMENT -> false
            ModuleEnum.USE -> true
            ModuleEnum.OUTPUT_STORE -> true
            ModuleEnum.QUERY -> true
            else -> true
        }
    }

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

    override fun onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

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

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (mModuleEnum) {
            ModuleEnum.INPUT_STORE -> {
                val intent = Intent(this, InputStoreActivity::class.java)
                intent.putExtra("chemicalBean", item)
                startActivity(intent)
            }
            ModuleEnum.QUERY -> {
                // 进入化学品详情
                val intent = Intent(this, ChemicalsDetailActivity::class.java)
                intent.putExtra("chemicalBean", item)
                startActivity(intent)
            }
            ModuleEnum.TAG_MANAGEMENT -> {
                val intent = Intent(this, TagManagementActivity::class.java)
                intent.putExtra("labelType", item.labelType)
                intent.putExtra("joinId", item.joinId)
                startActivity(intent)
            }
            ModuleEnum.USE -> {
                val intent = Intent(this, UseActivity::class.java)
                RcLog.info("================领用前参数${item.chemicalAmount}")
                intent.putExtra("chemicalBean", item)
                startActivity(intent)
            }
            ModuleEnum.OUTPUT_STORE -> {
                val intent = Intent(this, OutputStoreActivity::class.java)
                intent.putExtra("chemicalBean", item)
                startActivity(intent)
            }
            else -> {
            }
        }
    }

}

class QueryChemicalsAdapter(
    private val detailText: String,
    private val byStockQuery: Boolean
) :
    PageQuickAdapter<ChemicalBean>(R.layout.item_query_chemicals) {

    override fun convert(holder: BaseViewHolder, item: ChemicalBean) {
        holder.setText(R.id.chemicalName, item.chemicalName)
            .setText(R.id.cabinetName, item.cabinetName)
            .setText(R.id.purity, item.purity)
            .setText(
                R.id.chemicalAmount,
                "${item.chemicalAmount ?: ""}${item.chemicalAmountUnit ?: ""}"
            )
            .setText(R.id.classifyName, item.classifyName)
            .setText(R.id.chemicalNum, if (byStockQuery) item.chemicalNum else item.joinNum)
            .setText(R.id.detail, detailText)
    }

}