package com.dlc.chemical.ui.output

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import com.dlc.chemical.ChemicalApp
import com.dlc.chemical.R
import com.dlc.chemical.databinding.ActivityOutputStoreBinding
import com.dlc.chemical.databinding.ContentChemicalsInfoBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.ui.MainActivity
import com.dlc.chemical.ui.common.*
import com.dlc.chemical.ui.dialog.SimpleDialog
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.dlc.chemical.ui.msds.MsdsDetailActivity
import com.dlc.chemical.ui.revert.RevertActivity
import com.dlc.chemical.ui.unlock.SelectAuthMethodActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.rc.core.ui.ActivityCollector
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import com.rc.httpcore.vo.request.OutputStockReq
import com.rc.httpcore.vo.request.TagCodeReq
import com.rc.httpcore.vo.response.CabinetLockVo
import com.rc.httpcore.vo.response.ChemicalBean
import com.rc.httpcore.vo.response.LockRespBean

/**
 * 化学品出库
 *  无智能锁：
 *    MainActivity > TagScanActivity > OutputStoreActivity > [SelectAuthMethodActivity(finish)] > (finish)
 *  有智能锁：
 *    MainActivity > QueryChemicalsActivity > OutputStoreActivity > [SelectAuthMethodActivity(finish)] > ChemicalUnlockActivity(finish) > TagScanActivity(finish) > (finish)
 *
 * @author ReiChin_
 */
