var page = {
    submitFlag: 0,
    initTable: function () {
        var tbH = document.documentElement.clientHeight - $("#searchForm").outerHeight() - 20
        let pager = initGridPagerNew(tbH, 37, 40);
        $("#tb").edatagrid({
                url: g.ctx + 'pc/order/barcodePrinter/rest/labelList?ids=' + ids,
                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: 'boxType', title: '类型', align: 'left', width: 45, formatter: function (value) {
                            if (value === "P") {
                                return "内"
                            }
                            if (value === "B") {
                                return "外"
                            }
                            if (value === "M") {
                                return "中"
                            }
                        }
                    },
                    {
                        field: 'status', title: '推送状态', align: 'left', width: 70, formatter: function (value) {
                            if (value === 1) {
                                return "成功"
                            }
                            return "<span style='color: red'>失败</span>"
                        }
                    },
                    {
                        field: 'settingId', title: '来源', align: 'left', width: 80, formatter: function (value) {
                            if (value === "") {
                                return "<span style='color: red;'>导入</span>"
                            }
                            return '正常'
                        }
                    },
                    {
                        field: 'importCode', title: '导入批次号', align: 'left', width: 240
                    },
                    {
                        field: 'orderNumber', title: '采购订单号', align: 'left', width: 80
                    },
                    {
                        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: 'materialCode', title: '物料编号', align: 'left', width: 100
                    },
                    {
                        field: 'barcodeSerialNumber', title: '条码', align: 'left', width: 170
                    },
                    {
                        field: 'outsideBarcodeSerialNumber', title: '外箱条码', align: 'left', width: 170
                    },
                    {
                        field: 'barcodeContent', title: '条码内容', align: 'left', width: 540
                    },
                    {
                        field: 'quantity', title: '最小包装数', align: 'left', width: 74
                    },
                    {
                        field: 'innerBoxQuantity', title: '内箱张数', align: 'left', width: 64
                    },
                    {
                        field: 'supplierCode', title: '供应商编号', align: 'left', width: 74
                    },
                    {
                        field: 'supplierName', title: '供应商名称', align: 'left', width: 200
                    },
                    {
                        field: 'printSize', title: '打印次数', align: 'left', width: 64
                    },
                    {
                        field: 'printTime', title: '打印时间', align: 'left', width: 135
                    }
                ]],
                toolbar: [{
                    text: '打印', id: 'btn_all', iconCls: 'icon-print', handler: async function () {
                        const table = $('#tb');
                        let rows = table.datagrid('getChecked');
                        if (rows.length !== 1) {
                            topWin.layer.msg("请选中一条记录");
                            return;
                        }
                        // 1. 保存当前选中行的ID
                        const checkedIds = table.datagrid('getChecked').map(row => row.id);

                        // 先获取最新数据
                        const reloadDataGrid = () => {
                            return new Promise((resolve) => {
                                table.datagrid({
                                    onLoadSuccess: (data) => {
                                        // 3. 重新选中之前选中的行
                                        if (checkedIds.length > 0) {
                                            table.datagrid('unselectAll'); // 先清空所有选中
                                            const allRows = table.datagrid('getRows'); // 获取所有行数据
                                            checkedIds.forEach(id => {
                                                // 手动查找行索引
                                                const rowIndex = allRows.findIndex(row => row.id === id);
                                                if (rowIndex >= 0) {
                                                    table.datagrid('selectRow', rowIndex); // 通过索引选中
                                                }
                                            });
                                        }
                                        resolve(data.rows);
                                    }
                                }).datagrid('reload'); // 触发异步重载
                            });
                        };
                        await reloadDataGrid();

                        rows = table.datagrid('getChecked');
                        // 检查打印次数（使用Promise封装alert回调）
                        const checkPrintCount = () => {
                            return new Promise((resolve) => {
                                if (rows[0].printSize > 1) {
                                    topWin.layer.open({
                                        content: "该条码已经打印了" + rows[0].printSize + "次，需要重复打印吗",
                                        btn: ['打印', '取消'],
                                        btn1: function(alert) {
                                            topWin.layer.close(alert);
                                            resolve(true);
                                        }
                                    });
                                } else {
                                    resolve(true);
                                }
                            });
                        };

                        // 等待用户确认打印次数提示
                        await checkPrintCount();

                        //需要判断rows中的printerType属性是否都是一样的，如果不一样提示
                        if (rows.some(row => row.printerType !== rows[0].printerType)) {
                            topWin.layer.msg("请选择同一类型打印机进行打印");
                            return;
                        }
                        let ids = rows.map(row => row.id).join(',');
                        if (rows[0].printerType === 1) {
                            window.open(g.ctx + 'pc/order/barcodePrinter/page/lookup1?isPrint=1&ids=' + ids, '_blank');
                        } else {
                            $.ajax({
                                url: "http://localhost:8999/openport",
                                async: false,//同步
                                type: "get",
                                success: function () {
                                    $.ajax({
                                        url: g.ctx + 'pc/order/barcodePrinter/rest/getPrintDataByIds',
                                        type: 'GET',
                                        data: {ids: ids, isPrint: 1},
                                        success: function (data) {
                                            localStorage.setItem("printDataKey", JSON.stringify(data));
                                            if (rows[0].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_enhance_patchwork', iconCls: 'icon-print', handler: function () {
                        let rows = $('#tb').datagrid('getChecked');
                        if (rows.length < 1) {
                            topWin.layer.msg("请至少选中一条记录进行打印");
                            return;
                        }
                        //需要获取到rows元素的id组装成新的数组
                        let ids = rows.map(row => row.id).join(',');
                        window.open(g.ctx + 'pc/order/barcodePrinter/page/pdfPrints?ids=' + ids, '_blank');
                    }
                }, "-", {
                    text: '绑定关系导入', id: 'btn_import', iconCls: 'icon-import', handler: function () {
                        var importDialog = openImportExcelDialog('static/excel/绑定关系导入模板.xlsx', '绑定关系导入', function (file) {
                            let formData = new FormData();
                            formData.append("file", file);
                            var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                            var url = g.ctx + 'pc/order/barcodePrinter/rest/import'
                            $.ajax({
                                url: url, type: 'POST', data: formData, processData: false,
                                contentType: false,
                                async: true, // 设置为同步请求
                                complete: function () {
                                    $("#detailFileInput").filebox('clear')
                                    topWin.layer.close(loading);
                                },
                                success: function (obj) {
                                    topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                                        topWin.layer.close(idx);
                                        $('#tb').datagrid('reload');
                                        importDialog.dialog('close');
                                    });
                                }, error: function (data) {
                                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                }
                            });
                        });
                    }
                }, {
                    text: '批次重推', id: 'btn_replay', iconCls: 'icon-redo', handler: function () {
                        if (page.submitFlag === 1) {
                            return;
                        }
                        let rows = $('#tb').datagrid('getChecked');
                        if (rows.length <= 0) {
                            topWin.layer.msg("请选中至少一条记录");
                            return;
                        }
                        let a = rows.filter(a => a.settingId !== '')
                        if (a.length > 0) {
                            topWin.layer.msg("只有导入的标签允许批次重推操作!");
                            return;
                        }
                        let b = rows.filter(a => a.status === 1)
                        //重新推送给接口
                        if (b.length > 0) {
                            topWin.layer.msg("只有失败的数据才能重新推送");
                            return;
                        }
                        topWin.layer.confirm("是否确认推送?", function (index) {
                            let loadIndex = topWin.layer.msg('处理中...', {icon: 16, shade: [0.1, '#000'], time: false});
                            page.submitFlag = 1
                            $.ajax({
                                url: g.ctx + 'pc/order/barcodePrinter/rest/rePushByBatch',
                                type: 'POST',
                                data: {id: rows[0].id},
                                complete: function () {
                                    topWin.layer.close(loadIndex);
                                    page.submitFlag = 0
                                },
                                success: function (data) {
                                    //如果不是默认打印机需要调用下
                                    topWin.layer.msg("推送成功!");
                                    $("#tb").edatagrid("reload")
                                },
                                error: function (data) {
                                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                }
                            });
                        })


                    }
                }, {
                    text: '删除', id: 'btn_all', iconCls: 'icon-remove', handler: function () {
                        if (page.submitFlag === 1) {
                            return;
                        }
                        let rows = $('#tb').datagrid('getChecked');
                        if (rows.length <= 0) {
                            topWin.layer.msg("请选中至少一条记录");
                            return;
                        }
                        let a = rows.filter(a => a.settingId !== '')
                        if (a.length > 0) {
                            topWin.layer.msg("只有导入的标签允许删除操作!");
                            return;
                        }
                        let b = rows.filter(a => a.boxType === 'B')
                        if (b.length <= 0) {
                            topWin.layer.msg("只能整个外箱全部删除!");
                            return;
                        }
                        let ids = rows.filter(a => a.boxType === 'B').map(row => row.id).join(',');
                        topWin.layer.confirm("是否删除绑定关系?", function (index) {
                            let loadIndex = topWin.layer.msg('删除中...', {icon: 16, shade: [0.1, '#000'], time: false});
                            page.submitFlag = 1
                            $.ajax({
                                url: g.ctx + 'pc/order/barcodePrinter/rest/remove',
                                type: 'POST',
                                data: {ids: ids},
                                complete: function () {
                                    topWin.layer.close(loadIndex);
                                    topWin.layer.close(index);
                                    page.submitFlag = 0
                                },
                                success: function (data) {
                                    topWin.layer.alert("删除成功", {icon: 1}, function (idx) {
                                        topWin.layer.close(idx);
                                        $('#tb').datagrid('reload');
                                    });
                                },
                                error: function (data) {
                                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                }
                            });
                        })

                    }
                },
                    {
                        text: '批次删除', id: 'btn_all', iconCls: 'icon-remove', handler: function () {
                            if (page.submitFlag === 1) {
                                return;
                            }
                            let rows = $('#tb').datagrid('getChecked');
                            if (rows.length !== 1) {
                                topWin.layer.msg("请选中一条记录");
                                return;
                            }
                            let a = rows.filter(a => a.settingId !== '')
                            if (a.length > 0) {
                                topWin.layer.msg("只有导入的标签允许删除操作!");
                                return;
                            }
                            topWin.layer.confirm("是否批次删除绑定关系?", function (index) {
                                let loadIndex = topWin.layer.msg('删除中...', {
                                    icon: 16,
                                    shade: [0.1, '#000'],
                                    time: false
                                });
                                page.submitFlag = 1
                                $.ajax({
                                    url: g.ctx + 'pc/order/barcodePrinter/rest/removeByBatch',
                                    type: 'POST',
                                    data: {id: rows[0].id},
                                    complete: function () {
                                        topWin.layer.close(loadIndex);
                                        topWin.layer.close(index);
                                        page.submitFlag = 0
                                    },
                                    success: function (data) {
                                        topWin.layer.alert("删除成功", {icon: 1}, function (idx) {
                                            topWin.layer.close(idx);
                                            $('#tb').datagrid('reload');
                                        });
                                    },
                                    error: function (data) {
                                        topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                    }
                                });
                            })

                        }
                    }, {
                        text: '条码校验', iconCls: 'icon-help', handler: function () {
                            topWin.layer.prompt({
                                title: '请输入条码内容',
                                formType: 2
                            }, function (printContent, index, elem) {
                                if (printContent === '') return elem.focus();
                                var reg = /.*[\u4e00-\u9fa5]+.*$/;
                                var BarcodeReg = /[BPR]/g;
                                var msg = ""
                                if (parseInt(printContent.split('{').length) - 1 == 12) {
                                    var CPN = printContent.split('{')[0].trim();
                                    var QTY = printContent.split('{')[1].trim();
                                    var DC = printContent.split('{')[4].trim();
                                    var BarcodeNo = printContent.split('{')[8].trim();
                                    var Maunfacture = printContent.split('{')[10].trim();
                                    if (reg.test(printContent)) {
                                        msg = "二维码中不能含有汉字!!!      请确认";
                                    } else if (!(/(^[1-9]\d*$)/.test(QTY))) {
                                        msg = "二维码中数量不正确!!!      请确认";
                                    } else if (Maunfacture == "") {
                                        msg = "制造商不能为空!!!      请确认";
                                    } else if (!(/[BPR]/g.test(BarcodeNo))) {
                                        msg = "二维码中流水号不正确!!!      请确认";
                                    } else if (DC.length != 4) {
                                        msg = "DC周期不正确!!!    规则：年份+周数（2130）";
                                    }
                                } else {
                                    msg = "二维码格式不正确！！！      请确认";
                                }
                                if (msg === '') {
                                    topWin.layer.alert("校验通过", {icon: 1})
                                } else {
                                    topWin.layer.alert(msg, {icon: 2})
                                }
                            });

                        }
                    }, "-", {
                        id: 'export',
                        text: '导出',
                        iconCls: 'icon-undo',
                        handler: function () {
                            openExportDialog('pc/order/barcodePrinter/rest/export','tb',{ids: ids});
                        }
                    }
                ]
            }
        )
        ;
    }
}
$(function () {
    page.initTable()
})