/**
 * 交货管理-采购订单管理首页JS(购方)
 *
 * Created by likui on 2019/12/14.
 */
'use strict';
var el = {
    tb: '#tb',
    searchForm: '#searchForm',
    orderCode: '#orderCode',
    zlsdh: '#zlsdh',
    supplierErpCode: '#supplierErpCode',
    supplierName: '#supplierName',
    contractNo: '#contractNo',
    sapPoType: '#sapPoType',
    state: '#state',
    syncState: '#syncState',
    purchaseGroupCode: '#purchaseGroupCode',
    createUser: '#createUser',
    startCreateDate: '#startCreateDate',
    endCreateDate: '#endCreateDate',
    startEffectiveDate:'#startEffectiveDate',
    endEffectiveDate:'#endEffectiveDate',
    isSchedule: '#isSchedule',
    syncMaterialCode: "#syncMaterialCode",
    syncOrderDialog: '#syncOrderDialog',
    syncSupplierCode: '#syncSupplierCode',
    sapPoCode: '#sapPoCode',
    syncStartCreateDate: '#syncStartCreateDate',
    syncEndCreateDate: '#syncEndCreateDate',
    materialCode: '#materialCode',
    deleteFlag: '#deleteFlag',
    actualContract: '#actualContract',
    createName: '#createName',
    approvalPoDialog: null,
    againReleasePoDialog: null,
    lookPoDialog: null,
    tipsIndex: null,
    bodyHeight: document.documentElement.clientHeight,
    defaultColumns: []
};

