package com.dlc.chemical.ui.use

import android.annotation.SuppressLint
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Typeface
import android.hardware.usb.UsbManager
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.common.Constants
import com.dlc.chemical.databinding.ActivityUseBinding
import com.dlc.chemical.databinding.ContentChemicalsInfoBinding
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.print.PrinterListener
import com.dlc.chemical.print.PrinterStateReceiver
import com.dlc.chemical.print.UsbPrinterManager
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.SimpleTipsDialog
import com.dlc.chemical.ui.dialog.SuccessDialog
import com.dlc.chemical.ui.msds.MsdsDetailActivity
import com.dlc.chemical.ui.unlock.SelectAuthMethodActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.print.usbprint.util.USBUtil
import com.rc.core.util.trimEndZero
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.CabinetLockVo
import com.rc.httpcore.vo.response.ChemicalBean
import com.rc.httpcore.vo.response.LockRespBean
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.math.BigDecimal
import java.math.RoundingMode
import java.util.*

/**
 * 领用化学品
 * MainActivity > QueryChemicalsActivity > UseActivity
 *  [ > SelectAuthMethodActivity(finish) > ChemicalUnlockActivity(finish)]
 *  > TagScanActivity(finish) > UseWeightActivity > SteelyardVideoActivity(finish) > (finish)
 *
 * @author ReiChin_
 */
class UseActivity : BaseCountDownActivity<ActivityUseBinding>(), TitleBar.TitleListener {

    companion object {
        private const val REQ_PERSON_AUTH = 10
    }

    private val mChemicalBean: ChemicalBean by lazy {
        intent.getParcelableExtra("chemicalBean")!!
    }

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

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

        viewBinding.printTag.setOnClickListener {
            handlePrintTagClicked()
        }

        // 领用
        viewBinding.save.setOnClickListener {
            if ("2" == mChemicalBean.classifyConfig.collectStatus) {
                // 2-双人双卡
                val intent = Intent(this, SelectAuthMethodActivity::class.java)
                intent.putExtra("lockType", LockType.USE.code)
                startActivityForResult(intent, REQ_PERSON_AUTH)
            } else {
                // 1-单人验证
                dispatchUseAction()
            }
        }

