<%@ 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_tspl_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: 90,
    // 页长
    draw_h: 72.5,
    // 横向位置
    Image_x: 3,
    // 纵向位置
    Image_y: 4,
    // 图片宽度
    Image_w: 84,
    // 图片高度
    Image_h: 63,
    // 图片阈值
    Image_Threshold: 230,
    // 图片打印模式
    Image_style_let: 3,
}

//绘图打印图片
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)
            }
        }
    }

    url2Base64(url).then(res => {
        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: res
                },
            ]
        }
        // console.log(pack)
        // var str = JSON.stringify(pack, null, 2);
        // var blob = new Blob([str], {
        //     type: "application/json"
        // });
        // var url = URL.createObjectURL(blob);
        //
        // var a = document.createElement('a');
        // a.href = url;
        // a.download = 'a.json';
        // a.click();
        // a.remove();

        on_link_device(pack, onBack);
    })


}

function url2Base64 (url, type = 'image/jpeg') {
    return new Promise((resolve, reject) => {
        const img = new Image()
        const canvas = document.createElement('canvas');
        img.crossOrigin = '*';
        img.onload = function () {
            const width = img.width, height = img.height;
            canvas.width = width;
            canvas.height = height;

            const ctx = canvas.getContext('2d');
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0, width, height);
            const base64 = canvas.toDataURL(type);
            resolve(base64);
        };
        img.onerror = function () {
            reject(new Error('message'));
        };
        img.src = url;
    });
}

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>