$(function () {
    initDict("po_item_type")
    $("#fileInput").filebox({
        buttonText: 'Choose', buttonAlign: 'left', onChange: fileUpload
    });
    el.defaultColumns = [
        {
            field: 'confirmTime',
            title: '供应商确认时间',
            width: 115,
            sortable: true,
            formatter: function (value) {
                return DateFormatMs(value);
            },
        },
        {
            field: 'signStatus',
            title: '签署状态',
            width: 115,
            sortable: true,<!--按签署状态排序-->
            exportEnum: [
                {code: 0, codeWithDesc: '草稿'},
                {code: 1, codeWithDesc: '签署中'},
                {code: 2, codeWithDesc: '完成'},
                {code: 3, codeWithDesc: '已过期'},
                {code: 4, codeWithDesc: '已拒签'},
                {code: 5, codeWithDesc: '已作废'},
                {code: 6, codeWithDesc: '作废中'}
            ],
            formatter: function (value) {
                switch (value) {
                    case 0:
                        return '<span style="color: grey;">草稿</span>';
                    case 1:
                        return '<span style="color: blue;">签署中</span>';
                    case 2:
                        return '<span style="color: green;">完成</span>';
                    case 3:
                        return '<span style="color: orange;">已过期</span>';
                    case 4:
                        return '<span style="color: red;">已拒签</span>';
                    case 5:
                        return '<span style="color: dimgrey;">已作废</span>';
                    case 6:
                        return '<span style="color: blue;">作废中</span>';
                    default:
                        return '';
                }
            }
        },

        {
            field: 'finConf',
            title: '智微财务确认<br>(E签宝签章自动确认)',
            width: 115,
            sortable: true,
            exportEnum: [
                {code: 0, codeWithDesc: '未确认'},
                {code: 1, codeWithDesc: '已确认'}
            ],
            formatter: function (value, row) {
                if (row.orderTypeCode === 'Z003') {
                    return '<span style="color: grey;">无需确认</span>';
                } else {
                    switch (value) {
                        case 0:
                            return '<span style="color: red;">未确认</span>';
                        case 1:
                            return '<span style="color: blue;">已确认</span>';
                    }
                }

            }
        },
        {field: 'finUserName', title: '财务确认人', width: 100},
        {field: 'finTime', title: '财务确认时间', width: 130},
        {field: 'attachmentType', title: '附件类型', width: 100,
            formatter: function (value) {
                if (value === 0) {
                    return '<span style="color: #000000;">纸质附件</span>';
                }else if(value === 1){
                    return '<span style="color: #000000;">电子附件</span>';
                } else {
                    return '<span style="color: #ffffff;"></span>';
                }
            }},
        {
            field: 'fileState', title: '回签状态', align: 'center', width: 70, sortable: true,
            exportEnum: [
                {code: 0, codeWithDesc: '否'},
                {code: 1, codeWithDesc: '是'}
            ],
            formatter: function (value, row) {
                if (value === 0) {
                    return "<span style=\"color: red;\">否</span>"
                } else {
                    return "<span style=\"color: darkgreen;\">是</span>"
                }
            }
        },
        {field: 'supplierErpCode', title: '供应商编码', sortable: true, width: 120},
        {
            field: 'supplierName',
            title: '供应商名称',
            sortable: true,
            width: 160
        },
        {
            field: 'orderDate', title: '凭证日期', sortable: true, width: 130
        },
        {
            field: 'effectiveDate', title: '生效日期', sortable: true, width: 130
        },
        {field: 'orderCode', title: 'SAP订单号', sortable: true, width: 120},
        {
            field: 'rowTypeCode',
            title: '项目类别',
            width: 100,
            exportEnum: getDictList('po_item_type'),
            formatter: function (value) {
                return getDicName("po_item_type", value);
            }
        },
        {
            field: 'companyName', title: '公司', width: 120,
            sortable: true,
            formatter: function (value, row) {
                if (value) {
                    return '(' + row.companyCode + ')' + value;
                }
                return '';
            }
        },
        {
            field: 'supplierName1',
            title: '物流商',
            width: 120
        },
        {
            field: 'supplierName2',
            title: '关税报关公司',
            width: 120
        },
        {
            field: 'purchaseGroupName', title: '采购组', width: 120, formatter: function (value, row) {
                if (!value) {
                    return "";
                }
                return row.purchaseGroupCode + "-" + value;
            }
        },
        {field: 'createName', title: '创建人', width: 100},
        {
            field: 'orderTaxAmount', title: '含税总额', width: 100, formatter: function (value, row) {
                if (row.returnFlag === "X") {
                    return value * -1;
                }
                return value;
            }
        },
        // {
        //     field: 'aa', title: '附件', width: 100, formatter: function (value, row) {
        //         var sty = "";
        //         if (!row.fileSize) {
        //             sty = "color: #0C0C0C";
        //         }
        //         return '<a href="javascript:void(0)" style="' + sty + '" onclick="uploadRequireFileUI(this)" data-value="' + row.id + '">上传/下载</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.batchNo +"' )\">" + "点击查看(已上传)" + "</a>";
                } else {
                    return "<a style='color:red;' href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.orderCode +"', '" + row.batchNo +"' )\">" + "点击上传(未上传)" + "</a>";
                }
            }
        },
        {field: 'batchNo', title: '汇总单号', width: 120, sortable: true},
        {
            field: 'orderTypeName', title: '订单类型', width: 100, formatter: function (value, row) {
                if (!value) {
                    return "";
                }
                return row.orderTypeCode + "-" + value;
            }, sortable: true
        },
        {field: 'remark', title: '单头备注', width: 160, sortable: true},
        {
            field: 'purchaseOrgName',
            title: '采购组织',
            width: 120
        },
        {field: 'currencyName', title: '币别', width: 90},{field: 'refusalRemark', title: '回签拒绝原因', width: 130},{field: 'sumSignFlag', title: '签署状态', width: 100,
            formatter: function (value) {
                if (value === 0) {
                    return '<span style="color: grey;">汇总签</span>';
                } else {
                    return '<span style="color: red;"></span>';
                }
            }},{field: 'column1', title: '汇总签署文件', width: 90,hidden:true}]
    let column = getRemoteColumnSort(columnSortCodeEnum.PURCHASE_ORDER, el.defaultColumns);
    // 加载表格
    initDataGrid(column);

});
var attachmentDialog = {}
function viewAttachmentFileDetail(businessId, businessCode, batchNo) {
    //采购订单的“汇总单号”不为空时，不允许通过“其他附件”按钮和列表中的“其他附件“（点击上传（未上传））栏位 上传附件。
    if (!isBlank(batchNo)){
        topWin.layer.alert("采购订单的“汇总单号”不为空，不允许操作");
        return false;
    }
    debugger;
    const businessTypeCode = "purchase_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');
        }
    }]
    var 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/purchaseOrder/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});
        //             }
        //         });
        //
        //         await $.ajax({
        //             type: 'get',
        //             url: g.ctx + 'pc/sys/businessAttachment/rest/findInvoiceByFileId?id=' + fileId,
        //             async: false,
        //             success: function (data) {
        //                 invoiceCodeList = 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.deleteInvoiceValidation = invoiceExistValidation;
        //         // iframe.contentWindow.remarkValidation = accountStatementExistValidation;
        //     };
        // }
    })
}

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

