package com.dlc.chemical.ui.revert

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.dlc.chemical.ChemicalApp
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityRevertBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.*
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.dlc.chemical.ui.unlock.SelectAuthMethodActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.dlc.chemical.ui.msds.MsdsDetailActivity
import com.rc.core.util.trimEndZero
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.RevertReq
import com.rc.httpcore.vo.response.CabinetLockVo
import com.rc.httpcore.vo.response.ChemicalBean
import com.rc.httpcore.vo.response.LockRespBean
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * 归还化学品
 * MainActivity > TagScanActivity > RevertActivity > SteelyardVideoActivity(finish)
 *  [ > SelectAuthMethodActivity(finish) > ChemicalUnlockActivity(finish)]
 *  > (finish) > RevertCompletedActivity
 *
 * @author ReiChin_
 */
class RevertActivity : BaseCountDownActivity<ActivityRevertBinding>(),
    TitleBar.TitleListener {

    companion object {
        private const val REQ_PERSON_AUTH = 10
        private const val REQ_STEELYARD_VIDEO = 11
        private const val REQ_UNLOCK = 12
    }

    private lateinit var mChemicalBean: ChemicalBean

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

    override fun createViewBinding() = ActivityRevertBinding.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, // 容器重量
            collectStockNum = mChemicalBean.hxpUserecord.collectStockNum // 领用时库存
        )
        val intent = Intent(this, SteelyardVideoActivity::class.java)
        intent.putExtra("moduleEnum", ModuleEnum.REVERT)
        intent.putExtra("extraParam", extraParam)
        intent.putExtra("chemicalUnit", mChemicalBean.chemicalUnit)
        startActivityForResult(intent, REQ_STEELYARD_VIDEO)
    }

    private fun callRevertApi(lockLogId: String? = null) {
        showLoading("保存中...")
        val param = RevertReq().apply {
            id = mChemicalBean.hxpUserecord.id
            returnStockNum = mWeight
            returnType = mJoinType
            returnVideo = mRemoteFileUrl
            backOneUser = mJoinOneUser
            backTwoUser = mJoinTwoUser
            this.lockLogId = lockLogId
        }
        val disposable = ApiRepository.updateUserecord(param)
            .subscribe({
                dismissLoading()
                dispatchRevertSuccess()
            }, { 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天前提醒"
        // 领用净重：领用净重=领用时库存-容器规格
        val tare = if ("g" == mChemicalBean.chemicalUnit) mChemicalBean.tare else "0"
        val useSuttle = try {
            BigDecimal(mChemicalBean.hxpUserecord.collectStockNum)
                .subtract(BigDecimal(tare))
                .setScale(5, RoundingMode.HALF_UP)
                .toPlainString().trimEndZero()
        } catch (e: Exception) { "0" }
        viewBinding.useSuttle.text = "${useSuttle}${mChemicalBean.chemicalUnit ?: "g"}"
    }

    private fun dispatchRevertSuccess() {
        mChemicalBean.returnStockNum = mWeight
        val intent = Intent(this, RevertCompletedActivity::class.java)
        intent.putExtra("chemicalBean", mChemicalBean)
        startActivity(intent)
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQ_PERSON_AUTH -> {
                if (RESULT_OK == resultCode) {
                    val authResult = data?.getBooleanExtra("auth_result", false) ?: false
                    if (authResult) {
                        mJoinOneUser = data?.getStringExtra("joinOneUser")
                        mJoinTwoUser = data?.getStringExtra("joinTwoUser")
                        dispatchRevertAction()
                    }
                }
            }
            REQ_STEELYARD_VIDEO -> {
                if (RESULT_OK == resultCode) {
                    data ?: return
                    mWeight = data.getStringExtra("weight")!!
                    mJoinType = data.getStringExtra("joinType")!!
                    mRemoteFileUrl = data.getStringExtra("remoteFileUrl")!!

                    if ("2" == mChemicalBean.classifyConfig.returnStatus) {
                        // 2-双人双卡
                        val intent = Intent(this, SelectAuthMethodActivity::class.java)
                        intent.putExtra("lockType", LockType.BACK.code)
                        startActivityForResult(intent, REQ_PERSON_AUTH)
                    } else {
                        // 1-单人验证
                        dispatchRevertAction()
                    }
                }
            }
            REQ_UNLOCK -> {
                if (RESULT_OK == resultCode) {
                    data ?: return
                    val lockLogId = data.getStringExtra("lockLogId")
                    callRevertApi(lockLogId)
                }
            }
        }
    }

    private var mJoinOneUser: String? = null
    private var mJoinTwoUser: String? = null

    private var mWeight: String? = null // 化学品重量
    private var mJoinType: String? = null // 入库方式（1 称重，2 录入）
    private var mRemoteFileUrl: String? = null // 视频文件服务器地址

    private fun dispatchRevertAction() {
        if (true == ChemicalApp.sLearnLoginVo?.cabinetLock) {
            // 有智能锁，开锁/关锁流程 -> 调用归还API -> 归还完成画面
            callOpenLockApi()
        } else {
            // 没有智能锁，直接调用归还API
            callRevertApi()
        }
    }

    private fun callOpenLockApi() {
        showLoading("开锁中...")
        val param = CabinetLockVo()
        param.lockType = LockType.BACK.code
        param.joinId = mChemicalBean.joinId
        val disposable = ApiRepository.openLock(param)
            .subscribe({ data ->
                dismissLoading()
                if (data.success) {
                    // 开锁成功
                    dispatchOpenLockSuccess(param, data)
                } else {
                    showToast("开锁失败")
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun dispatchOpenLockSuccess(cabinetLock: CabinetLockVo, lockRespBean: LockRespBean) {
        AudioPlayerManager.speakVoice(R.raw.audio_success_open_lock)
        SuccessDialog(this, "开锁成功").apply {
            setCancelable(false)
            setOnDismissListener {
                mChemicalBean.returnStockNum = mWeight
                val intent = Intent(this@RevertActivity, ChemicalUnlockActivity::class.java)
                intent.putExtra("cabinetLock", cabinetLock)
                intent.putExtra("lockRespBean", lockRespBean)
                intent.putExtra("chemicalBean", mChemicalBean)
                startActivityForResult(intent, REQ_UNLOCK)
            }
        }.show()
    }

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

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

}