var el = {
    form : '#form',
    optType : '#optType',
    tb : '#tb',
    id : '#id',
    purchaseGroupCode : '#purchaseGroupCode',
    companyCode : '#companyCode',
    taxCode : '#taxCode',
    approveOpinion : '#approveOpinion',
    files : '#files',
    originalSignRows: [],
    businessCodes: [],
    tbAttachment : '#tbAttachment',
    tbAttachmentCheck : '#tbAttachmentCheck',
    currencyCode : '#currencyCode',
    taxAmount : '#taxAmount',
    paymentMethod : '#paymentMethod',
    remark : '#remark',
    purchaseOrgCode : '#purchaseOrgCode',
    type : '#type',
    supplierName : '#supplierName',
    supplierCode : '#supplierCode',
    shortName : '#shortName',
    purchaseCategoryCode: '#purchaseCategoryCode',
    spotFlag: '#spotFlag',
    businessAgreeFlag: '#businessAgreeFlag',
    customerBearFlag: '#customerBearFlag',
    behalfCode: '#behalfCode',
    bearRatio: '#bearRatio',
    limitPrice: '#limitPrice',
};
let editor = undefined;

$(function () {
    initDict('unit,currency,payment_method,fktzd_type')
    initDictName('businessFileType')
    initNecessaryDatas('pc/sys/purchaseCategory/rest/listAll,pc/sys/tax/rest/listAll,pc/sys/factory/rest/allList')
    initCombo();
    loadGrid();

    if ($(el.tbAttachment).length>0){
        loadSignFileGrid();
    }
    initTbAttachmentCheck();

});

/**
 * 加载下拉框数据
 */
function initCombo() {
    //采购组
    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll'
    });
    $(el.companyCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/company/rest/listAll',
    });
    //类型
    $(el.type).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        data: getDictList('fktzd_type')
    });
    $(el.currencyCode).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        data: getDictList('currency')
    });
    if (isSupplier===0){
        $(el.supplierCode).textbox({
            prompt: '请选择供应商',
            required: true,
            editable:false,
            icons: [
                {
                    iconCls: 'icon-search',
                    handler: function () {
                        if (optType!==2&&optType!==3){
                            choseSupplier();
                        }
                    }
                }
            ]
        });

        $(el.supplierCode).textbox('textbox').css('cursor', 'pointer');
        $(el.supplierCode).textbox('textbox').bind('click', function () {
            if (optType!==2&&optType!==3){
                choseSupplier();
            }
        });
    }

}
/**
 * 选择供应商
 */
function choseSupplier() {
    el.choseSupplierDialog = openDialog('choseSupplier', g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1", {
        title: '供应商选择',
        width: '80%',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseSupplierDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseSupplier'].chooseRow(function (data) {
                        console.log(data[0])
                        var oriSupCode = $(el.supplierCode).val();
                        if(oriSupCode !== data[0].supplierCode){
                            clearPageTableData();
                        }
                        $(el.shortName).val(data[0].shortName);
                        $(el.supplierCode).textbox('setValue', data[0].supplierCode);
                        $(el.supplierName).textbox('setValue', data[0].supplierName);
                        $(el.companyCode).combobox('setValue', data[0].companyCode);
                        $(el.currencyCode).combobox('setValue',data[0].currencyCode);
                        el.choseSupplierDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseSupplierDialog.dialog('close');
                }
            }
        ]
    });
}

