package com.dlc.chemical.ui.use

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.dlc.chemical.databinding.ActivityUseWeightBinding
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.BaseCountDownActivity
import com.dlc.chemical.ui.common.ExtraParam
import com.dlc.chemical.ui.common.ModuleEnum
import com.dlc.chemical.ui.common.SteelyardVideoActivity
import com.dlc.chemical.ui.msds.MsdsDetailActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.UseReq
import com.rc.httpcore.vo.response.ChemicalBean
import org.greenrobot.eventbus.EventBus

/**
 * info
 *
 * @author ReiChin_
 */
class UseWeightActivity : BaseCountDownActivity<ActivityUseWeightBinding>(),
    TitleBar.TitleListener {

    companion object {
        private const val REQ_STEELYARD_VIDEO = 10
    }

    private lateinit var mChemicalBean: ChemicalBean

    override fun beforeSetContentView() {
        mChemicalBean = intent.getParcelableExtra("chemicalBean")!!
    }

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

    @SuppressLint("SetTextI18n")
    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setTitleInfoFromSp()

        // MSDS
        viewBinding.msds.setOnClickListener {
            if (mChemicalBean.hazardId.isNullOrEmpty()) {
                showToast("暂无MSDS信息")
                return@setOnClickListener
            }
            MsdsDetailActivity.startAction(this, mChemicalBean.hazardId)
        }

        // 取消
        viewBinding.cancel.setOnClickListener {
            finish()
        }

        // 确定
        viewBinding.save.setOnClickListener {
            dispatchSaveClicked()
        }
    }

    private fun dispatchSaveClicked() {
        val extraParam = ExtraParam(
            chemicalName = mChemicalBean.chemicalName, // 化学品名称
            tareWeight = mChemicalBean.tare, // 容器重量
            outUsages = mChemicalBean.outUsages // 剩余库存量
        )
        val intent = Intent(this, SteelyardVideoActivity::class.java)
        intent.putExtra("moduleEnum", ModuleEnum.USE)
        intent.putExtra("extraParam", extraParam)
        intent.putExtra("chemicalUnit", mChemicalBean.chemicalUnit)
        startActivityForResult(intent, REQ_STEELYARD_VIDEO)
    }

    private fun callUseApi(weight: String, joinType: String, remoteFileUrl: String) {
        showLoading("保存中...")
        val param = UseReq().apply {
            stockId = mChemicalBean.id
            collectStockNum = weight
            outType = joinType
            outVideo = remoteFileUrl
            outOneUser = intent.getStringExtra("oneUser")
            outTwoUser = intent.getStringExtra("twoUser")
            lockLogId = intent.getStringExtra("lockLogId")
        }
        val disposable = ApiRepository.addUserecord(param)
            .subscribe({
                dismissLoading()
                // 进入领用完成画面
                // 无智能锁：MainActivity -> TagScanActivity -> UseActivity -> UseWeightActivity(finish) -> UseActivity
                // 有智能锁：MainActivity -> QueryChemicalsActivity -> UseActivity -> UseWeightActivity(finish) -> UseActivity
                EventBus.getDefault().post(UseCompletedEvent(weight))
                finish()
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        // 名称
        viewBinding.chemicalName.text = mChemicalBean.chemicalName
        // 别名
        viewBinding.anotherName.text = mChemicalBean.anotherName
        // 分类
        viewBinding.classifyName.text = mChemicalBean.classifyName
        // 编号
        viewBinding.chemicalNum.text = mChemicalBean.chemicalNum
        // CAS号
        viewBinding.casNum.text = mChemicalBean.casNum
        // 形态
        viewBinding.chemicalShape.text = mChemicalBean.chemicalShapeName
        // 纯度
        viewBinding.purity.text = mChemicalBean.purity
        // 容量规格
        viewBinding.chemicalAmount.text =
            "${mChemicalBean.chemicalAmount ?: ""}${mChemicalBean.chemicalAmountUnit ?: ""}"
        // 容器规格
        viewBinding.tare.text = if ("g" == mChemicalBean.chemicalUnit) "${mChemicalBean.tare ?: "0.0"}g" else "--"
        // 所在位置
        viewBinding.cabinetName.text = mChemicalBean.cabinetName
        // 负责人
        viewBinding.safeUserName.text = mChemicalBean.safeUserName
        // 过期时间
        viewBinding.expirationTime.text = "${mChemicalBean.expirationTime ?: ""} | 30天前提醒"
        // 库存净重
        viewBinding.suttle.text = "${mChemicalBean.suttle ?: "0.0"}${mChemicalBean.chemicalUnit ?: "g"}"
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQ_STEELYARD_VIDEO -> {
                if (RESULT_OK == resultCode) {
                    data ?: return
                    val weight = data.getStringExtra("weight")!!
                    val joinType = data.getStringExtra("joinType")!!
                    val remoteFileUrl = data.getStringExtra("remoteFileUrl")!!
                    callUseApi(weight, joinType, remoteFileUrl)
                }
            }
        }
    }

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

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

}