package com.stand.standapp.printer

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import com.dp.dp_serialportlist.Serialport_Factory
import com.stand.standapp.AppConfig
import timber.log.Timber
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

object PrinterManager {
    private var sf: Serialport_Factory? = null
    private var isConnecting = false
    private val executor = Executors.newSingleThreadScheduledExecutor()
    private var mContext: Context? = null
    private var hasPaper: Boolean = true // 默认为有纸

    private val mHandler = Handler(Looper.getMainLooper()) { msg ->
        if (msg.what == Serialport_Factory.PAPER_STATE) {
            hasPaper = msg.data.getBoolean("PAPER_STATE")
            val statusStr = if (hasPaper) "有纸" else "缺纸"
            Timber.tag("Printer").i("打印机状态变更: %s", statusStr)
            
            // 在 Android 系统层面主动提示
            mContext?.let {
                if (!hasPaper) {
                    android.widget.Toast.makeText(it.applicationContext, "⚠️ 警告：打印机缺纸！", android.widget.Toast.LENGTH_LONG).show()
                } else {
                    android.widget.Toast.makeText(it.applicationContext, "打印机状态：正常 (有纸)", android.widget.Toast.LENGTH_SHORT).show()
                }
            }
            
            // 通知前端页面
            com.stand.standapp.MainActivity.executeJs("if(window.onPaperStateChanged) { window.onPaperStateChanged($hasPaper); }")
        }
        true
    }

    fun isPaperReady(): Boolean = hasPaper

    fun init(context: Context) {
        if (sf != null) return
        mContext = context.applicationContext
        
        // Serialport_Factory 构造函数内部会创建 Handler，必须在有 Looper 的线程（如主线程）调用
        mHandler.post {
            try {
                Timber.tag("Printer").i("正在主线程初始化打印机组件...")
                sf = Serialport_Factory.getSerialport_Factory(mContext, mHandler)
                
                // 成功创建 factory 后，将后续耗时的连接任务丢给子线程
                executor.execute {
                    // 启动自动重连定时任务
                    executor.scheduleWithFixedDelay({
                        checkAndConnect()
                    }, 0, 10, TimeUnit.SECONDS)
                }
                
                Timber.tag("Printer").i("打印机组件初始化任务已分发")
            } catch (e: Exception) {
                Timber.tag("Printer").e(e, "打印机组件初始化失败")
            }
        }
    }

    @Synchronized
    private fun checkAndConnect() {
        val factory = sf ?: return
        if (factory.isConnection) return

        val path = AppConfig.getSerialPort(mContext!!)
        val baudrate = "9600"
        
        Timber.tag("Printer").d("尝试自动连接打印机: %s @ %s", path, baudrate)
        try {
            if (factory.OpenPort(path, baudrate)) {
                Timber.tag("Printer").i("打印机自动连接成功")
            }
        } catch (e: Throwable) {
            Timber.tag("Printer").e(e, "打印机自动连接异常")
        }
    }

    fun getFactory(): Serialport_Factory? = sf

    fun isConnected(): Boolean = sf?.isConnection ?: false

    /**
     * 提供便捷的打印方法
     */
    fun printText(text: String, size: Int = 1, align: Int = 1, space: Int = 10) {
        sf?.let {
            if (it.isConnection) {
                it.PrintText(text, size, align, space)
            }
        }
    }

    fun cutPaper() {
        sf?.let {
            if (it.isConnection) {
                it.PaperCut()
            }
        }
    }
}