function invoiceExistValidation() {
    let result = {
        isError: false,
        message: ''
    };
    debugger;
    if (invoiceCodeList && invoiceCodeList.length && invoiceCodeList.length > 0) {
        result.isError = true;
        result.message = "该订单已有关联开票申请单号，申请单号：" + invoiceCodeList.join("、");
    }
    return result;
}

/**
 * 初始化数据表格
 */
function initDataGrid(columns) {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).datagrid({
        url: g.ctx + 'pc/order/purchaseOrder/rest/list',
        queryParams: {deleteFlag: 0, states: "0,1,2,3", state: '6,7,11'},
        loadMsg: '数据远程载入中,请等待...',
        singleSelect: false,
        method: "GET",
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        checkbox: true,
        rownumbers: true,
        height: el.bodyHeight - searchHeight,
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'state', title: '状态', align: 'left', width: 100, sortable: true,
                    exportEnum: [
                        {code: 2, codeWithDesc: '订单不可用'},
                        {code: 6, codeWithDesc: '待供应商确认'},
                        {code: 7, codeWithDesc: '确认完成'},
                        {code: 8, codeWithDesc: '收货完成'},
                        {code: 9, codeWithDesc: '删除'},
                        {code: 11, codeWithDesc: '供应商拒收'},
                    ],
                    formatter: function (value, row) {
                        if (!value) {
                            return ""
                        }
                        // if (value === 1) {
                        //     return "新建"
                        // }
                        if (value === 2) {
                            return "<span style='color:red;' > 订单不可用 </span>"
                        }
                        // if (value === 3) {
                        //     return "<span style='color:red;' >订单审批驳回</span>"
                        // }
                        // if (value === 4) {
                        //     return "GMP审批中"
                        // }
                        // if (value === 5) {
                        //     return "<span style='color:red;' >GMP审批驳回</span>"
                        // }
                        if (value === 6) {
                            return "<span style='color:saddlebrown;' > 待供应商确认 </span>"
                        }
                        if (value === 7) {
                            return "<span style='color:royalblue;' > 确认完成 </span>"
                        }
                        if (value === 8) {
                            return "<span style='color:green;' > 收货完成 </span>"
                        }
                        if (value === 9) {
                            return "删除"
                        }
                        // if (value === 10) {
                        //     return "订单审批通过"
                        // }
                        if (value === 11) {
                            return "<span style='color:orangered;' >供应商拒收</span>"
                        }
                    }
                }
            ]
        ],
        columns: [columns],
        toolbar: [{
            text: '供方确认', id: 'btn_replay', iconCls: 'icon-man', handler: function () {
                let rows = $(el.tb).datagrid('getSelections');
                if (!rows || rows.length != 1) {
                    topWin.layer.msg("请选中一条订单");
                    return;
                }
                setOperationLog("供方确认按钮", "采购订单查询");
                let row = rows[0];
                if (row.state !== 6) {
                    topWin.layer.msg("请选择“待供方确认”状态订单");
                    return;
                }
                openConfiDialog(1, row.id);
            }
        }, {
            text: '答交', id: 'btn_replay_plan', iconCls: 'icon-back', handler: function () {
                let rows = $(el.tb).datagrid('getSelections');
                if (!rows || rows.length != 1) {
                    topWin.layer.msg("请选中一条订单");
                    return;
                }
                let row = rows[0];
                if (row.state !== 7) {
                    topWin.layer.msg("请选择“确认完成”状态订单");
                    return;
                }
                openConfiDialog(2, row.id);
            }
        }, {
            text: '查看', id: 'btn_detail', iconCls: 'icon-search', handler: function () {
                let rows = $(el.tb).datagrid('getSelections');
                if (!rows || rows.length != 1) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                setOperationLog("查看按钮", "采购订单查询");
                let row = rows[0];
                var lookupDialog = openDialog('lookupDialog', g.ctx + 'pc/order/purchaseOrder/page/lookup?id=' + row.id, {
                    title: '订单查看',
                    width: "90%",
                    height: "100%",
                    cache: false,
                    modal: true,
                    border: 'thin',
                    onClose: function () {
                        lookupDialog.dialog('destroy');
                    },
                    buttons: [{
                        text: '关闭', iconCls: 'icon-cancel', handler: function () {
                            lookupDialog.dialog('close');
                        }
                    }]
                });

            }
        }, '-', {
            text: '订单打印', id: 'btn_print', iconCls: 'icon-print', handler: function () {
                let rows = $(el.tb).datagrid('getSelections');
                if (!rows || rows.length != 1) {
                    topWin.layer.msg("请选中一条记录");
                    return;
                }
                setOperationLog("订单打印按钮", "采购订单查询");
                let row = rows[0];
                printOrder(row) // 选择物质类模板打印

            }
        }, "-", {
            text: '附件回签', id: 'btn_up', iconCls: 'icon-file-add', handler: function () {
                var row = $(el.tb).datagrid("getSelected");
                if (!row) {
                    topWin.layer.confirm("请选择一条数据");
                    return
                }
                setOperationLog("附件回签按钮", "采购订单查询");
                if(row.signStatus != 2){
                    topWin.layer.confirm("请先进行,'甲方单签',文件签署!");
                    return
                }
                $("#fileUpload .filebox-label").click();
            }
        }, "-", {
            text: '电子印章签署',
            iconCls: 'icon-sign',
            id: 'btn-sign',
            handler: function () {

                sendSign();
            }
        }, '-',
            {
                text: '查看签署文件',
                iconCls: 'icon-find',
                id: 'btn-sign-look',
                handler: function () {
                    signFileLook();
                }
            }, '-'
            , {
                text: '签署文件批量下载', id: 'btn_updownload', iconCls: 'icon-folder-save', handler: function () {
                    signFileDown();
                }
            },
            "-", {
                text: '汇总订单打印', id: 'btn_batch_print', iconCls: 'icon-print', handler: function () {
                    setOperationLog("汇总订单打印按钮", "采购订单查询");
                    var batchPrintDialog = openDialog('batchPrintDialog', g.ctx + 'pc/order/purchaseOrder/page/batchPrintList', {
                        title: '汇总订单打印',
                        width: "90%",
                        height: "100%",
                        cache: false,
                        modal: true,
                        border: 'thin',
                        onClose: function () {
                            batchPrintDialog.dialog('destroy');
                            $(el.tb).datagrid("reload")
                        },
                        buttons: [{
                            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                                batchPrintDialog.dialog('close');
                            }
                        }]
                    });
                }
            }, {
                text: '文件批量下载', id: 'btn_updown', iconCls: 'icon-folder-save', handler: function () {
                    var rows = $(el.tb).datagrid("getChecked");
                    if (rows.length <= 0) {
                        topWin.layer.confirm("请选择至少一条数据");
                        return
                    }
                    setOperationLog("文件批量下载按钮", "采购订单查询");
                    var ids = [];
                    $.each(rows, function (idx, itm) {
                        ids.push(itm.id);
                    });
                    openAttachmentDialog(ids.join(','), 1);

                }
            }, "-", {
                text: '导入', iconCls: 'icon-import', id: 'btn_import', handler: function () {
                    $("#detailUpload .filebox-label").click();
                }
            }, '-', {
                text: "导出", id: 'btn_export', iconCls: 'icon-download', handler: function () {
                    setOperationLog("导出按钮", "采购订单查询");
                    openExportDialog('pc/order/purchaseOrder/rest/export', 'tb', searchParams());
                }
            },
            {
                text: '回签拒绝', id: 'btn_refusal_sign', iconCls: 'icon-cancel', handler: function () {
                    let rows = $(el.tb).datagrid('getChecked');
                    if (!rows || rows.length !== 1) {
                        topWin.layer.msg("请选中一条记录");
                        return;
                    }
                    let orderId = rows[0].id;
                    topWin.layer.prompt({
                        title: '请输入回签拒绝原因',
                        formType: 2,
                        value: '拒绝'
                    }, function (value, index, elem) {
                        if (value === '') {
                            topWin.layer.msg("请输入回签拒绝原因")
                            return
                        }
                        $.ajax({
                            url: g.ctx + 'pc/order/purchaseOrder/rest/refusal',
                            method: "post",
                            data: {id: orderId, remark: value},
                            complete: function () {
                            },
                            success: function (data) {
                                topWin.layer.alert("操作成功", {icon: 1}, function (idx) {
                                    $(el.tb).datagrid('reload');
                                    topWin.layer.close(idx);
                                    topWin.layer.close(index)
                                });

                            },
                            error: function (data) {
                                topWin.layer.alert(data.responseJSON.message, {icon: 2});
                            }
                        });
                    });
                }
            },
            {
                text: '财务确认', id: 'btn_fin_ok', iconCls: 'icon-ok', handler: function () {
                    finanConfir(1);
                }
            },
            {
                text: '财务取消', iconCls: 'icon-cancel', id: 'btn_fin_cancel', handler: function () {
                    finanConfir(0);
                }
            },
            {
                text: '其他附件', iconCls: 'icon-upload', id: 'btn_fin_file', handler: function () {
                    uploadAttachmentFile();

                }
            },{
                text: '列设置',
                iconCls: 'icon-anchor',
                id: 'btn_column_sort',
                handler: function () {
                    console.log(el.defaultColumns)
                    openSortDialog({
                        //唯一编码
                        code: columnSortCodeEnum.PURCHASE_ORDER,
                        //初始列（每次新增或删除列需要手动删除sys_column_sort表中对应code数据）
                        columns: el.defaultColumns,
                        callBack: function (newColumns) {
                            //需要隐藏
                            initDataGrid(newColumns)
                        },
                    });
                }
            }],
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        },
        onBeforeLoad: function () {
            displayButtonByUserRole('purchaseOrder.list');
        },
        onLoadError: function () {
            displayButtonByUserRole('purchaseOrder.list');
            if (type === 2) {
                $(el.tb).datagrid("hideColumn", "billCode"); //
                $(el.tb).datagrid("hideColumn", "supplierName"); //
                $(el.tb).datagrid("hideColumn", "supplierErpCode"); //

            }
        },
        onCheck: function (rowIndex, field, value) {
            var rows = $('#tb').datagrid('getRows');
            var flag = rows[rowIndex].state;
            var enableFlag = 'enable';
            if (flag === 2) {
                enableFlag = 'disable'
            } else {
                enableFlag = 'enable';
            }
            $('#btn_replay').linkbutton(enableFlag);
            $('#btn_replay_plan').linkbutton(enableFlag);
            $('#btn_detail').linkbutton(enableFlag);
            $('#btn_print').linkbutton(enableFlag);
            $('#btn_up').linkbutton(enableFlag);
            $('#btn-sign').linkbutton(enableFlag);
            $('#btn-sign-look').linkbutton(enableFlag);
            $('#btn_batch_print').linkbutton(enableFlag);
            $('#btn_updown').linkbutton(enableFlag);
            $('#btn_import').linkbutton(enableFlag);
            $('#btn_export').linkbutton(enableFlag);
            $('#btn_fin_ok').linkbutton(enableFlag);
            $('#btn_fin_cancel').linkbutton(enableFlag);
            $('#btn_column_sort').linkbutton(enableFlag);
        },
        onClickCell: function (rowIndex, field, value) {
        }
    });
}

