let el = {
    tb: '#tb',
    orderCode: '#orderCode',
    searchForm: '#searchForm',
    bodyHeight: document.documentElement.clientHeight,
    poCode: "#poCode",
    materialCodeOrName: "#materialCodeOrName",
    formDialog: null,
    ftpDialog: null,
    printOrder: "#printOrder"
};
let uploadAttachmentFileDialog;
let attachmentFileDetailDialog;
let accountStatementCodeList;
let invoiceCodeList;

function initDataGrid() {
    let searchHeight = $(el.searchForm).outerHeight();
    let pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).edatagrid({
        url: g.ctx + 'pc/order/deliveryOrder/rest/list',
        method: "GET",
        queryParams: {page: 1, rows: 10, delFlag: '0'},
        singleSelect: false,
        loadMsg: '数据远程载入中,请等待...',
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        checkbox: true,
        height: el.bodyHeight - searchHeight,
        frozenColumns: [
            [
                {
                    field: 'ck', checkbox: true
                }, {
                field: 'state', title: '状态', align: 'left', width: 100, formatter: function (value, row) {
                    if (!value) {
                        return ""
                    }
                    if (row.delFlag === 1) {
                        return "<span style='color: red;' >删除</span>"
                    }
                    if (value === 1) {
                        return "<span style='color: yellowgreen;' >新建</span>"
                    }
                    if (value === 2) {
                        return "已发货"
                    }
                    if (value === 3) {
                        return "<span style='color: seagreen;' > 已完成 </span>"
                    }
                }
            }, {
                field: 'shipmentSapStatus', title: '推送sap交货单状态', align: 'left', width: 120,
                exportEnum:[
                    {code:0,codeWithDesc:'未推送'},
                    {code:1,codeWithDesc:'无需推送'},
                    {code:2,codeWithDesc:'推送成功'},
                    {code:3,codeWithDesc:'推送失败'},
                ],
                formatter: function (value, row) {
                    if (isBlank(value)) {
                        return ""
                    }
                    switch (Number(value)) {
                        case 0:
                            return '<span style="color: grey;">未推送</span>';
                        case 1:
                            return '<span style="color: green;">无需推送</span>';
                        case 2:
                            return '<span style="color: green;">推送成功</span>';
                        case 3:
                            return '<span style="color: red;" title="'+row.shipmentSapMsg+'">推送失败</span>';
                        default:
                            return '';
                    }
                }
            },
                {
                    field: 'returnConfirmStatus', title: '退货确认', align: 'left', width: 100,sortable: true,
                    exportEnum:[
                        {code:0,codeWithDesc:''},
                        {code:1,codeWithDesc:'未确认'},
                        {code:2,codeWithDesc:'已确认'},
                    ],
                    formatter: function (value, row) {
                        //退货确认状态；0-空；1-未确认；2-确认
                        if (isBlank(value)) {
                            return ""
                        }
                        switch (Number(value)) {
                            case 0:
                                return '';
                            case 1:
                                return "<a href='javascript:void(0)' style='color: red;' onclick=\"lookReceiveVoucher('" + row.orderCode + "')\">" + "未确认" + "</a>";
                            case 2:
                                return "<a href='javascript:void(0)' style='color: green;' onclick=\"lookReceiveVoucher('" + row.orderCode + "')\">" + "已确认" + "</a>";
                            default:
                                return '';
                        }
                    }
                }
            ]
        ],
        columns: [[ {
            field: 'createTime', title: '创建日期', width: 130,
            sortable: true
        }, {
            field: 'orderCode', title: '送货单号', width: 120,
            sortable: true
        },{
            field: 'entrustNo', title: '委托单号', width: 150,
            sortable: true
        },
            {
                field: 'directShipment', title: '送货方式', width: 120,
                exportEnum:getDictList('delivery_type'),
                formatter:function (value){
                    return getDicName("delivery_type",value)
                }
            },
            {field: 'appointmentCode', title: '预约单号', width: 120,
                sortable: true},
            {
                field: 'supplierErpCode', title: '供应商编码', width: 100,
                sortable: true
            }, {
                field: 'supplierName', title: '供应商名称', width: 260, sortable: true
            }, {
                field: 'deliveryDate', title: '发货日期', width: 100,
                sortable: true
            }, {
                field: 'planDeliveryDateStr', title: '到货日期', width: 100,
                sortable: true
            }, {field: 'remark', title: '备注', width: 200,
                sortable: true}, {
                field: 'companyName', title: '公司', width: 200, sortable: true
            },
            {
                field: 'factoryCode', title: '工厂', width: 200,
                sortable: true,
                formatter: function (value) {
                    return getNecessaryDataName("pc/sys/factory/rest/allList", value);
                }
            },
            {
                field: 'receiverAddress', title: '收货地址', width: 200,
                formatter: function (value) {
                    return '<span title="' + value + '">' + value + '</span>'
                },
                sortable: true
            },
            {
                field: 'purchaseGroupName', title: '采购组', width: 120, formatter: function (value, row) {
                    if (!value) {
                        return "";
                    }
                    return row.purchaseGroupCode + "-" + value;
                },
                sortable: true
            },
            {
                field: 'fileIds', title: '出货检验报告', width: 120, align: 'left', formatter: function (value, row) {
                    if (value !== "") {
                        return "<a href='javascript:void(0)' onclick=\"lookQuoteSituation('" + row.id + "')\">" + "点击查看(已上传)" + "</a>";
                    } else {
                        return '<a style="color:red;">未上传</a>';
                    }
                }
            },
            {
                field: 'attachmentFiles', title: '送货单附件', width: 120, align: 'left', formatter: function (value, row) {
                    if (value !== "") {
                        return "<a href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.orderCode +"', '" + row.supplierErpCode +"')\">" + "点击查看(已上传)" + "</a>";
                    } else {
                        return "<a style='color:red;' href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.orderCode +"', '" + row.supplierErpCode +"')\">" + "点击上传(未上传)" + "</a>";
                    }
                }
            }]],
        toolbar: [{
            text: '导出', id: 'btn_export', iconCls: 'icon-download', handler: function () {
                //导出
                setOperationLog("导出按钮", "送货单");
                openExportDialog("pc/order/deliveryOrder/rest/export", 'tb', searchParams())
            }
        }, "-", {
            text: '编辑', id: 'btn_edit', iconCls: 'icon-edit', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length != 1) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                let row = rows[0];
                if (row.delFlag === 1) {
                    topWin.layer.msg("此单已删除");
                    return;
                }
                if (row.state !== 2) {
                    topWin.layer.msg("只有已发货状态可以修改");
                    return;
                }
                setOperationLog("编辑按钮", "送货单");
                var url = g.ctx + "pc/order/deliveryOrder/page/edit?id=" + row.id;
                var deliveryCreateDialog = openDialog("deliveryCreateDialog", url, {
                    title: '送货单修改',
                    width: '100%',
                    height: '100%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        deliveryCreateDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: '提交', iconCls: 'icon-save', handler: function () {
                            topWin.frames['deliveryCreateDialog'].submit(function () {
                                topWin.layer.msg('修改成功', {icon: 1});
                                deliveryCreateDialog.dialog('close');
                                $(el.tb).datagrid('reload');
                                $(el.tb).datagrid('clearChecked');
                            }, 1);
                        }
                    }, {
                        text: '关闭', iconCls: 'icon-cancel', handler: function () {
                            deliveryCreateDialog.dialog('close');
                        }
                    }]
                })
            }
        }, "-", {
            text: '查看', id: 'btn_detail', iconCls: 'icon-search', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length != 1) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                setOperationLog("查看按钮", "送货单");
                let row = rows[0];
                var url = g.ctx + "pc/order/deliveryOrder/page/createOrUpdate?type=2&id=" + row.id;
                var deliveryCreateDialog = openDialog("deliveryCreateDialog", url, {
                    title: '送货单查看',
                    width: '100%',
                    height: '100%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        deliveryCreateDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: '关闭', iconCls: 'icon-cancel', handler: function () {
                            deliveryCreateDialog.dialog('close');
                        }
                    }]
                })
            }
        }, "-", {
            text: "打印", id: 'btn_print', iconCls: 'icon-print', handler: function () {
                printBarcode();
            }
        }, "-", {
            text: "出货检验报告上传", id: 'btn_file', iconCls: 'icon-add', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length != 1) {
                    layer.msg("请选中一条记录");
                    return;
                }
                $("#detailUpload .filebox-label").click();
            }
        }, "-", {
            text: "出货检验报告一键下载", id: 'btn_batch_download', iconCls: 'icon-download', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length < 1) {
                    layer.msg("请选中一条记录");
                    return;
                }
                let ids = [];
                for (let i = 0; i < rows.length; i++) {
                    if (rows[i].fileIds != '') {
                        ids = ids.concat(rows[i].fileIds.split(","));
                    }
                }
                for (const id of ids) {
                    //创建标签；
                    var iframe = document.createElement('iframe');
                    //该标签不显示；目的是在页面不要显示该标签；
                    iframe.style.display = "none";
                    //设置高度为0；
                    iframe.style.height = 0;
                    //设置下载路径
                    iframe.src = g.ctx + "pc/sys/file/rest/download/" + id;
                    // 这一行必须有，iframe绑定在dom树上才会发请求
                    document.body.appendChild(iframe);
                    // 1分钟之后删除该标签
                    setTimeout(function () {
                        iframe.remove();
                    }, 60 * 1000);
                }
            }
        }, "-", {
            text: "预约送货", id: 'btn_booking', iconCls: 'icon-book-add', handler: function () {
                let rows = $('#tb').datagrid('getChecked');
                if (rows.length <= 0) {
                    topWin.layer.msg("请选中至少一条记录");
                    return;
                }
                //我需要判断rows中的元素的directShipment属性是否=2
                let isAppointment = rows.every(row => row.directShipment !== 2);
                if (!isAppointment) {
                    topWin.layer.msg("物流或快递不允许预约!");
                    return;
                }
                // //判断是否需要预约
                // if (!isAppointment) {
                //     topWin.layer.msg("该订单不需要预约");
                //     return;
                // }
                // 检查 rows 中的每个元素的 appointmentCode 是否全部是 ''
                const allAppointmentCodesEmpty = rows.every(row => row.appointmentCode === '');
                if (!allAppointmentCodesEmpty) {
                    topWin.layer.msg("选中的记录存在已预约的数据，不可再预约");
                    return;
                }
                // 检查 rows 中的所有元素的 factoryCode 是否一致
                const firstFactoryCode = rows[0].factoryCode;
                const allFactoryCodesSame = rows.every(row => row.factoryCode === firstFactoryCode);

                if (!allFactoryCodesSame) {
                    topWin.layer.msg("选中的记录中 factoryCode 不一致");
                    return;
                }

                // 检查 rows 中的所有元素的 factoryCode 是否一致
                const supplierErpCode = rows[0].supplierErpCode;
                const allsupplierErpCodesSame = rows.every(row => row.supplierErpCode === supplierErpCode);

                if (!allsupplierErpCodesSame) {
                    topWin.layer.msg("选中的记录中 供应商 不一致");
                    return;
                }
                // 提取所有元素的 id 并用逗号拼接
                const ids = rows.map(row => row.id);
                let url = g.ctx + 'pc/order/appointmentRecord/appointment?ids=' + ids.join(",")
                    + "&factoryCode=" + rows[0].factoryCode + "&dockerCode=" + rows[0].dockerCode + "&supplierCode=" + rows[0].supplierErpCode + "&supplierName=" + rows[0].supplierName;
                var appointmentDialog = openDialog("appointmentDialog", url, {
                    title: "预约送货",
                    width: '776',
                    height: '96%',
                    cache: false,
                    modal: true,
                    border: false,
                    draggable: true,
                    shadow: false,
                    onClose: function () {
                        appointmentDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: '插队',
                        iconCls: 'icon-save',
                        handler: function () {
                            topWin.frames['appointmentDialog'].submit(1, function (data) {
                                $(el.tb).datagrid('reload');
                                $(el.tb).datagrid('clearChecked');
                                appointmentDialog.dialog('close');
                            });
                        }
                    }, {
                        text: '预约',
                        iconCls: 'icon-save',
                        handler: function () {
                            topWin.frames['appointmentDialog'].submit(0, function (data) {
                                $(el.tb).datagrid('reload');
                                $(el.tb).datagrid('clearChecked');
                                appointmentDialog.dialog('close');
                            });
                        }
                    }, {
                        text: '关闭',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            appointmentDialog.dialog('close');
                        }
                    }]
                });
            }
        }, "-", {
            text: "补打", id: 'btn_reprint', iconCls: 'icon-print', handler: function () {
                rePrintBarcode();
            }}, "-", {
            text: "送货单附件上传", id: 'btn_attachment_file', iconCls: 'icon-add', handler: function () {
                let rows = $(el.tb).datagrid('getChecked');
                if (rows.length !== 1) {
                    layer.msg("请选中一条记录");
                    return;
                }
                var businessTypeCode = ''
                //判断送货单号是否以“H”开头
                if (rows[0].orderCode.indexOf('H') !== 0) {
                    businessTypeCode = eSignBusinessTypeCodeEnum.OVERSEAS_DELIVERY_ORDER;
                }else {
                    businessTypeCode = eSignBusinessTypeCodeEnum.DELIVERY_ORDER;
                }
                // uploadAttachmentFile();
                openCommonFileDialog('commonFileDialog',{
                    //业务类型编码
                    title:'送货单附件上传',
                    //业务类型编码
                    businessTypeCode:businessTypeCode,
                    businessCode:rows[0].orderCode,
                    //业务唯一id
                    businessId:rows[0].id,
                    callBack : function () {
                        $(el.tb).datagrid('reload');
                    },
                });
            }
        }, "-", {
            text: "维护委托单号", id: 'btn_entrust', iconCls: 'icon-edit', handler: function () {
                var row = $(el.tb).datagrid('getSelected');
                if (!row) {
                    topWin.layer.alert('请选中一条记录', {icon: 0});
                    return false;
                }
                var id = row.id;
                topWin.layer.prompt({title: "请填写委托单号", formType: 3, value: row.entrustNo, maxlength: 500}, function(text, index){
                    if(text ===''){
                        topWin.layer.msg('请填写委托单号', {icon: 2});
                        return;
                    }
                    var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                    $.ajax({
                        url: g.ctx + 'pc/order/deliveryOrder/rest/setEntrustNo',
                        method: "post",
                        data: {id: id,entrustNo:text},
                        success: function () {
                            topWin.layer.close(index);
                            topWin.layer.msg('数据保存成功', {icon: 1});
                            $(el.tb).datagrid('reload');
                            $(el.tb).datagrid('clearSelections');
                        },
                        complete: function(data) {
                            topWin.layer.close(loading);
                        },
                        error: function (data) {
                            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                        }
                    });
                });
            }
        },"-",
            {
                text: 'SAP交货单推送',
                iconCls: 'icon-ok',
                id: 'btn_sap_send',
                handler: function () {
                    pushDeliveryToSap();
                }
            },
            "-",
            {
                text: '退货确认',
                iconCls: 'icon-ok',
                id: 'btn_return_confirm',
                handler: function () {
                    updateReturnConfirmStatus();
                }
            },
            "-",
            {
                text: '获取ftp附件',
                iconCls: 'icon-ok',
                id: 'btn_ftp',
                handler: function () {
                    var url = g.ctx + 'pc/order/deliveryOrder/page/ftpDialog';
                    el.ftpDialog = openDialog('ftpDialog', url, {
                        title: '线下购销合同上传',
                        width: '500',
                        height: '450',
                        cache: false,
                        modal: true,
                        border: 'thin',
                        onClose: function () {
                            el.ftpDialog.dialog('destroy');
                        },
                        buttons: [
                            {
                                text: '执行',
                                iconCls: 'icon-save',
                                handler: function () {
                                    topWin.frames['ftpDialog'].confirm(function (param) {
                                        var formData = new FormData()
                                        formData.append("startDate",param.startDate)
                                        formData.append("endDate",param.endDate)
                                        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                                        $.ajax({
                                            url: g.ctx + 'pc/order/deliveryOrder/rest/getFtp',
                                            type: 'POST',
                                            data: formData,
                                            processData: false,
                                            contentType: false,
                                            success: function () {
                                                el.ftpDialog.dialog('close');
                                                topWin.layer.msg('操作成功', {icon: 1});
                                                $(el.tb).datagrid('reload');
                                            },
                                            complete: function(data) {
                                                top.layer.close(loading);
                                            },
                                            error: function (data) {
                                                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                                            }
                                        });
                                    });
                                }
                            },
                            {
                                text: '取消',
                                iconCls: 'icon-cancel',
                                handler: function () {
                                    el.contractFileUpload.dialog('close');
                                }
                            }
                        ]
                    });
                }
            }
        ],
        onBeforeLoad: function () {
            displayButtonByUserRole('deliveryOrder');
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        }
    });
}