function loadGrid() {
    var url = g.ctx + 'pc/finance/payment/notice/detail/rest/getDetailListByMainId?mainId='+$(el.id).val();
    let columns = [
        {
            field: 'ck',
            checkbox: true
        },
        // {
        //     field: 'code',
        //     title: '委托单号<span style="color: red">*</span>',
        //     width: '120',
        //     align: 'left',
        //     editor: {
        //         type: 'textbox',
        //         options: {
        //             // required:true
        //         }
        //     }
        // },
        {
            field: 'code',
            title: '委托单号<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    onChange: function (newValue, oldValue) {
                        // 只在新增/编辑态触发
                        if (optType !== 0 && optType !== 1) return;

                        // newValue 有值才触发（防空）
                        if (!isBlank(newValue)) {
                            scheduleInitFileGrid(300);
                        } else {
                            // 清空 code 时顺带清空附件区（可选）
                            if ($(el.tbAttachment).length > 0) {
                                $(el.tbAttachment).datagrid('loadData', { total: 0, rows: [] });
                            }
                            if ($(el.tbAttachmentCheck).length > 0) {
                                $(el.tbAttachmentCheck).datagrid('loadData', { total: 0, rows: [] });
                            }
                            el.businessCodes = [];
                        }
                    }
                }
            }
        },
        {
            field: 'customsDeclarationCode',
            title: '报关单号<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    // required:true
                }
            }
        },
        {
            field: 'codeDate',
            title: '报关日期<span style="color: red">*</span>',
            width: '150',
            align: 'left',
            editor: {
                type: 'datebox',
            },
            formatter: function (value) {
                if (value) {
                    return new Date(value).format('yyyy-MM-dd');
                }
                return value;
            }
        },
        {
            field: 'num',
            title: '数量<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required: true,
                    precision: 0
                }
            }
        },
        {
            field: 'taxAmount',
            title: '进口总价(USD)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'tariffPrice',
            title: '关税(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'valueAddedTaxPrice',
            title: '增值税(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'agencyFeePrice',
            title: '代理费(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'domesticFeePrice',
            title: '境内费用(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'overseasFeePrice',
            title: '境外费用(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'feeTaxAmountPrice',
            title: '费用税额(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'freightPrice',
            title: '运费(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'freightTaxAmountPrice',
            title: '运费用税额(CNY)<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'otherFeePrice',
            title: '其他费用<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    // required:true,
                    precision: priceHandle.precision
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        }
    ];
    var toolbar = [];
    if (optType===0||optType===1){
        toolbar.push(
            // {
            //     text: "新增",
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         $(el.tb).datagrid('appendRow', {
            //
            //         });
            //         endEditing();
            //     }
            // }
            {
                text: "新增",
                iconCls: 'icon-add',
                handler: function () {
                    if (!endEditing()) return;

                    $(el.tb).datagrid('appendRow', {});
                    var idx = $(el.tb).datagrid('getRows').length - 1;
                    $(el.tb).datagrid('selectRow', idx).datagrid('beginEdit', idx);
                    editor = idx;
                }
            }
            , "-",{
                text: "删除",
                iconCls: 'icon-remove',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.alert("请选择数据");
                        return;
                    }
                    let index = $(el.tb).datagrid('getRowIndex', row);
                    $(el.tb).datagrid('deleteRow', index);

                    //先关闭行编辑
                    if (editor !== undefined) {
                        $(el.tb).datagrid('endEdit', editor);
                        editor = undefined;
                    }

                    //删除行的时候，要把编辑行的索引更新
                    if (index < editor) {
                        editor--;
                    } else if (index === editor) {
                        editor = -1;
                    }
                    initFileGrid();
                }
            }, "-",
            {
                text: '导入',
                iconCls: 'icon-import',
                handler: function () {
                    materialImport();
                }
            }
        );
    }
    $(el.tb).datagrid({
        iconCls: 'icon-list',
        height: '490',
        singleSelect: false,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        url: url,
        columns: [columns],
        onClickRow: function (index, rowData) {
            if(optType !== 2&&optType !== 5){
                if (editor !== index) {
                    if (endEditing()) {
                        editor = index;
                        $(el.tb).datagrid('updateRow', {index: index, row: {state: 2}})
                        $(el.tb).datagrid('selectRow', index).datagrid('beginEdit', index);
                        editor = index;
                    } else {
                        editor = index;
                        $(el.tb).datagrid('selectRow', editor);
                    }
                } else {
                    $(el.tb).datagrid('updateRow', {index: index, row: {state: 2}})
                    $(el.tb).datagrid('selectRow', index).datagrid('beginEdit', index);
                    editor = index;
                }
            }

        },
        toolbar: toolbar,
        onLoadSuccess: function (data) {
            if (optType!==0){
                initFileGrid();
            }
        }
    });
}

