package com.example.chemical.ui.warehousing

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.caysn.autoreplyprint.AutoReplyPrint
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.databinding.ActivityElectronicLedgerBinding
import com.example.chemical.ui.SplashActivity
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.utils.BitmapUtils
import com.example.chemical.utils.MediaPlayerHelper
import com.example.chemical.utils.TimeUpdater
import com.example.chemical.utils.UiManager
import com.example.chemical.weidith.AirBottleDialog
import com.example.chemical.weidith.CustomDialog
import com.rc.core.log.RcLog
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.sun.jna.Pointer

//标签管理
class ElectronicLedgerActivity : BaseCountDownActivity<ActivityElectronicLedgerBinding>() {

    private lateinit var timeUpdater: TimeUpdater
    override fun createViewBinding() =
        ActivityElectronicLedgerBinding.inflate(LayoutInflater.from(this))

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.tvOutLogin.setOnClickListener {
            callLogoutApi {
                ChemicalApp.userData = null
                HttpClient.token = null
                ChemicalApp.subjectId = null
                UiManager.switcherCashier(this, SplashActivity::class.java)
            }
        }
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }

        viewBinding.chemicalLabeling.setOnClickListener {
            //化学品标签
            UiManager.switcher(this, ChemicalLabelingActivity::class.java)
        }

        viewBinding.cylinderLabel.setOnClickListener {
            //气瓶标签
            var airBottleDialog = AirBottleDialog(this, object : AirBottleDialog.ILintDate {
                override fun onLintDate(cont: String) {
                    if (cont.isNotEmpty()){
                        labelPrint(cont)
                    }
                }
            })
            airBottleDialog.show()
        }
    }

    override fun initData() {
        super.initData()
        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()


        viewBinding.tvName.text = ChemicalApp.userData!!.userName
        val imageView = viewBinding.imageName
        // 使用 Glide 加载网络图片
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.userData!!.avatar}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(imageView)

        // 使用 Glide 加载网络图片
        viewBinding.deptName.text="${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(viewBinding.image)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
    }
    var h = Pointer.NULL
    private fun labelPrint(rfid:String) {
        val thread = Thread {
            try {

                try {//关闭打印
                    h = AutoReplyPrint.INSTANCE.CP_Port_OpenUsb("VID:0x0FE6,PID:0x811E", 1)
                } catch (e: Exception) {
                    RcLog.info("初始化异常")
                }

                val bitmap = BitmapUtils.airBottlePrint(rfid)  //图片信息
                AutoReplyPrint.INSTANCE.CP_Label_BackPaperToPrintPosition(h)
                AutoReplyPrint.CP_Pos_PrintRasterImageFromData_Helper.PrintRasterImageFromBitmap(
                    h,
                    bitmap!!.width,
                    bitmap.height,
                    bitmap,
                    AutoReplyPrint.CP_ImageBinarizationMethod_Thresholding,
                    AutoReplyPrint.CP_ImageCompressionMethod_None
                )
                AutoReplyPrint.INSTANCE.CP_Label_PagePrint(h, 1)
                val result = AutoReplyPrint.INSTANCE.CP_Pos_HalfCutPaper(h) //全切
                if (result) {
                    //打印成功
                    MediaPlayerHelper.playRawMp3(this, R.raw.zhantiefrid)
                    customDialogView(0, "请将二维码粘贴在RFID标签上")
                    closePort()
                } else {
                    //失败
                    closePort()
                    RcLog.info("=====异常2222")
                }
            } catch (e: Exception) {
                // 监听子线程中抛出的异常
                closePort()
                RcLog.info("=======异常${e.message}")
            }
        }
        thread.start() // 启动子线程
    }

    private fun closePort() {
        if (h !== Pointer.NULL) {
            AutoReplyPrint.INSTANCE.CP_Port_Close(h)
            h = Pointer.NULL
        }
    }
    /**
     * 0  没有图标 1 绿色(成功)   2红色（失败）
     *   失败或者成功的弹框
     */
    private fun customDialogView(types: Int, msg: String) {
        if (!this.isFinishing && !this.isDestroyed) {
            val customDialog = CustomDialog(this, types, msg)
            customDialog.show()
        }
    }
}