        // 继续领用
        viewBinding.continueUse.setOnClickListener {
            // 新流程：MainActivity -> QueryChemicalsActivity -> UseActivity -> [开/关锁(finish)] -> TagScanActivity(finish) -> UseWeightActivity(finish)
            if (!Constants.Mock.USE_FLOW_NEWLY) {
                if (false == ChemicalApp.sLearnLoginVo?.cabinetLock) {
                    val intent = Intent(this, TagScanActivity::class.java)
                    intent.putExtra("moduleEnum", ModuleEnum.USE)
                    startActivity(intent)
                }
            }
            finish()
        }
    }

    private fun handlePrintTagClicked() {
        if (TagType.QR_CODE.type == mChemicalBean.labelType) {
            // 补打二维码
            SimpleDialog(context = this,
                titleText = "本次补打编号：${mChemicalBean.tagCode}",
                message = "确认补打？",
                messageTextColor = "#FF333333",
                messageTextStyle = Typeface.BOLD,
                dialogListener = {
                    // 调用二维码打印机
                    val device = USBUtil.getInstance()
                        .getUsbDevice(UsbPrinterManager.DEVICE_VID, UsbPrinterManager.DEVICE_PID)
                    if (null != device && USBUtil.getInstance().IsOpen(device, this)) {
                        UsbPrinterManager.printLabel(mChemicalBean)
                    } else {
                        showToast("未连接打印设备！")
                    }
                }).show()
        } else {
            // RFID更换
            val intent = Intent(this, TagScanActivity::class.java)
            intent.putExtra("moduleEnum", ModuleEnum.RFID)
            intent.putExtra("id", mChemicalBean.id)
            startActivity(intent)
        }
    }

    private fun dispatchUseAction(oneUser: String? = null, twoUser: String? = null) {
        if (true == ChemicalApp.sLearnLoginVo?.cabinetLock) {
            // 有智能锁，开锁/关锁流程 -> 领用物品验证 -> 领用称重 -> 领用完成
            callOpenLockApi(oneUser, twoUser)
        } else {
            if (Constants.Mock.USE_FLOW_NEWLY) {
                val intent = Intent(this, TagScanActivity::class.java)
                intent.putExtra("chemicalBean", mChemicalBean)
                intent.putExtra("moduleEnum", ModuleEnum.USE)
                intent.putExtra("oneUser", oneUser)
                intent.putExtra("twoUser", twoUser)
                startActivity(intent)
            } else {
                val intent = Intent(this, UseWeightActivity::class.java)
                intent.putExtra("chemicalBean", mChemicalBean)
                intent.putExtra("oneUser", oneUser)
                intent.putExtra("twoUser", twoUser)
                startActivity(intent)
            }
        }
    }

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

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

    override fun initData() {
        if (TagType.QR_CODE.type == mChemicalBean.labelType) {
            viewBinding.printText.text = "补打二维码"
            viewBinding.printImage.setImageResource(R.mipmap.icon_hxpk_bdewm)
        } else {
            viewBinding.printText.text = "RFID更换"
            viewBinding.printImage.setImageResource(R.mipmap.icon_hxprk_rfid)
        }

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

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

    @SuppressLint("SetTextI18n")
    private fun inflateContentView() {
        // MSDS
        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"}"
    }

    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) {
                        val joinOneUser = data?.getStringExtra("joinOneUser")
                        val joinTwoUser = data?.getStringExtra("joinTwoUser")
                        dispatchUseAction(joinOneUser, joinTwoUser)
                    }
                }
            }
        }
    }

    private fun dispatchQRCodePrintSuccess() {
        val message = "二维码补打成功！\n请将二维码标签粘在化学品瓶身上。"
        AudioPlayerManager.speakVoice(R.raw.audio_success_print_qrcode)
        SimpleTipsDialog(this, message)
            .show()
    }

    private fun onPrinterEvent(success: Boolean, message: String) {
        if (success) {
            dispatchQRCodePrintSuccess()
        } else {
            showToast(message)
        }
    }

    private var mPrinterStateReceiver: PrinterStateReceiver? = null

    override fun onResume() {
        super.onResume()
        registerPrinterStateReceiver()
    }

    private fun registerPrinterStateReceiver() {
        if (mPrinterStateReceiver == null) {
            val filter = IntentFilter()
            mPrinterStateReceiver = PrinterStateReceiver(printerListener = object : PrinterListener {
                override fun onPrintResult(success: Boolean, message: String) {
                    onPrinterEvent(success, message)
                }

            })
            filter.addAction(PrinterStateReceiver.ACTION_PRINTER_STATE)
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
            this.registerReceiver(mPrinterStateReceiver, filter)
        }
    }

    override fun onPause() {
        super.onPause()
        if (mPrinterStateReceiver != null) {
            unregisterReceiver(mPrinterStateReceiver)
            mPrinterStateReceiver = null
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUseCompletedEvent(event: UseCompletedEvent) {
        // 领用净重=称重重量-容器规格
        val tare = if ("g" == mChemicalBean.chemicalUnit) mChemicalBean.tare else "0"
        val useSuttle = try {
            BigDecimal(event.weight).subtract(BigDecimal(tare)).setScale(5, RoundingMode.HALF_UP)
        } catch (e: Exception) { BigDecimal("0.00") }

        // 损耗量=库存净重-领用净重
        val lossAmount = try {
            BigDecimal(mChemicalBean.suttle).subtract(useSuttle).setScale(5, RoundingMode.HALF_UP)
        } catch (e: Exception) { BigDecimal("0.00") }

        // 损耗量
        contentViewBinding.lossAmountGroup.visibility = View.VISIBLE
        contentViewBinding.lossAmount.text = "${lossAmount.toPlainString().trimEndZero()}${mChemicalBean.chemicalUnit ?: "g"}"
        // 领用净重
        contentViewBinding.useSuttleGroup.visibility = View.VISIBLE
        contentViewBinding.useSuttle.text = "${useSuttle.toPlainString().trimEndZero()}${mChemicalBean.chemicalUnit ?: "g"}"
        viewBinding.save.visibility = View.GONE
        viewBinding.continueUse.visibility = View.VISIBLE
        AudioPlayerManager.speakVoice(R.raw.audio_success_use)
        SuccessDialog(this, "领用成功").apply {
            setCancelable(false)
        }.show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        EventBus.getDefault().register(this)
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

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

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

    override fun onBackPressed() {
        if (View.VISIBLE == viewBinding.continueUse.visibility) {
            startActivity(Intent(this, MainActivity::class.java))
        } else {
            super.onBackPressed()
        }
    }

}