function lookReceiveVoucher(orderCode){
    var url = g.ctx + 'pc/order/deliveryOrder/page/lookReceiveVoucher?orderCode='+orderCode;
    el.ftpDialog = openDialog('ftpDialog', url, {
        title: '入库凭证',
        width: '80%',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.ftpDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.ftpDialog.dialog('close');
                }
            }
        ]
    });

}
function pushDeliveryToSap() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length===0) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        if (Number(row.shipmentSapStatus) === 0 || Number(row.shipmentSapStatus) === 3) {
            ids.push(row.id);
        } else {
            topWin.layer.alert('送货单号: ' + row.orderCode + ', 不可以推送交货单', {icon: 0});
            return false;
        }
    }

    topWin.layer.confirm('您确定要推送选中的送货单吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/order/deliveryOrder/rest/pushDeliveryToSap',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('操作成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}
function updateReturnConfirmStatus() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length===0) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        if (Number(row.returnConfirmStatus) === 1 ) {
            ids.push(row.id);
        } else {
            topWin.layer.alert('送货单号: ' + row.orderCode + ', 不可以退货确认', {icon: 0});
            return false;
        }
    }

    topWin.layer.confirm('您确定要确认选中的送货单吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/order/deliveryOrder/rest/updateReturnConfirmStatus',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                topWin.layer.msg('操作成功', {icon: 1});
                $(el.tb).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

function lookQuoteSituation(id) {
    let url = g.ctx + "pc/order/deliveryOrder/page/attachment?id=" + id;
    const btns = [{
        text: itablei8n.close, handler: function () {
            attachmentDialog.dialog('close');
        }
    }]
    attachmentDialog = openDialog("attachmentDialog", url, {
        title: "出货检验报告",
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            attachmentDialog.dialog('destroy');
        },
        buttons: btns
    })
}

