package com.dlc.chemical.ui.query

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.databinding.ActivityChemicalsDetailBinding
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.BaseCountDownActivity
import com.dlc.chemical.ui.common.ModuleEnum
import com.dlc.chemical.ui.common.TagScanActivity
import com.dlc.chemical.ui.common.TagType
import com.dlc.chemical.ui.dialog.SimpleDialog
import com.dlc.chemical.ui.dialog.SimpleTipsDialog
import com.dlc.chemical.ui.msds.MsdsDetailActivity
import com.dlc.chemical.ui.widget.TitleBar
import com.print.usbprint.util.USBUtil
import com.rc.httpcore.vo.response.ChemicalBean

/**
 * 化学品详情
 *
 * @author ReiChin_
 */
class ChemicalsDetailActivity : BaseCountDownActivity<ActivityChemicalsDetailBinding>(),
    TitleBar.TitleListener {

    private lateinit var mChemicalBean: ChemicalBean

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

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

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

        viewBinding.printTag.visibility = if (null == ChemicalApp.sLearnLoginVo) View.GONE else View.VISIBLE
        viewBinding.printTag.setOnClickListener {
            handlePrintTagClicked()
        }
    }

    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 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")
    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)
    }

    @SuppressLint("SetTextI18n")
    private fun inflateContentView() {
        val contentViewBinding = ContentChemicalsInfoBinding.bind(viewBinding.content.inflate())

        // 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 onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

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

}