//2026-01-26注释，等功能测试稳定后再删除此代码
// function initFileGrid(){
//     var rows = $(el.tb).datagrid('getRows');
//     if (rows.length>0){
//         if (isBlank(rows[0].code)){
//             return false;
//         }
//         el.businessCodes = [rows[0].code];
//         $.ajax({
//             url: g.ctx + 'pc/order/deliveryOrder/rest/getDevOrderCodesByEntrustNo',
//             type: "GET",
//             async: false,
//             data: {entrustNo: rows[0].code},
//             success: function (data) {
//                 if (data.length>0){
//                     var deliveryOrderCodes = data.join(',');
//                     if ($(el.tbAttachment).length>0){
//                         $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;
//                         var attachmentTypeCreateConfigList = eval(attachmentTypeCreateConfigs);
//                         //取attachmentTypeCreateConfigList中的code,逗号隔开
//                         var attachmentTypeCreateConfigCodes = attachmentTypeCreateConfigList.map(function(item){
//                             return item.code;
//                         })
//                         let url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+$(el.id).val()+'&businessTypeCodes=payment_notice';
//                         if (optType===0||optType===1){
//                             url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessCodes='+deliveryOrderCodes+'&businessTypeCodes=delivery_order,delivery_order_sign'+'&types='+attachmentTypeCreateConfigCodes.join(',');
//                         }
//                         $(el.tbAttachment).datagrid('options').url = url;
//                         $(el.tbAttachment).datagrid('load');
//                     }
//                 }else {
//                     $(el.tbAttachment).datagrid('loadData', {total: 0, rows: []});
//                 }
//             }
//         })
//
//     }
// }
function initFileGrid(){
    var rows = $(el.tb).datagrid('getRows') || [];
    if (rows.length <= 0) {
        if ($(el.tbAttachment).length > 0) $(el.tbAttachment).datagrid('loadData', {total:0, rows:[]});
        if ($(el.tbAttachmentCheck).length > 0) $(el.tbAttachmentCheck).datagrid('loadData', {total:0, rows:[]});
        el.businessCodes = [];
        return;
    }

    // ✅ 第一行委托单号（编辑态实时取值）
    var firstCode = getRowFieldValue(0, 'code');
    if (isBlank(firstCode)) return;

    // ✅ 附件检查表用所有委托单号（去重）
    var codes = [];
    for (var i = 0; i < rows.length; i++) {
        var c = getRowFieldValue(i, 'code');
        if (!isBlank(c)) codes.push(String(c));
    }
    codes = codes.filter(function(item, idx, arr){ return arr.indexOf(item) === idx; });
    el.businessCodes = codes;

    $.ajax({
        url: g.ctx + 'pc/order/deliveryOrder/rest/getDevOrderCodesByEntrustNo',
        type: "GET",
        async: false,
        data: { entrustNo: firstCode },
        success: function (data) {
            if (data && data.length > 0) {
                var deliveryOrderCodes = data.join(',');
                if ($(el.tbAttachment).length > 0) {
                    $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;

                    var attachmentTypeCreateConfigList = eval(attachmentTypeCreateConfigs);
                    var types = attachmentTypeCreateConfigList.map(function(item){ return item.code; });

                    let url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes'
                        + '?businessIds=' + $(el.id).val()
                        + '&businessTypeCodes=payment_notice';

                    if (optType === 0 || optType === 1) {
                        url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes'
                            + '?businessCodes=' + deliveryOrderCodes
                            + '&businessTypeCodes=delivery_order,delivery_order_sign'
                            + '&types=' + types.join(',');
                    }
                    $(el.tbAttachment).datagrid('options').url = url;
                    $(el.tbAttachment).datagrid('load'); // ✅ loadSuccess 里会刷新 tbAttachmentCheck
                }
            } else {
                if ($(el.tbAttachment).length > 0) $(el.tbAttachment).datagrid('loadData', {total:0, rows:[]});
                if ($(el.tbAttachmentCheck).length > 0) $(el.tbAttachmentCheck).datagrid('loadData', {total:0, rows:[]});
            }
        }
    });
}

function pagerSignFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function')     {   // is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalSignRows) {
        data.originalSignRows = (data.rows);
        el.originalSignRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalSignRows.slice(start, end));
    return data;
}
function loadSignFileGrid(){
    let toolbar = [];
    if (optType === 0 || optType === 1 ) {
        // toolbar = [
        // {
        //     text: BJGL.BJGL__SC, iconCls: 'icon-add', hidden: true, handler: uploadAttachmentFile
        // }, "-", {
        //     text: BJGL.BJGL__SHANC, iconCls: 'icon-remove', handler: deleteAttachmentFile
        // // }, "-",
        // {
        //     text: "设置备注", iconCls: 'icon-remove', handler: remarkAttachmentFile
        // }
        // ];

        toolbar = [
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailRelationFileExport();
                }
            },
        ];
    }

    // const url = g.ctx + 'pc/finance/account/statement/attachment/rest/list?asId=' + $(el.id).val()+'&reloadFlag='+(optType === 1?1:0)+'&businessTypeCodes=delivery_order';
    $(el.tbAttachment).datagrid({
        loadMsg: '数据加载中......',
        // url: url,
        height: '460px',
        width: '98%',
        async: false,  // 设置为同步加载
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        queryParams: {},
        columns: [[
            {
                field: 'type', title: "附件类型", sortable: true,width: '10%',  formatter: function (value) {
                    return getDicName('businessFileType',value)
                }
            },
            {
                field: 'imageCode', title: "影像编码", width: '10%'
            },
            {
                field: 'businessCode', title: "单据编号", sortable: true,width: '10%'
            },
            {
                field: 'fileId',
                title: '附件名称',
                width: '20%',
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            },
            {
                field: 'signStatus',
                title: '签章状态',
                width: '5%',
                sortable: true,
                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>';
                        case 7:
                            return '<span style="color: red;">已删除</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'signOrder',
                title: '签章顺序',
                sortable: true,
                width: '5%',
                formatter: function (value) {
                    return getDicName('sign_order',value)
                }
            },
            {
                field: 'signatureType',
                title: '签章类别',
                sortable: true,
                width: '5%',
                formatter: function (value) {
                    return getDicName('sign_type',value)
                }
            },
            {
                field: 'remark', title: "备注", width: '10%'
            },
            {
                field: 'createTime', sortable: true,title: "上传时间"
            },
            {
                field: 'updateUserName', sortable: true,title: "最近修改人"
            },
            {
                field: 'updateTime', sortable: true,title: "最近修改时间"
            }
        ]],
        toolbar: toolbar,
        loadFilter: pagerSignFilter,
        onLoadSuccess: async function (data) {
            if (data.rows.length>0){
                initFileForm('supplier-file-form');
            }
            const allRows = await getAllBusinessData(data.rows);
            if (el.businessCodes.length>0){
                var checkRows = [];
                var attachmentTypeCreateConfigList = eval(attachmentTypeCreateConfigs);
                var attachmentTypeCheckConfigList = eval(attachmentTypeCheckConfigs);
                el.businessCodes.forEach(function (item) {
                    var obj = {};
                    obj.entrustNo = item;
                    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
                        var exist = allRows.find(function (item2) {
                            // return item2.businessCode === item && item2.type === attachmentTypeCreateConfig.code;
                            return  item2.type === attachmentTypeCreateConfig.code
                                &&attachmentTypeCreateConfig.code!=='agent_supplier_invoice'
                                &&attachmentTypeCreateConfig.code!=='agent_supplier_packing_list'
                                &&attachmentTypeCreateConfig.code!=='invoice_and_packing_list'
                                ;
                        });
                        obj[attachmentTypeCreateConfig.code] = exist?1:0;
                        if (attachmentTypeCreateConfig.code==='invoice_and_packing_list'){
                            debugger
                            if (obj[attachmentTypeCreateConfig.code]===0){
                                var exist3 = allRows.find(function (item2) {
                                    return item2.type === 'agent_supplier_invoice';
                                });
                                var exist4 = allRows.find(function (item2) {
                                    return item2.type === 'agent_supplier_packing_list';
                                });
                                exist = exist3&&exist4;
                                obj[attachmentTypeCreateConfig.code] = exist3&&exist4?1:0;
                            }else {
                                exist = 1;
                                obj[attachmentTypeCreateConfig.code] = 1;
                            }
                        }

                        //物流供应商-invoice和物流供应商-packing list取值如果为空，再取这个附件类型，如果这个类型有附件，就代表物流供应商-invoice和物流供应商-packing list都有值
                        if (attachmentTypeCreateConfig.code==='agent_supplier_invoice'){
                            var exist11 = allRows.find(function (item2) {
                                return item2.type === 'agent_supplier_invoice';
                            });
                            if (!exist11){
                                var exist1 = allRows.find(function (item2) {
                                    return item2.type === 'invoice_and_packing_list';
                                });
                                exist = exist1;
                                obj[attachmentTypeCreateConfig.code] = exist1?1:0;
                            }else {
                                exist = 1;
                                obj[attachmentTypeCreateConfig.code] = 1;
                            }

                        }
                        if (attachmentTypeCreateConfig.code==='agent_supplier_packing_list'){
                            var exist22 = allRows.find(function (item2) {
                                return item2.type === 'agent_supplier_packing_list';
                            });
                            if (!exist22){
                                var exist2 = allRows.find(function (item2) {
                                    return item2.type === 'invoice_and_packing_list';
                                });
                                exist = exist2;
                                obj[attachmentTypeCreateConfig.code] = exist2?1:0;
                            }else {
                                exist = 1;
                                obj[attachmentTypeCreateConfig.code] = 1;
                            }
                        }


                        //是否存在校验
                        var checkExist = false;
                        attachmentTypeCheckConfigList.forEach(function (attachmentTypeCheckConfig) {
                            if (attachmentTypeCheckConfig.code === attachmentTypeCreateConfig.code){
                                checkExist = true;
                            }
                        });
                        //如果不存在校验，但是文件也不存在，则文件状态为无需校验
                        if (!checkExist && !exist){
                            obj[attachmentTypeCreateConfig.code] = 2;
                        }
                        //存在校验，但是文件也不存在，则满足状态为不满足
                        if (checkExist && !exist){
                            obj.satisfyFlag = 0;
                        }else {
                            obj.satisfyFlag = 1;
                        }

                    });
                    checkRows.push(obj);
                });
                $(el.tbAttachmentCheck).datagrid('loadData', {total: checkRows.length, rows: checkRows});
                //allRows
                // el.businessCodes.forEach(function (item) {
                //     //判断allRows中是否存在businessCode和item相同且type为delivery_order的数据
                //     var delivery_order_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'delivery_order';
                //     });
                //
                //     var customs_declaration_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'customs_declaration';
                //     });
                //
                //     var supplier_invoice_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'supplier_invoice';
                //     });
                //
                //     var agent_supplier_invoice_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'agent_supplier_invoice';
                //     });
                //
                //     var supplier_packing_list_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'supplier_packing_list';
                //     });
                //
                //     var agent_supplier_packing_list_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'agent_supplier_packing_list';
                //     });
                //     var obj = {
                //         "deliveryOrderNo": item,
                //         "deliveryOrderFile": delivery_order_exist?1:0,
                //         "customsDeclarationFile": customs_declaration_exist?1:0,
                //         "invoiceFile": supplier_invoice_exist||agent_supplier_invoice_exist?1:0,
                //         "packingListFile": supplier_packing_list_exist||agent_supplier_packing_list_exist?1:0,
                //         "satisfyFlag": (!delivery_order_exist||!customs_declaration_exist||(!supplier_invoice_exist&&!agent_supplier_invoice_exist)||(!supplier_packing_list_exist&&!agent_supplier_packing_list_exist))?0:1
                //     }
                //     checkRows.push(obj);
                // });
                // $(el.tbAttachmentCheck).datagrid('loadData', {total: checkRows.length, rows: checkRows});
            }
        },
    });
}
function initTbAttachmentCheck(){
    let toolbar = [];
    var attachmentTypeCreateConfigList = eval(attachmentTypeCreateConfigs);
    let columns = [
        {
            field: 'entrustNo', title: "委托单号", sortable: true,width: attachmentTypeCreateConfigList.length>1?50:100
        }
    ];
    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
        columns.push(
            {
                field: attachmentTypeCreateConfig.code, title: attachmentTypeCreateConfig.name, width: attachmentTypeCreateConfigList.length>1?50:100,sortable: true,
                formatter: function (value) {
                    if (value===1) {
                        return '<span style="color:green;">存在</span>';
                    }else if (value===0) {
                        return '<span style="color:red;">不存在</span>';
                    }else{
                        return '<span style="color:green;">无需校验</span>';
                    }
                }
            }
        );
    });
    columns.push(
        {
            field: 'satisfyFlag', title: "是否满足", width: attachmentTypeCreateConfigList.length>1?50:100,sortable: true,
            formatter: function (value) {
                if (value===1) {
                    return '<span style="color:green;">满足</span>';
                }
                return '<span style="color:red;">不满足</span>';
            }
        }
    )
    $(el.tbAttachmentCheck).datagrid({
        loadMsg: '数据加载中......',
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        columns: [columns],
        toolbar: toolbar,
    });
}