function openConfiDialog(type, id) {
    var btn = [{
        text: '关闭', iconCls: 'icon-cancel', handler: function () {
            confirmDialog.dialog('close');
        }
    }]
    if (type === 1) {
        //供方确认
        btn.unshift({
            text: '确定', iconCls: 'icon-ok', handler: function () {
                topWin.frames['confirmDialog'].save(function () {
                    confirmDialog.dialog('close');
                    $(el.tb).datagrid("reload")
                })
            }
        })
    } else {
        //答交
        btn.unshift({
            text: '提交', iconCls: 'icon-ok', handler: function () {
                topWin.frames['confirmDialog'].savePlan(function () {
                    confirmDialog.dialog('close');
                })
            }
        })
    }
    var confirmDialog = openDialog('confirmDialog', g.ctx + 'pc/order/purchaseOrder/page/supplierConfirm?id=' + id + "&type=" + type, {
        title: (type === 1 ? '供方确认' : '订单答交'),
        width: "90%",
        height: "100%",
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            confirmDialog.dialog('destroy');
        },
        buttons: btn
    });
}


function printOrder(row) {
    $.ajax({
        type: 'GET', url: g.ctx + 'pc/order/purchaseOrder/page/print?orderId=' + row.id, success: function (data) {
            $('#printDiv').print({
                globalStyles: false,
                mediaPrint: false,
                iframe: true,
                prepend: data,
                deferred: $.Deferred().done(function () {
                })
            });
        }
    });
}