function fileUpdate() {
    debugger;
    let rows = $('#tb').datagrid('getChecked');
    if (rows.length != 1) {
        layer.msg("请选中一条记录");
        return;
    }
    var row = rows[0];
    var addFiles = [];
    var files = $("#detailFileInput").filebox('files'), formData = new FormData();
    for (var r = 0; r < files.length; r++) {
        addFiles.push(files[r]);
    }
    for (var n = 0; n < addFiles.length; n++) {
        formData.append('files', addFiles[n]);
    }
    fileUploadAjaxWithCall(formData, function (fileRows) {
        // 使用 map 方法提取id属性并组装成新数组
        let idArray = fileRows.map(obj => obj.id);
        const postData = []
        for (const idArrayElement of idArray) {
            postData.push({
                fileId: idArrayElement, masterId: row.id
            })
        }

        $.ajax({
            url: g.ctx + 'pc/order/deliveryOrder/rest/saveAttachment',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(postData),
            success: function () {
                topWin.layer.msg('保存成功', {icon: 1});
                $("#file_table").datagrid('reload');
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    }, true)
}

function printById(ids) {
    var iframe = document.getElementById('printOrder');
    iframe.src = g.ctx + 'pc/order/deliveryOrder/page/print?ids=' + ids.join(",");
}

async function printBarcode() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length <= 0) {
        topWin.layer.alert("至少选择一条数据进行打印", {icon: 0});
        return false;
    }
    let tipMsg = [];
    let ids = [];
    for (const itm of rows) {
        ids.push(itm.id);
        if (itm.delFlag === 1) {
            tipMsg.push("送货单" + itm.orderCode + "已删除");
            return true;
        }
        if (itm.state !== 2) {
            tipMsg.push("送货单" + itm.orderCode + "不是发货状态");
        }
        //需要判断是否是预约供应商
        if (itm.isAppointment === 1 && itm.printLock === 1) {
            //tipMsg.push("送货单" + itm.orderCode + "需要预约送货完成");
        } else if (itm.isAppointment === 0 && itm.printLock === 1) {
            //tipMsg.push("送货单" + itm.orderCode + "需要预约送货完成");
        }

        if (itm.directShipment === 1 && itm.appointmentCode === "") {
            tipMsg.push("送货单" + itm.orderCode + "需要预约送货完成");
        }

        // 出货检验报告是否必填判断
        if ((itm.fileIds === "" || itm.fileIds === null)) {
            await $.ajax({
                url: g.ctx + 'pc/sys/supplierOrderFileSetting/rest/getBySupplierCode',
                method: "GET",
                data: {
                    supplierCode: itm.supplierErpCode
                },
                success: function(data) {
                    if (data && data.requiredFlag === "1") {
                        tipMsg.push("请上传出货检验报告" + "(送货单:" + itm.orderCode + ")");
                    }
                }
            });
        }
    }
    if (tipMsg.length > 0) {
        topWin.layer.msg(tipMsg.join("</br>"));
        return;
    }
    printById(ids);
}

async function rePrintBarcode() {
    var rows = $(el.tb).datagrid('getSelections');
    if (rows.length <= 0) {
        topWin.layer.alert("至少选择一条数据进行打印", {icon: 0});
        return false;
    }
    let tipMsg = [];
    let ids = [];
    for (const itm of rows) {
        ids.push(itm.id);
        if (itm.delFlag === 1) {
            tipMsg.push("送货单" + itm.orderCode + "已删除");
            return true;
        }
        // if (itm.state !== 2) {
        //     tipMsg.push("送货单" + itm.orderCode + "不是发货状态");
        // }
        //需要判断是否是预约供应商
        if (itm.isAppointment === 1 && itm.printLock === 1) {
            tipMsg.push("送货单" + itm.orderCode + "需要预约送货完成");
        } else if (itm.isAppointment === 0 && itm.printLock === 1) {
            tipMsg.push("送货单" + itm.orderCode + "需要预约送货完成");
        }

        // 出货检验报告是否必填判断
        if ((itm.fileIds === "" || itm.fileIds === null)) {
            await $.ajax({
                url: g.ctx + 'pc/sys/supplierOrderFileSetting/rest/getBySupplierCode',
                method: "GET",
                data: {
                    supplierCode: itm.supplierErpCode
                },
                success: function(data) {
                    if (data && data.requiredFlag === "1") {
                        tipMsg.push("请上传出货检验报告" + "(送货单:" + itm.orderCode + ")");
                    }
                }
            });
        }
    }
    if (tipMsg.length > 0) {
        topWin.layer.msg(tipMsg.join("</br>"));
        return;
    }
    printById(ids);
}

function uploadAttachmentFile() {
    debugger;
    const url = g.ctx + "pc/sys/businessAttachment/fileUploadWithType";
    uploadAttachmentFileDialog = openDialog("uploadAttachmentFileDialog", url, {
        title: '送货单附件上传',
        width: '400px',
        height: '250px',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            uploadAttachmentFileDialog.dialog('destroy');
        },
        onOpen: function() {
            // dialog打开后，等待iframe加载完成
            const iframe = $(this).find('iframe')[0];
            iframe.onload = function() {
                // 将父页面的函数引用传递给iframe
                iframe.contentWindow.parentCallback = receiveFileUploadData;
            };
        },
        buttons: [{
            text: '继续', iconCls: 'icon-save', handler: function () {
                topWin.frames['uploadAttachmentFileDialog'].openFileUploader();
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                uploadAttachmentFileDialog.dialog('close');
            }
        }]
    });
}

