var page = {
    printLookupDialog: {},
    printSettingDialog: {},
    submitFlag: 0,
    initTable: function () {
        var tbH = document.documentElement.clientHeight - $("#searchForm").outerHeight() - 10
        let pager = initGridPagerNew(tbH, 37, 40);
        $("#tb").edatagrid({
            url: g.ctx + 'pc/order/barcodePrinter/rest/list',
            method: "GET",
            singleSelect: false,
            loadMsg: '数据远程载入中,请等待...',
            pagination: true,
            checkbox: true,
            pageSize: pager.pageSize,
            pageList: pager.pageList,
            height: tbH,
            rownumbers: true,
            columns: [[
                {
                    field: 'ck', checkbox: true
                },
                {
                    field: 'status', title: '推送状态', align: 'left', width: 70, formatter: function (value) {
                        if (value === 1) {
                            return "成功"
                        }
                        return "<span style='color: red'>失败</span>"
                    }
                },
                {
                    field: 'type', title: '类型', align: 'left', width: 100, formatter: function (value) {
                        if (value === 1) {
                            return "多层"
                        }
                        if (value === 2) {
                            return "单层"
                        }
                        if (value === 3) {
                            return "供应商接口调用"
                        }
                    }
                },
                {
                    field: 'purchaseOrderCode', title: '采购订单号', align: 'left', width: 100
                },
                {
                    field: 'materialCode', title: '物料编号', align: 'left', width: 130
                },
                {
                    field: 'printerType', title: '打印机类型', align: 'left', width: 130, formatter: function (value) {
                        if (value === 1) {
                            return "默认"
                        } else if (value === 2) {
                            return '200dpi(TSC)';
                        } else if (value === 3) {
                            return '300dpi(TSC)';
                        } else {
                            return '未知'
                        }
                    }
                },

                {
                    field: 'supplierCode', title: '供应商编号', align: 'left', width: 100
                },
                {
                    field: 'supplierName', title: '供应商名称', align: 'left', width: 200
                },
                {
                    field: 'deleteFlag', title: '是否作废', align: 'left', width: 100, formatter: function (value) {
                        if (value === 1) {
                            return "作废"
                        }
                        return '正常'
                    }
                },
                {
                    field: 'createTime', title: '创建时间', align: 'left', width: 135
                }
            ]],
            toolbar: [{
                text: '多层标签打印', id: 'btn_all', iconCls: 'icon-print', handler: function () {
                    page.openPrintSettingDialog(1)
                }
            }, "-", {
                text: '单层标签打印', id: 'btn_inner', iconCls: 'icon-print', handler: function () {
                    page.openPrintSettingDialog(2)
                }
            }, "-", {
                text: '打印', id: 'btn_inner', iconCls: 'icon-print', handler: function () {
                    let rows = $('#tb').datagrid('getChecked');
                    if (rows.length != 1) {
                        topWin.layer.msg("请选中一条记录");
                        return;
                    }
                    if (rows[0].printSize > 0) {
                        topWin.layer.alert("该笔数据已打印，需要重复打印，请查询后选择明细打印");
                        return;
                    }
                    let row = rows[0];
                    if (row.printerType === 1) {
                        let btns = [
                            {
                                text: '关闭',
                                iconCls: 'icon-cancel',
                                handler: function () {
                                    page.printLookupDialog.dialog('close');
                                }
                            }
                        ]
                        if (row.deleteFlag === 1) {
                            btns.shift()
                        }
                        page.printLookupDialog = openDialog('printLookupDialog', g.ctx + 'pc/order/barcodePrinter/page/lookup?id=' + row.id, {
                            title: '打印',
                            width: 340,
                            height: '100%',
                            cache: false,
                            modal: true,
                            border: 'thin',
                            onClose: function () {
                                page.printLookupDialog.dialog('destroy');
                                topWin.layer.open({
                                    content: "请确认是否完成打印？",
                                    btn: ['已打印', '未打印'],
                                    btn1: function(alert) {
                                        topWin.layer.close(alert);
                                        $.ajax({
                                            url: g.ctx + 'pc/order/barcodePrinter/rest/updatePrintSize',
                                            async: false,//同步
                                            type: "post",
                                            data: {id : row.id},
                                            success: function () {
                                                $("#tb").edatagrid("reload")
                                            }
                                        });
                                    }
                                });
                            },
                            buttons: btns
                        });
                    } else {
                        $.ajax({
                            url: "http://localhost:8999/openport",
                            async: false,//同步
                            type: "get",
                            success: function () {
                                $.ajax({
                                    url: g.ctx + 'pc/order/barcodePrinter/rest/getPrintData',
                                    type: 'GET',
                                    data: {id: row.id, isPrint: 1},
                                    success: function (data) {
                                        localStorage.setItem("printDataKey", JSON.stringify(data));
                                        if (row.printerType === 2) {
                                            var iframe = document.getElementById('printDiv');
                                            iframe.src = g.ctx + 'pc/order/barcodePrinter/page/dpi200';
                                        } else {
                                            var iframe = document.getElementById('printDiv');
                                            iframe.src = g.ctx + 'pc/order/barcodePrinter/page/dpi300';
                                        }
                                    },
                                    error: function (data) {
                                        topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                    }
                                });
                            },
                            error: function (data) {
                                topWin.layer.alert("请先开启打印脚本!!!", {icon: 2});
                            }
                        })

                    }
                }
            }, "-", {
                text: '重推', id: 'btn_replay', iconCls: 'icon-redo', handler: function () {
                    let rows = $('#tb').datagrid('getChecked');
                    if (rows.length < 1) {
                        topWin.layer.msg("请选中一条记录");
                        return;
                    }
                    let row = rows[0];
                    //重新推送给接口
                    if (row.status === 1) {
                        topWin.layer.msg("只有失败的数据才能重新推送");
                        return;
                    }
                    if (row.deleteFlag === 1) {
                        topWin.layer.msg("作废数据无法重新推送");
                        return;
                    }
                    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                    $.ajax({
                        url: g.ctx + 'pc/order/barcodePrinter/rest/rePush',
                        type: 'POST',
                        data: {id: row.id},
                        complete: function () {
                            top.layer.close(loading);
                        },
                        success: function (data) {
                            //如果不是默认打印机需要调用下
                            topWin.layer.msg("推送成功!");
                            $("#tb").edatagrid("reload")
                        },
                        error: function (data) {
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                }
            }, "-", {
                text: '批量重推', id: 'btn_replay_batch', iconCls: 'icon-redo', handler: function () {
                    let rows = $('#tb').datagrid('getChecked');
                    if (rows.length < 1) {
                        topWin.layer.msg("请选中至少一条记录");
                        return;
                    }
                    //判断数据是否都是全部失败
                    let ids = []
                    for (let i = 0; i < rows.length; i++) {
                        if (rows[i].status === 1) {
                            //topWin.layer.msg("只有失败的数据才能重新推送");
                            //return;
                        }
                        if (rows[i].deleteFlag === 1) {
                            topWin.layer.msg("作废数据无法重新推送");
                            return;
                        }
                        ids.push(rows[i].id)
                    }
                    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                    $.ajax({
                        url: g.ctx + 'pc/order/barcodePrinter/rest/rePushBatch',
                        type: 'POST',
                        data: {ids: ids.join(",")},
                        complete: function () {
                            top.layer.close(loading);
                        },
                        success: function (data) {
                            //如果不是默认打印机需要调用下
                            topWin.layer.msg("推送成功!");
                            $("#tb").edatagrid("reload")
                        },
                        error: function (data) {
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                }
            }, "-", {
                text: '查询', id: 'btn_patchwork', iconCls: 'icon-search', handler: function () {
                    let btns = [
                        {
                            text: '关闭',
                            iconCls: 'icon-cancel',
                            handler: function () {
                                patchworkDialog.dialog('close');
                            }
                        }
                    ]
                    let rows = $('#tb').datagrid('getChecked');
                    //判断数据是否都是全部失败
                    let ids = []
                    for (let i = 0; i < rows.length; i++) {
                        ids.push(rows[i].id)
                    }
                  //  let materialCode = $('#materialCode').val();
                  //  let orderCode = $('#orderCode').val();
                  //  let barCode = $('#barCode').val();
                    let supplierName = $('#supplierName').val();
                    if(!isSupplier){
                        if ((Array.isArray(ids) && ids.length === 0)) {
                            topWin.layer.msg("请先勾选查询数据！");
                            return;

                        }
                    }
                        var patchworkDialog = openDialog('patchworkDialog', g.ctx + 'pc/order/barcodePrinter/page/labelIndex?ids=' + ids.join(","), {
                        title: '查询',
                        width: '100%',
                        height: '100%',
                        cache: false,
                        modal: true,
                        border: 'thin',
                        onClose: function () {
                            patchworkDialog.dialog('destroy');
                        },
                        buttons: btns
                    });
                }
            }, "-", {
                text: '增强打印', id: 'btn_enhance_patchwork', iconCls: 'icon-print', handler: function () {
                    let rows = $('#tb').datagrid('getChecked');
                    if (rows.length < 1) {
                        topWin.layer.msg("请选中一条记录进行打印");
                        return;
                    }
                    let ids = rows.map(row => row.id).join(',');
                    window.open(g.ctx + 'pc/order/barcodePrinter/page/pdfPrint?ids=' + ids, '_blank');
                }
            }],
            onBeforeLoad: function () {
                displayButtonByUserRole('materialBar');
            }
        });
    },
    openPrintSettingDialog: function (type) {
        page.printSettingDialog = openDialog('printSettingDialog', g.ctx + 'pc/order/barcodePrinter/page/detail?type=' + type, {
            title: '打印',
            width: '100%',
            height: '100%',
            cache: false,
            modal: true,
            border: 'thin',
            onClose: function () {
                page.printSettingDialog.dialog('destroy');
            },
            buttons: [
                {
                    text: '打印',
                    iconCls: 'icon-save',
                    handler: function () {
                        var formData = topWin.frames['printSettingDialog'].page.getFormData();
                        if (!formData) {
                            return
                        }
                        if (page.submitFlag === 1) {
                            console.log('重复提交了!');
                            return;
                        }

                        //不能有中文校验 邓京术 2025-09-19
                        const regNum = /^\d+(\.\d+)?$/;
                        if (type === 1) {
                            //整箱数量
                            if (formData.fullQuantity) {
                                var flage1 = regNum.test(formData.fullQuantity);
                                if (!flage1) {
                                    topWin.layer.alert('整箱数量只能输入数字！');
                                    return false;
                                }
                                for (var i = 0; i < formData.fullQuantity.length; i++) {
                                    if (formData.fullQuantity.charCodeAt(i) <= 0 || formData.fullQuantity.charCodeAt(i) >= 255) {
                                        topWin.layer.alert('整箱数量不能包含中文，请重新输入');
                                        return false;
                                    }
                                }
                            }
                            //最小包装数
                            if (formData.minQuantity) {
                                var flage1 = regNum.test(formData.minQuantity);
                                if (!flage1) {
                                    topWin.layer.alert('最小包装数只能输入数字！');
                                    return false;
                                }
                                for (var i = 0; i < formData.minQuantity.length; i++) {
                                    if (formData.minQuantity.charCodeAt(i) <= 0 || formData.minQuantity.charCodeAt(i) >= 255) {
                                        topWin.layer.alert('最小包装数不能包含中文，请重新输入');
                                        return false;
                                    }
                                }
                            }

                            //中箱数量
                            if (formData.middleQuantity) {
                                var flage1 = regNum.test(formData.middleQuantity);
                                if (!flage1) {
                                    topWin.layer.alert('中箱数量只能输入数字！');
                                    return false;
                                }
                                for (var i = 0; i < formData.middleQuantity.length; i++) {
                                    if (formData.middleQuantity.charCodeAt(i) <= 0 || formData.middleQuantity.charCodeAt(i) >= 255) {
                                        topWin.layer.alert('中箱数量不能包含中文，请重新输入');
                                        return false;
                                    }
                                }
                            }
                        } else {
                            //包装数
                            if (formData.minQuantity) {
                                var flage1 = regNum.test(formData.minQuantity);
                                if (!flage1) {
                                    topWin.layer.alert('包装数只能输入数字！');
                                    return false;
                                }
                                for (var i = 0; i < formData.minQuantity.length; i++) {
                                    if (formData.minQuantity.charCodeAt(i) <= 0 || formData.minQuantity.charCodeAt(i) >= 255) {
                                        topWin.layer.alert('包装数不能包含中文，请重新输入');
                                        return false;
                                    }
                                }
                            }
                        }

                        //数量
                        if (formData.num) {
                            var flage1 = regNum.test(formData.num);
                            if (!flage1) {
                                topWin.layer.alert('数量只能输入数字！');
                                return false;
                            }
                            for (var i = 0; i < formData.num.length; i++) {
                                if (formData.num.charCodeAt(i) <= 0 || formData.num.charCodeAt(i) >= 255) {
                                    topWin.layer.alert('数量不能包含中文，请重新输入');
                                    return false;
                                }
                            }
                        }
                        //版本校验
                        if (formData.version) {
                            for (var i = 0; i < formData.version.length; i++) {
                                if (formData.version.charCodeAt(i) <= 0 || formData.version.charCodeAt(i) >= 255) {
                                    topWin.layer.alert('版本不能包含中文，请重新输入');
                                    return false;
                                }
                            }
                        }
                        //lot不能包含中文
                        if (formData.lot) {
                            for (var i = 0; i < formData.lot.length; i++) {
                                if (formData.lot.charCodeAt(i) <= 0 || formData.lot.charCodeAt(i) >= 255) {
                                    topWin.layer.alert('LOT不能包含中文，请重新输入');
                                    return false;
                                }
                            }
                        }


                        //产地必填校验
                        // var originV = $('#origin').val();
                        if (!formData.origin) {
                            topWin.layer.alert("请选择产地！");
                            return;
                        }



                        //2025-05-16 数据校验，如果单位为PCS, 则数量，总数量，最小包装数量，中箱数量不能为小数或带有.00
                        if (formData.unit && formData.unit == 'PCS') {
                            debugger
                            var testReg = /^\d+$/;
                            //整箱数量
                            if (formData.fullQuantity && !testReg.test(formData.fullQuantity)) {
                                topWin.layer.msg("请勿输入小数点！");
                                return;
                            }
                            //最小包装数
                            if (formData.minQuantity && !testReg.test(formData.minQuantity)) {
                                topWin.layer.msg("请勿输入小数点！");
                                return;
                            }
                            //中箱数量
                            if (formData.middleQuantity && !testReg.test(formData.middleQuantity)) {
                                topWin.layer.msg("请勿输入小数点！");
                                return;
                            }
                            //数量
                            if (formData.num && !testReg.test(formData.num)) {
                                topWin.layer.msg("请勿输入小数点！");
                                return;
                            }
                        }
                        page.submitFlag = 1;
                        var loadIndex = topWin.layer.msg('处理中....', {
                            icon: 16,
                            shade: 0.2
                        });
                        var jsonStr = JSON.stringify(formData)
                        formData['optionJson'] = jsonStr
                        let postFormData = JSON.stringify(formData);
                        if (Number(formData.printerType) === 1) {
                            $.ajax({
                                url: g.ctx + 'pc/order/barcodePrinter/rest/print',
                                type: 'POST',
                                data: postFormData,
                                contentType: 'application/json',
                                complete: function () {
                                    topWin.layer.close(loadIndex)
                                },
                                success: function (data) {
                                    page.callBack()
                                    var iframe = document.getElementById('printDiv');
                                    iframe.src = g.ctx + 'pc/order/barcodePrinter/page/lookup?id=' + data[0].settingId;
                                    const settingId = data[0].settingId;
                                    page.handlePrintClose(settingId);
                                },
                                error: function (data) {
                                    page.submitFlag = 0;
                                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                }
                            });
                        } else {
                            $.ajax({
                                url: "http://localhost:8999/openport",
                                async: false,//同步
                                type: "get",
                                success: function () {
                                    $.ajax({
                                        url: g.ctx + 'pc/order/barcodePrinter/rest/print',
                                        type: 'POST',
                                        data: postFormData,
                                        contentType: 'application/json',
                                        complete: function () {
                                            page.submitFlag = 0;
                                            topWin.layer.close(loadIndex)
                                        },
                                        success: function (data) {
                                            page.callBack()
                                            localStorage.setItem("printDataKey", JSON.stringify(data));
                                            if (Number(formData.printerType) === 2) {
                                                var iframe = document.getElementById('printDiv');
                                                iframe.src = g.ctx + 'pc/order/barcodePrinter/page/dpi200';
                                            } else {
                                                var iframe = document.getElementById('printDiv');
                                                iframe.src = g.ctx + 'pc/order/barcodePrinter/page/dpi300';
                                            }
                                        },
                                        error: function (data) {
                                            page.submitFlag = 0;
                                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                        }
                                    });
                                },
                                error: function (data) {
                                    page.submitFlag = 0;
                                    topWin.layer.close(loadIndex)
                                    topWin.layer.alert("请先开启打印脚本!!!", {icon: 2});
                                }
                            })
                        }
                    }
                },
                {
                    text: '关闭',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        page.printSettingDialog.dialog('close');
                    }
                }
            ]
        });
    },
    callBack: function () {
        page.printSettingDialog.dialog('close')
        page.submitFlag = 0;
        $("#tb").edatagrid("reload")
    },
    handlePrintClose: function (settingId) {
        topWin.layer.open({
            content: "请确认是否完成打印？",
            btn: ['已打印', '未打印'],
            btn1: function(alert) {
                topWin.layer.close(alert);
                $.ajax({
                    url: g.ctx + 'pc/order/barcodePrinter/rest/updatePrintSize',
                    async: false,//同步
                    type: "post",
                    data: {id : settingId},
                    success: function () {
                        $("#tb").edatagrid("reload")
                    }
                });
            }
        });
    }
}
$(function () {
    page.initTable()

})