function fileUpload(v1, v2) {
    var orderRows = $(el.tb).datagrid("getChecked");
    var addFiles = [];
    var files = $("#fileInput").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]);
    }
    if (addFiles.length > 0) {
        fileUploadAjaxWithCall(formData, function (rows) {
            const postData = []
            $.each(rows, function (idx, itm) {
                $.each(orderRows, function (iid, iit) {
                    postData.push({
                        fileId: itm.id, masterId: iit.id
                    })
                })

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

}




function sendSign() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录");
        return;
    }
    setOperationLog("电子印章签署按钮", "采购订单查询");
    // if (row.state !== 7) {
    //     topWin.layer.msg("确认完成才允许电子印章签署");
    //     return;
    // }
    const displayOrderCode =
        row.orderCode?.startsWith('40')
            ? row.orderCode[0] + 'x' + row.orderCode.slice(2)
            : row.orderCode;
    openSignDialog('esignDialog', {
        //业务类型编码
        title: '采购订单'+displayOrderCode,
        //业务类型编码
        businessTypeCode: eSignBusinessTypeCodeEnum.PURCHASE_ORDER,
        //业务唯一id
        businessId: row.id,
        //甲方
        firstParty: row.companyCode,
        //甲方名称
        firstPartyName: row.companyName,
        //乙方
        secondParty: row.supplierErpCode,
        //乙方名称
        secondPartyName: row.supplierName,
        sumSignFlag :row.sumSignFlag,
        summaryFileId :row.column1,
        attachmentType :'采购订单',
        callBack: function () {
            $(el.tb).datagrid('reload');
        },
    });
}

function signFileLook() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录");
        return;
    }
    setOperationLog("查看签署文件按钮", "采购订单查询");
    openSignLookDialog('esignDialog', row.id, eSignBusinessTypeCodeEnum.PURCHASE_ORDER);
}

