package service

import (
	"fmt"
	"time"
	"wails-app/internal/dao"
	"wails-app/internal/global"
)

type PrintService struct{}

func NewPrintService() *PrintService {
	return &PrintService{}
}

// PrintTicket 打印入场小票
func (s *PrintService) PrintTicket(printerID uint, lotName, channelCode, plateNo string, ticketID uint, ticketNo string) error {
	var printer dao.Printer
	if err := global.GVA_DB.First(&printer, printerID).Error; err != nil {
		return fmt.Errorf("打印机未配置: id=%d", printerID)
	}

	// 根据 port_name 判断连接类型
	var err error
	var srl *SerialPrinter
	write := func(data []byte) {}

	if len(printer.PortName) >= 3 && printer.PortName[:3] == "COM" {
		srl, err = NewSerialPrinter(printer.PortName, printer.BaudRate)
		if err == nil { defer srl.Close(); write = func(data []byte) { srl.Write(data) } }
	} else {
		// USB/Windows 打印机 → COPY /B 到共享路径
		write = func(data []byte) {
			err = copyToPrinter(printer.Name, data)
		}
	}
	if err != nil {
		global.GVA_DB.Model(&printer).Update("status", "offline")
		return fmt.Errorf("连接打印机失败: %w", err)
	}

	now := time.Now().Format("02-01-2006 15:04:05")
	slipNo := fmt.Sprintf("%d", ticketID)

	// Print ticket
	write(InitCmd)
	write(AlignCenterCmd)
	write(DoubleHeightCmd)
	write(BoldOnCmd)
	write(ESCPOS_Text("PARKING TICKET"))
	write(BoldOffCmd)
	write(NormalCmd)
	write(ESCPOS_Text(""))
	write(ESCPOS_Text(lotName))
	write(ESCPOS_Text("A-General Car"))
	write(ESCPOS_Text(""))
	write(BoldOnCmd)
	write(ESCPOS_Text("PARK AT YOUR OWN RISK"))
	write(BoldOffCmd)

	write(InitCmd)
	write(AlignLeftCmd)
	write(ESCPOS_Text("In-Time::" + now))
	if channelCode != "" {
		write(ESCPOS_Text("InGate::" + channelCode))
	}
	if plateNo != "" {
		write(ESCPOS_Text("Veh No::" + plateNo))
	}

	write(InitCmd)
	write(ESCPOS_Text(""))
	write(ESCPOS_Text("Slip No::" + slipNo))

	write(InitCmd)
	write(AlignCenterCmd)
	write(ESCPOS_Text(""))
	write(ESCPOS_QRCode(ticketNo))
	write(ESCPOS_Text(""))

	write(AlignCenterCmd)
	write(ESCPOS_Text("SCAN AND PAY WITH"))
	write(ESCPOS_Text("NEW THE CANADIA BANK APP"))

	write(InitCmd)
	write(ESCPOS_Text(""))
	write(ESCPOS_Text(""))
	write(CutPaperCmd)

	global.GVA_DB.Model(&printer).Update("status", "online")
	return nil
}