class OutputStoreActivity : BaseCountDownActivity<ActivityOutputStoreBinding>(),
    TitleBar.TitleListener {

    companion object {
        private const val REQ_PERSON_AUTH_BALANCE = 10
        private const val REQ_PERSON_AUTH_NULLIFY = 11

        // 库存状态 2-用结出库，3-作废出库
        private const val STOCK_STATUS_BALANCE = "2" // 用结出库
        private const val STOCK_STATUS_NULLIFY = "3" // 作废出库
    }

    private lateinit var mChemicalBean: ChemicalBean

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

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

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

        // 用结出库
        viewBinding.balanceOutput.setOnClickListener {
            SimpleDialog(
                context = this,
                titleText = "本次用结出库：${mChemicalBean.chemicalName}",
                message = "化学品出库净重：${mChemicalBean.suttle ?: "0.0"}${mChemicalBean.chemicalUnit ?: "g"}",
                messageTextStyle = Typeface.BOLD,
                dialogListener = {
                    if ("2" == mChemicalBean.classifyConfig.outStatus) {
                        // 2-双人双卡
                        val intent = Intent(this, SelectAuthMethodActivity::class.java)
                        intent.putExtra("lockType", LockType.OUT_STOCK.code)
                        startActivityForResult(intent, REQ_PERSON_AUTH_BALANCE)
                    } else {
                        // 1-单人验证
                        dispatchUseAction(STOCK_STATUS_BALANCE)
                    }
                }
            ).show()
        }
        // 作废出库
        viewBinding.nullifyOutput.setOnClickListener {
            SimpleDialog(context = this,
                titleText = "本次作废出库：${mChemicalBean.chemicalName}",
                message = "化学品出库净重：${mChemicalBean.suttle ?: "0.0"}${mChemicalBean.chemicalUnit ?: "g"}",
                messageTextStyle = Typeface.BOLD,
                extraTips = "作废操作不可逆，不可恢复！确认作废？",
                dialogListener = {
                    if ("2" == mChemicalBean.classifyConfig.outStatus) {
                        // 2-双人双卡
                        val intent = Intent(this, SelectAuthMethodActivity::class.java)
                        intent.putExtra("lockType", LockType.OUT_STOCK.code)
                        startActivityForResult(intent, REQ_PERSON_AUTH_NULLIFY)
                    } else {
                        // 1-单人验证
                        dispatchUseAction(STOCK_STATUS_NULLIFY)
                    }
                }
            ).show()
        }
        // 继续出库
        viewBinding.continueOutput.setOnClickListener {
            // 无智能锁：MainActivity -> TagScanActivity -> OutputStoreActivity -> OutputStoreActivity(output completed)
            // 有智能锁：MainActivity -> QueryChemicalsActivity -> OutputStoreActivity -> (lock finish) -> TagScanActivity(finish) -> OutputStoreActivity
            if (false == ChemicalApp.sLearnLoginVo?.cabinetLock) {
                val intent = Intent(this, TagScanActivity::class.java)
                intent.putExtra("moduleEnum", ModuleEnum.OUTPUT_STORE)
                startActivity(intent)
            }
            finish()
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val outputCompleted = intent?.getBooleanExtra("outputCompleted", false) ?: false
        if (outputCompleted) {
            val stockStatus = intent!!.getStringExtra("stockStatus")!!
            showContinueOutputUI(stockStatus)
        }
    }

    private fun dispatchUseAction(
        stockStatus: String,
        oneUser: String? = null,
        twoUser: String? = null
    ) {
        if (true == ChemicalApp.sLearnLoginVo?.cabinetLock) {
            // 有智能锁，开锁/关锁流程 -> 出库物品验证 -> 调用出库API -> 出库完成画面(继续出库)
            callOpenLockApi(stockStatus, oneUser, twoUser)
        } else {
            // 无智能锁：调用出库API -> 出库完成画面(继续出库)
            callOutputApi(stockStatus, oneUser, twoUser)
        }
    }

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

    private fun dispatchOpenLockSuccess(cabinetLock: CabinetLockVo, lockRespBean: LockRespBean,
                                        stockStatus: String, oneUser: String? = null, twoUser: String? = null) {
        AudioPlayerManager.speakVoice(R.raw.audio_success_open_lock)
        SuccessDialog(this, "开锁成功").apply {
            setCancelable(false)
            setOnDismissListener {
                val intent = Intent(this@OutputStoreActivity, ChemicalUnlockActivity::class.java)
                intent.putExtra("cabinetLock", cabinetLock)
                intent.putExtra("lockRespBean", lockRespBean)
                intent.putExtra("chemicalBean", mChemicalBean)
                intent.putExtra("stockStatus", stockStatus)
                intent.putExtra("oneUser", oneUser)
                intent.putExtra("twoUser", twoUser)
                startActivity(intent)
            }
        }.show()
    }

    /**
     * 调用出库api
     *
     * @param stockStatus 库存状态 2-用结出库，3-作废出库
     */
    private fun callOutputApi(
        stockStatus: String,
        oneUser: String? = null,
        twoUser: String? = null
    ) {
        showLoading("保存中...")
        val param = OutputStockReq().apply {
            id = mChemicalBean.id
            status = stockStatus
            outOneUser = oneUser
            outTwoUser = twoUser
        }
        val disposable = ApiRepository.outStock(param)
            .subscribe({
                dismissLoading()
                showContinueOutputUI(stockStatus)
            }, { throwable ->
                if (!pretreatmentOutputError(throwable)) {
                    dismissLoading()
                    showNetError(throwable)
                    throwable.printStackTrace()
                }
            })
        addDisposable(disposable)
    }

    private fun pretreatmentOutputError(throwable: Throwable): Boolean {
        if (throwable is NetException) {
            if ("500" == throwable.code
                && true == throwable.message?.contains("领用中")
            ) {
                dispatchOutputError_500(throwable.message)
                return true
            }
        }
        return false
    }

    private fun queryByUserecord(callback: (cBean: ChemicalBean) -> Unit) {
        showLoading("查询中...")
        val param = TagCodeReq()
        param.id = mChemicalBean.id
        val disposable = ApiRepository.queryByUserecord(param)
            .subscribe({ data ->
                dismissLoading()
                callback.invoke(data)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun dispatchOutputError_500(message: String?) {
        if (null == message) return
        OutputErrorDialog(this, message, dialogListener = {
            queryByUserecord { cBean ->
                val intent = Intent(this, RevertActivity::class.java)
                intent.putExtra("chemicalBean", cBean)
//                intent.putExtra("oneUser", getIntent().getStringExtra("oneUser"))
//                intent.putExtra("twoUser", getIntent().getStringExtra("twoUser"))
                startActivity(intent)
                ActivityCollector.removeActivity(2)
            }
        }).apply {
            setOnCancelListener {
                startActivity(Intent(this@OutputStoreActivity, MainActivity::class.java))
            }
        }.show()
    }

    override fun initData() {
        // 延迟加载内容页
        Handler(Looper.getMainLooper()).postDelayed({
            inflateContentView()
        }, 50)
    }

    private val contentViewBinding by lazy {
        ContentChemicalsInfoBinding.bind(viewBinding.content.inflate())
    }

    @SuppressLint("SetTextI18n")
    private fun inflateContentView() {
        contentViewBinding.msds.setOnClickListener {
            if (mChemicalBean.hazardId.isNullOrEmpty()) {
                showToast("暂无MSDS信息")
                return@setOnClickListener
            }
            MsdsDetailActivity.startAction(this, mChemicalBean.hazardId)
        }

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

    private fun showContinueOutputUI(stockStatus: String) {
        viewBinding.balanceOutput.visibility = View.GONE
        viewBinding.nullifyOutput.visibility = View.GONE
        viewBinding.continueOutput.visibility = View.VISIBLE
        contentViewBinding.suttleLabel.text = "出库净重"/*if (STOCK_STATUS_BALANCE == stockStatus) "用结重量" else "作废重量"*/

        AudioPlayerManager.speakVoice(R.raw.audio_success_output)
        SuccessDialog(this, "出库成功").show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQ_PERSON_AUTH_BALANCE,
            REQ_PERSON_AUTH_NULLIFY -> {
                if (RESULT_OK == resultCode) {
                    val authResult = data?.getBooleanExtra("auth_result", false) ?: false
                    if (authResult) {
                        val stockStatus =
                            if (REQ_PERSON_AUTH_BALANCE == requestCode) STOCK_STATUS_BALANCE else STOCK_STATUS_NULLIFY
                        val joinOneUser = data?.getStringExtra("joinOneUser")
                        val joinTwoUser = data?.getStringExtra("joinTwoUser")
                        dispatchUseAction(stockStatus, joinOneUser, joinTwoUser)
                    }
                }
            }
        }
    }

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

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

}