function receiveFileUploadData(data) {
    let rows = $(el.tb).datagrid('getChecked');
    let businessData = [];
    for (let i = 0; i < rows.length; i++) {
        const businessId = rows[i].id;
        const businessCode = rows[i].orderCode;
        data.forEach(item => {
            // 创建新对象，深拷贝原对象
            const newItem = {
                ...item,            // 展开运算符拷贝所有属性
                businessId: businessId, // 添加新的businessId
                businessCode: businessCode,
                businessTypeCode: "delivery_order"
            };
            businessData.push(newItem);
        });
    }

    $.ajax({
        url: g.ctx + 'pc/sys/businessAttachment/rest/save',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(businessData),
        success: function () {
            topWin.layer.msg('保存成功', {icon: 1});
            $(el.tb).datagrid('reload');
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

    uploadAttachmentFileDialog.dialog('close');
}

/**
 * 送货单附件
 */
function viewAttachmentFileDetail(businessId, businessCode,supplierErpCode) {
    //当送货单单头为“九立-1001或者”朗华-5012“时判断当前用户编码，与送货单单头供应商编码不一致时，不能打开“送货单附件“栏位的文件查看弹窗
    // （分配物流商角色权限，使用按钮”送货单附件上传“按钮）
    if (supplierErpCode==='1001'||supplierErpCode==='5012'){
        if (userCode!==supplierErpCode&&userCode!=='admin'){
            topWin.layer.alert("当前用户编码与送货单单头供应商编码不一致，不能打开“送货单附件“栏位的文件查看弹窗", {icon: 0});
            return false;
        }

    }
    const businessTypeCode = "delivery_order";
    let url = g.ctx + "pc/sys/businessAttachment/businessAttachmentDetail?businessId="
        + businessId + "&businessCode=" + businessCode + "&businessTypeCode=" + businessTypeCode;
    const buttons = [{
        text: itablei8n.close, handler: function () {
            attachmentFileDetailDialog.dialog('close');
        }
    }]
    attachmentFileDetailDialog = openDialog("attachmentFileDetailDialog", url, {
        title: '送货单附件',
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        buttons: buttons,
        onClose: function () {
            attachmentFileDetailDialog.dialog('destroy');
        },
        // onOpen: function() {
        //     // dialog打开后，等待iframe加载完成
        //     const iframe = $(this).find('iframe')[0];
        //     iframe.onload = async function() {
        //         await $.ajax({
        //             type: 'get',
        //             url: g.ctx + 'pc/order/deliveryOrder/rest/findAccountStatement?id=' + businessId,
        //             async: false,
        //             success: function (data) {
        //                 accountStatementCodeList = data;
        //             }, error: function (data) {
        //                 topWin.layer.close(index);
        //                 topWin.layer.alert(data.responseJSON.message, {icon: 2});
        //             }
        //         });
        //         // 将父页面的函数引用传递给iframe
        //         // iframe.contentWindow.uploadValidation = accountStatementExistValidation;
        //         iframe.contentWindow.deleteValidation = accountStatementExistValidation;
        //         // iframe.contentWindow.remarkValidation = accountStatementExistValidation;
        //     };
        // }
    })
}

function accountStatementExistValidation() {
    let result = {
        isError: false,
        message: ''
    };
    if (accountStatementCodeList && accountStatementCodeList.length && accountStatementCodeList.length > 0) {
        result.isError = true;
        result.message = "该送货单已有关联对账单，对账单号：" + accountStatementCodeList.join("、");
    }
    return result;
}

$(function () {
    initDict("delivery_type")
    initNecessaryData("pc/sys/factory/rest/allList")
    // 加载表格
    initDataGrid();
});