/**
 * 签署文件批量下载
 */
function signFileDown() {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录");
        return;
    }
    setOperationLog("签署文件批量下载按钮", "采购订单查询");
    //查看签署文件，增加可以按选定的订单查看所有的签署文件 2024-10-15 邓京术
    var rows = $(el.tb).datagrid('getSelections');
    //只要选中的订单都可以查签署文件
    var bsIds = [];
    for (var i = 0; i < rows.length; i++) {
        bsIds.push(rows[i].id);
    }
    openSignLookDialog('downEsignDialog', bsIds.join(","), eSignBusinessTypeCodeEnum.PURCHASE_ORDER);
}


function uploadRequireFileUI(rec) {
    setOperationLog("明细查看附件", "采购订单查询");
    var value = $(rec).data('value');
    openAttachmentDialog(value)
}

function openAttachmentDialog(value, batchFlag, btn, title) {
    let url = g.ctx + "pc/order/purchaseOrder/page/attachment?ids=" + value;
    if (batchFlag !== undefined) {
        url = url + "&batchFlag=" + batchFlag
    }
    const btns = [{
        text: itablei8n.close, handler: function () {
            attachmentDialog.dialog('close');
        }
    }]
    if (btn !== undefined) {
        btns.unshift(btn)
    }
    attachmentDialog = openDialog("attachmentDialog", url, {
        title: title !== undefined ? title : "附件上传",
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            attachmentDialog.dialog('destroy');
        },
        buttons: btns
    })
}

