<%@ page contentType="text/html;charset=UTF-8" %>
<script>

var printerProtocolMap = {
    usb: 'usb',
    tcp: 'tcp'
}
var printerDirectiveMap = {
    _thermal_zpl_draw_print_: '_thermal_zpl_draw_print_',
    _thermal_tspl_draw_print_: '_thermal_tspl_draw_print_',
    _thermal_escpos_draw_print_: '_thermal_escpos_draw_print_'
}

var defPrintOption = {
    // post ws
    linkDeviceType: 'post',
    // usb tcp
    protocol: printerProtocolMap.usb,
    // 打印机指令
    printerDirective: printerDirectiveMap._thermal_zpl_draw_print_
}
var device = '';

var printCallback = null;
var startLink = false;

const __io_lnk = function() {
    return 'localhost:8008'
}
const __io_url = function() {
    return 'http://' + __io_lnk() + '/thermal.io?data='
}
const __ws_url = function() {
    return 'ws://' + __io_lnk() + '/thermal.ws'
}

/**
 * 枚举设备  获取设备
 * @private
 */
function _thermal_enum_printer_ () {
    if (startLink) return;
    startLink = true;
    var onBack = function onBack (isOk, res) {
        startLink = false;
        if (!isOk) {
            jp.warning('通讯失败：' + JSON.stringify(res));
            return
        }
        if (res.code !== 0) {
            jp.warning(res.msg);
            return
        }
        if (res.device.length > 0) {
            device = res.device[0];
            printCallback && printCallback();
        } else {
            jp.warning(res.message)
        }
    }
    let pack = {
        command: '_thermal_enum_printer_',
        require: defPrintOption.protocol,
    }
    on_link_device(pack, onBack);
}

var Image_style_letType = {
    '1': '误差扩撒',
    '2': '有序抖动',
    '3': '阈值'
}

var pageConfig = {
    // 纸张宽度
    draw_w: '',
    // 页长
    draw_h: '',
    // 横向位置
    Image_x: '',
    // 纵向位置
    Image_y: '',
    // 图片宽度
    Image_w: '',
    // 图片高度
    Image_h: '',
    // 图片阈值
    Image_Threshold: '',
    // 图片打印模式
    Image_style_let: '1',
}

//绘图打印图片
function _thermal_Image_print_ (url) {
    if (!device) {
        printCallback = printImage.bind(window, url);
        _thermal_enum_printer_();
    } else {
        printImage(url);
    }
}

function printImage (url) {
    //直接打印（ 打印:'true' / 预览:'false' ）
    var printdirectly  = 'true'
    //获取预览图为base64数据（ base64:'true' / 路径:'false' ）
    var get_base64_img = 'false'
    var onBack = function (isok, res) {
        if (!isok) {
            jp.warning('通讯失败：' + JSON.stringify(res));
            return
        }
        if (res.code !== 0) {
            jp.warning(res.msg);
            return
        }
        if (printdirectly === 'true') {
            jp.success('绘图打印成功')
        } else {
            if (get_base64_img === 'true') {
                console.log(res.image_base64)
            } else {
                console.log(res.image_path)
            }
        }
    }

    var pack = {
        command: defPrintOption.printerDirective,
        device : device,
        printdirectly : 'true',
        measurement_mode: 'mm',
        canvas_size : {
            width: pageConfig.draw_w,
            height: pageConfig.draw_h
        },
        get_base64_img : 'false',
        is_label: 'false',
        print: [
            {
                func: "PDSetAddImageMode",
                iMode: pageConfig.Image_style_let,
                iValueThreshold: pageConfig.Image_Threshold
            },
            {
                func:"PDDrawImage",
                iX: pageConfig.Image_x,
                iY: pageConfig.Image_y,
                iWidth: pageConfig.Image_w,
                iHeight: pageConfig.Image_h,
                szImageFile: url
            },
        ]
    }
    on_link_device(pack, onBack);
}

function on_link_device (pack, onBack) {
    if (defPrintOption.linkDeviceType === 'post') {
        jqPost(__io_url(), pack, onBack);
    } else if (defPrintOption.linkDeviceType === 'ws') {
        jqLink(__ws_url(), pack, onBack);
    }
}

function jqPost (url, pack, callback) {
    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(pack),
        dataType: 'json',
        success: function (data) {
            callback(true, data)
        },
        error: function (err) {
            callback(false, err)
        }
    })
}

var ws = null;
function jqLink (url, pack, callback) {
    if (ws == null) {
        ws = new WebSocket(url);
        ws.onback = callback;
        ws.onopen = function (evt) {
            ws.send(JSON.stringify(pack))
        };
        ws.onclose = function (evt) {
            ws = null
        };
        ws.onmessage = function (evt) {
            ws.onback(true, eval('(' + evt.data + ')'))
        };
        ws.onerror = function (evt) {
            ws.onback(false, evt)
        }
    } else {
        ws.onback = callback;
        ws.send(JSON.stringify(pack))
    }
}

// 输出信息
function output_control (text) {
    console.log(text);
}

</script>
