//
//  PrintTask.swift
//  PrinterDemo
//
//  Created by ios on 2022/3/11.
//  Copyright © 2022 Printer. All rights reserved.
//

import Foundation
import UIKit
import PrinterSDK
import SVProgressHUD

struct PrintTask {
    
    static func beginPrint(with image: UIImage, _ cmdType: PTCommandType, _ copies: Int, _ imageMode: PTBitmapMode, _ compress: (PTBitmapCompressMode, Bool)) {
        
        let zybImage = image
        var cmdData = Data()
        switch cmdType {
            case .CPCL:
                let cmd = PTCommandCPCL.init()
                cmd.cpclLabel(withOffset: 0, hRes: PTCPCLLabelResolution.resolution200, vRes: PTCPCLLabelResolution.resolution200, height: Int(zybImage.size.height) + 10, quantity: copies)
                cmd.cpclPrintBitmap(withXPos: 0, yPos: 0, image: zybImage.cgImage, bitmapMode: imageMode, compress: compress.0, isPackage: compress.1)
                if kUserDefaults.bool(forKey: PDPaperType) {
                    cmd.cpclForm()
                }
                cmd.cpclPrint()
                cmdData.append(cmd.cmdData as Data)
                
            case .ESC:
                for _ in 0..<copies {
                    let cmd = PTCommandESC.init()
                    cmd.initializePrinter()
                    cmd.appendRasterImage(zybImage.cgImage, mode: imageMode, compress: compress.0, package: compress.1)
                    cmdData.append(cmd.getCommandData())
                }
                /// 兼容单张和批量打印 escRequestTransmissionOfResponseOrStatus打印成功回调
                let stateCmd = PTCommandESC.init()
                stateCmd.escRequestTransmissionOfResponseOrStatus()
                cmdData.append(stateCmd.getCommandData())
                
            case .TSPL:
                
                let imageWidth = Int((zybImage.size.width.truncatingRemainder(dividingBy: 8))) == 0 ? Int((zybImage.size.width / 8)) : Int((zybImage.size.width + 8) / 8)
                let imageHeight = Int((zybImage.size.height.truncatingRemainder(dividingBy: 8))) == 0 ? Int((zybImage.size.height / 8)) : Int((zybImage.size.height + 8) / 8)
                let cmd = PTCommandTSPL.init()
                cmd.setCLS()
                //这边指的是纸的毫米，不是像素点
                cmd.setPrintDirection(PTTSCPrintDirection.normal, mirror: PTTSCPrintStyle.normal)
                cmd.setPrintAreaSizeWithWidth(imageWidth, height: imageHeight)
                if compress.0 == .none {
                    cmd.addBitmap(withXPos: 0, yPos: 0, mode: PTTSCBitmapMode.OR, image: zybImage.cgImage, bitmapMode: imageMode, compress: compress.0)

                }else {
                    cmd.addBitmap(withXPos: 0, yPos: 0, mode: PTTSCBitmapMode.orCompress, image: zybImage.cgImage, bitmapMode: imageMode, compress: compress.0)
                }
                cmd.print(withSets: 1, copies: copies)
                cmdData.append(cmd.cmdData as Data)
            
            case .ZPL:
                
                #if true
                /// DG~是先下载到打印机，建议用这条，可以用压缩方式
                let cmd = PTCommandZPL()
                cmd.xa_FormatStart()
                cmd.mc_MapClear(PTZplBool.Y)
                cmd.pm_PrintLabelMirrorImage(PTZplBool.N)
                cmd.pw_PrintWidth(kUserDefaults.integer(forKey: PDPrintDots))
                cmd.lh_LabelHome(withXPos: 0, yPos: 0)
                cmd.lr_LabelReversePrint(PTZplBool.N)
                cmd.xz_FormatEnd()
                
                /// 下载
                cmd.dg_DownloadGraphics(with: zybImage.cgImage!, bitmapMode: imageMode, compress: compress.0, deviceLocation: PTZplFileLocation.R, imageName: "iZPL", extension: "GRF")
                
                cmd.xa_FormatStart()
                cmd.pq_PrintQuantity(copies)
                cmd.fo_FieldOrigin(withXAxis: 10, yAxis: 10)
                /// 打印
                cmd.xg_RecallGraphic(withSourceDevice: PTZplFileLocation.R, imageName: "iZPL", extension: "GRF", xAxisMagnification: 1, yAxisMagnification: 1)
                cmd.fs_FieldSeparator()
                cmd.xz_FormatEnd()
                
                cmd.xa_FormatStart()
                /// 删除
                cmd.id_ImageDelete(withObjectLocation: PTZplFileLocation.R, objectName: "iZPL", extension: "GRF")
                cmd.xz_FormatEnd()
                cmdData.append(cmd.cmdData as Data)
                
                #else
                /// GF~是无法用压缩模式
                let cmd = PTCommandZPL()
                
                cmd.xa_FormatStart()
                cmd.mc_MapClear(PTZplBool.Y)
                cmd.pm_PrintLabelMirrorImage(PTZplBool.N)
                cmd.pw_PrintWidth(kUserDefaults.integer(forKey: PDPrintDots))
                cmd.lh_LabelHome(withXPos: 0, yPos: 0)
                cmd.lr_LabelReversePrint(PTZplBool.N)
                cmd.xz_FormatEnd()
                
                cmd.xa_FormatStart()
                cmd.pq_PrintQuantity(printCopiesCount)
                cmd.fo_FieldOrigin(withXAxis: 10, yAxis: 10)
                cmd.gf_GraphicField(withCompressionType: "B", image: cgImage, bitmapMode: imageMode)
                cmd.fs_FieldSeparator()
                cmd.xz_FormatEnd()
                cmdData.append(cmd.cmdData as Data)
                #endif
        }
                
        PTDispatcher.share()?.send(cmdData)
        PTDispatcher.share()?.whenSendFailure({
            SVProgressHUD.showError(withStatus: "Data send failed".localized)
        })
        
        PTDispatcher.share()?.whenSendProgressUpdate({
            SVProgressHUD.showProgress($0!.floatValue)
        })
        
        PTDispatcher.share()?.whenSendSuccess({ _,_ in
            if cmdType == .ESC {
                SVProgressHUD.dismiss()
            }else {
                SVProgressHUD.showSuccess(withStatus: "Data sent successfully".localized)
            }
            
//            UIAlertController.showConfirmView("Tips".localized, message: "Data sent successfully".localized + ",  " +  "Total data:".localized + "\($0/1000) kb,  " + "Total time:".localized + String.init(format: "%.1f s,  ", $1) + "Transmission rate:".localized + String.init(format: "%.1f kb/s", Double($0/1000)/$1), confirmHandle: nil)
        })
        
        PTDispatcher.share()?.whenReceiveData({ (data) in
            guard let data = data else {return}
            print(#line,data.hexString)
        })
        
        PTDispatcher.share()?.whenESCPrintSuccess { _ in
            SVProgressHUD.showSuccess(withStatus: "Print successfully".localized)
        }
    }
}