function finanConfir(confirmFlag) {
    let rows = $(el.tb).datagrid('getChecked');
    if (!rows || rows.length < 1) {
        topWin.layer.msg("请选中至少一条记录");
        return;
    }
    let ids = [];
    let tipMsg = []
    $.each(rows, function (idx, itm) {
        if (itm.orderTypeCode === 'Z003') {
            tipMsg.push(itm.orderCode)
        }
        ids.push(itm.id)
    })
    if (tipMsg.length > 0) {
        topWin.layer.msg(tipMsg.join(",") + "无需要财务确认!");
        return;
    }

    openAttachmentDialog(ids.join(","), confirmFlag, {
        text: '确认', handler: function (call) {
            debugger;
            topWin.frames['attachmentDialog'].confirm(function (param) {
                console.log(param.attachmentType);
                $.ajax({
                    url: g.ctx + 'pc/order/purchaseOrder/rest/updateFinConf?ids=' + ids.join(','),
                    type: "POST",
                    data: {ids: ids.join(","), confirmFlag: confirmFlag,attachmentType:param.attachmentType},
                    success: function (data) {
                        topWin.layer.alert("操作成功", {icon: 1}, function (i) {
                            topWin.layer.close(i);
                            $(el.tb).datagrid('reload');
                            attachmentDialog.dialog('close');
                        });
                    },
                    error: function (data) {
                        topWin.layer.alert(JSON.parse(data.responseText).message, {icon: 2});
                    }
                });
            });
        }
    }, confirmFlag === 1 ? "财务确认" : "财务取消")
}

function syncQiChu() {

    $.ajax({
        url: g.ctx + 'purchaseOrder/syncQiChu', contentType: false, processData: false, success: function (data) {
            if (data.state) {
                topWin.layer.alert(data.msg);
            } else {
                topWin.layer.alert(data.msg);
            }

        }
    })
}

function detailImport(v1, v2) {
    var filebox = $("#detailFileInput").filebox("files");
    if (filebox.length == 1) {
        var formData = new FormData();
        formData.append("file", filebox[0]);
        var index = layer.load(1, {
            shade: [0.1, '#eee'] //0.1透明度的白色背景
        });
        $.ajax({
            url: g.ctx + 'purchaseOrder/import',
            data: formData,
            type: 'post',
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.state) {
                    layer.close(index);
                    $("#detailFileInput").filebox("clear")
                    $('#tb').datagrid('reload');
                    layer.alert(data.msg);
                } else {
                    layer.alert(data.msg);
                    layer.close(index);
                    $("#detailFileInput").filebox("clear")
                }

            }
        })
    }
}

function uploadAttachmentFile() {
    let rows = $('#tb').datagrid('getChecked');
    if (rows.length != 1) {
        layer.msg("请选中一条记录");
        return;
    }

    //采购订单的“汇总单号”不为空时，不允许通过“其他附件”按钮和列表中的“其他附件“（点击上传（未上传））栏位 上传附件。
    if (!isBlank(rows[0].batchNo)){
        topWin.layer.alert("选择的采购订单的“汇总单号”不为空，不允许操作");
        return false;
    }
    // const row = rows[0];
    // const businessTypeCode = "purchase_order";
    // const url = g.ctx + "pc/sys/businessAttachment/businessAttachmentDetail?businessId="+row.id+"&businessCode="+row.orderCode+ "&businessTypeCode=" + businessTypeCode;
    // var uploadAttachmentFileDialog = openDialog("uploadAttachmentFileDialog", url, {
    //     title: '采购订单附件上传',
    //     width: '900px',
    //     height: '400px',
    //     cache: false,
    //     modal: true,
    //     border: false,
    //     draggable: true,
    //     shadow: false,
    // })

    openCommonFileDialog('commonFileDialog',{
        //业务类型编码
        title:'采购订单附件上传',
        //业务类型编码
        businessTypeCode:eSignBusinessTypeCodeEnum.PURCHASE_ORDER,
        businessCode:rows[0].orderCode,
        //业务唯一id
        businessId:rows[0].id,
        callBack : function () {
            $(el.tb).datagrid('reload');
        },
    });
}