/**
 * 物料数据导入
 */
function materialImport() {
    endEditing();
    var importDialog = openImportExcelDialog('static/excel/付款通知单导入模板.xls','付款通知单明细导入',function(file){
        let formData = new FormData();
        formData.append("file", file);
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/payment/notice/rest/importData',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    let ps = $(el.tb).datagrid('getRows');
                    var code = '';
                    for (let i = 0; i < data.length; i++) {
                        let product = data[i];
                        // getSupplierByMaterialCodeAndFactoryCode(product.materialCode,product.factoryCode,companyCode);
                        $(el.tb).datagrid('appendRow', {
                            code: product.code,
                            customsDeclarationCode: product.customsDeclarationCode,
                            codeDate: product.codeDate,
                            num: product.num,
                            taxAmount: product.taxAmount,
                            tariffPrice: product.tariffPrice,
                            valueAddedTaxPrice: product.valueAddedTaxPrice,
                            agencyFeePrice: product.agencyFeePrice,
                            domesticFeePrice: product.domesticFeePrice,
                            overseasFeePrice: product.overseasFeePrice,
                            feeTaxAmountPrice: product.feeTaxAmountPrice,
                            freightPrice: product.freightPrice,
                            freightTaxAmountPrice: product.freightTaxAmountPrice,
                            otherFeePrice: product.otherFeePrice
                        });
                    }

                    initFileGrid();
                    importDialog.dialog('close');
                });
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

function setRemark() {
    var allRows = $(el.tb).datagrid('getRows');
    if (allRows.length>0){
        if (allRows[0].code){
            $(el.remark).textbox('setValue',allRows[0].code+'_运杂费_增值税_关税')
        }
    }


}

// ====== 编辑态取值（优先 editor，否则取 row）======
function getRowFieldValue(index, field) {
    var ed = $(el.tb).datagrid('getEditor', { index: index, field: field });
    if (ed && ed.target) {
        try { return $(ed.target).textbox('getValue'); } catch (e) {}
        try { return $(ed.target).numberbox('getValue'); } catch (e) {}
        try { return $(ed.target).datebox('getValue'); } catch (e) {}
        try { return $(ed.target).combobox('getValue'); } catch (e) {}
    }
    var row = ($(el.tb).datagrid('getRows') || [])[index] || {};
    return row[field];
}

// ====== initFileGrid 防抖（避免每敲一个字符就请求）======
var __initFileGridTimer = null;
function scheduleInitFileGrid(delayMs) {
    clearTimeout(__initFileGridTimer);
    __initFileGridTimer = setTimeout(function () {
        initFileGrid();
    }, delayMs || 300);
}


function endEditing() {
    if (editor === undefined) {
        calculateTaxAmount();
        setRemark();
        initFileGrid();
        return true
    }
    if ($(el.tb).datagrid('endEdit', editor)) {
        editor = undefined;
        calculateTaxAmount();
        setRemark();
        initFileGrid();
        return true;
    } else {
        return false;
    }
}

function calculateTaxAmount(){
    var allRows = $(el.tb).datagrid('getRows');
    var total = new BigNumber(0);
    for (let i = 0; i < allRows.length; i++) {
        if (allRows[i].taxAmount){
            total = new BigNumber(allRows[i].taxAmount).plus(total);
        }
    }
    $(el.taxAmount).textbox('setValue',total);
}
function copy(type) {
    $(el.tb).datagrid('endEdit', editor);
    let allRows = $(el.tb).datagrid('getRows');
    for (let i = 0;i<allRows.length;i++){
        $(el.tb).datagrid('endEdit', i);

    }
    for (let i = 0; i < allRows.length; i++) {
        $(el.tb).datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}

/**
 * 清空页面表格数据
 */
function clearPageTableData() {
    $(el.tb).datagrid('loadData', {total: 0, rows: []});
}

async function saveOrUpdate(call){
    if($(el.form).form('validate')){
        // if(editor !== undefined){
        //     let flag = $(el.tb).datagrid('validateRow', editor);
        //     if(!flag){
        //         layer.msg('检验未通过!请检查行明细中红框未填');
        //         return;
        //     }
        //     $(el.tb).datagrid('endEdit', editor);
        // }
        var formData = $(el.form).serializeJson();
        formData.id = optType===3?'':$(el.id).val();
        // formData.files = $(el.files).attr('data-fileIds');
        endEditing();
        setRemark();
        let row = $(el.tb).datagrid('getRows');
        if (row.length <= 0) {
            layer.msg('请添加明细', {time: 2000});
            return false;
        }
        for (let i = 0 ; i < row.length ; i ++){
            let flag = false, msg = "";
            if(isBlank(row[i].code)){
                layer.msg("明细第"+ ++i+"行，委托单号必填");
                return false;
            }
            if(isBlank(row[i].customsDeclarationCode)){
                layer.msg("明细第"+ ++i+"行，报关单号必填");
                return false;
            }
            if(isBlank(row[i].codeDate)){
                layer.msg("明细第"+ ++i+"行，报关日期必填");
                return false;
            }
            if(isBlank(row[i].num)){
                layer.msg("明细第"+ ++i+"行，数量必填");
                return false;
            }
            if(isBlank(row[i].taxAmount)){
                layer.msg("明细第"+ ++i+"行，进口总价(USD)必填");
                return false;
            }
            if(isBlank(row[i].tariffPrice)){
                layer.msg("明细第"+ ++i+"行，关税(CNY)必填");
                return false;
            }
            if(isBlank(row[i].valueAddedTaxPrice)){
                layer.msg("明细第"+ ++i+"行，增值税(CNY)必填");
                return false;
            }
            if(isBlank(row[i].agencyFeePrice)){
                layer.msg("明细第"+ ++i+"行，代理费(CNY)必填");
                return false;
            }
            if(isBlank(row[i].domesticFeePrice)){
                layer.msg("明细第"+ ++i+"行，境内费用(CNY)必填");
                return false;
            }
            if(isBlank(row[i].overseasFeePrice)){
                layer.msg("明细第"+ ++i+"行，境外费用(CNY)必填");
                return false;
            }

            if(isBlank(row[i].feeTaxAmountPrice)){
                layer.msg("明细第"+ ++i+"行，费用税额(CNY)必填");
                return false;
            }
            if(isBlank(row[i].freightPrice)){
                layer.msg("明细第"+ ++i+"行，运费(CNY)必填");
                return false;
            }
            if(isBlank(row[i].freightTaxAmountPrice)){
                layer.msg("明细第"+ ++i+"行，运费用税额(CNY)必填");
                return false;
            }
            if (isBlank(row[i].otherFeePrice)) {
                layer.msg("明细第"+ ++i+"行，其他费用必填");
                return false;
            }
            // if (Number(formData.limitPrice) === 0) {
            //     if(!row[i].currencyCode){
            //         layer.msg("明细第"+ ++i+"行，币别必填");
            //         return false;
            //     }
            //     if(!row[i].externalPriceFlag){
            //         layer.msg("明细第"+ ++i+"行，是否需要调整在外订单价格必填");
            //         return false;
            //     }
            //     if(!row[i].customerSpecifiedType){
            //         layer.msg("明细第"+ ++i+"行，客户指定类型必填");
            //         return false;
            //     }
            //     if(!row[i].aduitType){
            //         layer.msg("明细第"+ ++i+"行，报价类型必填");
            //         return false;
            //     }
            // }else {
            //     if(!row[i].currencyCode){
            //         layer.msg("明细第"+ ++i+"行，币别必填");
            //         return false;
            //     }
            //     if(!row[i].spotGoods){
            //         layer.msg("明细第"+ ++i+"行，现货必填");
            //         return false;
            //     }
            //     if(!row[i].num){
            //         layer.msg("明细第"+ ++i+"行，数量必填");
            //         return false;
            //     }
            //     if(!row[i].limitedPriceReview){
            //         layer.msg("明细第"+ ++i+"行，限价原因必填");
            //         return false;
            //     }
            // }
            // row[i].taxPrice = getTaxPrice(row[i].taxCode,row[i].noTaxPrice,1,precision,1)
        }
        formData.detailList = row;
        var satisfyFlagExist = false;
        let uploadAttachmentFileDataList = Number(tbAttachmentLookFlag)===1?[]:$(el.tbAttachment).datagrid("getData").rows;
        uploadAttachmentFileDataList = await getAllBusinessData(uploadAttachmentFileDataList);
        formData.businessAttachmentDTOList = uploadAttachmentFileDataList;
        uploadAttachmentFileDataList.forEach(item=>{
            if (item.satisfyFlag===0){
                satisfyFlagExist = true;
            }
        })
        if (satisfyFlagExist){
            layer.confirm('附件检查中存在附件未满足,是否继续？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                layer.closeAll()
                saveOrUpdateAjax(formData,call)
                return false;
            }, function(){
                layer.closeAll()
                return false;
            });
        }else {
            saveOrUpdateAjax(formData,call)
        }
    }else {
        layer.msg('检验未通过!请检查红框未填');
        return false;
    }
}

function saveOrUpdateAjax(formData,call) {
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/payment/notice/rest/saveOrUpdate',
        method: 'post',
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            call();
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 财务保存
 *
 * @param approveStatus 审批结果 0:拒绝 1:同意
 * @param call 回调函数
 */
function financeConfirm(approveStatus,call) {
    var approveOpinion = $(el.approveOpinion).val();
    var formData = {};
    formData.id = $(el.id).val();
    formData.approveStatus = approveStatus;
    formData.approveOpinion = approveOpinion;
    if(approveStatus===0&&!approveOpinion){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/payment/notice/rest/financeConfirm',
        method: 'post',
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            call();
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 获取所有业务附件
 */
async function getAllBusinessData(rows) {
    if (rows.length === 0) return [];
    const url = $(el.tbAttachment).datagrid('options').url;
    if (isBlank(url)) return [];
    const detailRows = await new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            type: "GET",
            success: resolve,
            error: reject
        });
    });
    return detailRows.rows;
}