var el = {
    form : '#form',
    optType : '#optType',
    tbCustomsDeclaration : '#tbCustomsDeclaration',
    imgCode : '#imgCode',
    tbReceiveVoucher : '#tbReceiveVoucher',
    id : '#id',
    purchaseGroupCode : '#purchaseGroupCode',
    companyCode : '#companyCode',
    taxCode : '#taxCode',
    approveOpinion : '#approveOpinion',
    files : '#files',
    currencyCode : '#currencyCode',
    taxAmount : '#taxAmount',
    mainId : '#mainId',
    paymentMethod : '#paymentMethod',
    purchaseOrgCode : '#purchaseOrgCode',
    type : '#type',
    customsDeclarationDetailCode : '#customsDeclarationDetailCode',
    invoiceDate : '#invoiceDate',
    postDate : '#postDate',
    supplierName : '#supplierName',
    agentSupplierName : '#agentSupplierName',
    supplierCode : '#supplierCode',
    remark : '#remark',
    agentSupplierCode : '#agentSupplierCode',
    shortName : '#shortName',
    purchaseCategoryCode: '#purchaseCategoryCode',
    spotFlag: '#spotFlag',
    businessAgreeFlag: '#businessAgreeFlag',
    customerBearFlag: '#customerBearFlag',
    behalfCode: '#behalfCode',
    bearRatio: '#bearRatio',
    limitPrice: '#limitPrice',
    originalCustomsDeclarationRows: [],
    originalReceiveVoucherRows: [],
    filterCustomsDeclarationFlag: false,
    filterReceiveVoucherFlag: false,
    tbAttachment: '#tbAttachment',
    tbAttachmentCheck: '#tbAttachmentCheck',
    businessCodes: [],
    originalSignRows: [],
    bodyHeight: document.documentElement.clientHeight
};
let editor = undefined;

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

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

    if (optType!==0){
        initTbAttachmentData($(el.customsDeclarationDetailCode).textbox('getValue'),$(el.mainId).val());
    }

});

/**
 * 加载下拉框数据
 */
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('hkpp_type')
    });
    $(el.currencyCode).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        data: getDictList('currency')
    });
    $(el.customsDeclarationDetailCode).textbox({
        prompt: '请选择委托单号',
        required: true,
        editable:false,
        icons: [
            {
                iconCls: 'icon-search',
                handler: function () {
                    if (optType!==2&&optType!==3){
                        choseCustomsDeclarationDetailCode();
                    }
                }
            }
        ]
    });

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

    $(el.invoiceDate).datebox({
        onChange: function (date) {
            if (!$(el.postDate).datebox('getValue')){
                $(el.postDate).datebox('setValue',date)
            }
        }
    })

    $(el.imgCode).textbox('textbox').css('cursor', 'pointer').css('color', '#0b94ea');
    $(el.imgCode).textbox('textbox').bind('click', function () {
        if(!$(el.imgCode).textbox('getValue')) return false;
        showImage($(el.imgCode).textbox('getValue'));
    });
}

function showImage(imageCode){
    $.ajax({
        type: 'get',
        url: g.ctx + 'pc/sys/kingdeeImage/rest/getImageViewPath',
        data: {
            imageCode: imageCode
        },
        success: function (data) {
            if (data) {
                window.open(data, "_blank");
            }
        },
        error: function (error) {
            topWin.layer.alert(error.responseJSON.message, {
                icon: 2,
                content: error.responseJSON.message
            });
        }
    });
}
/**
 * 选择供应商
 */
function choseCustomsDeclarationDetailCode() {
    el.choseCustomsDeclarationDetailCodeDialog = openDialog('choseCustomsDeclarationDetailCode', g.ctx + "pc/finance/customs/declaration/dialog?single=1", {
        title: '委托单选择',
        width: '50%',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseCustomsDeclarationDetailCodeDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseCustomsDeclarationDetailCode'].confirmChose(function (data) {
                        console.log(data[0])
                        var customsDeclarationDetailCode = $(el.customsDeclarationDetailCode).val();
                        if(customsDeclarationDetailCode !== data[0].code){
                            clearCustomsDeclarationPageTableData();
                            clearReceiveVoucherPageTableData();
                        }
                        $(el.type).combobox('setValue', Number(data[0].type)===1?'0':'1');
                        $(el.customsDeclarationDetailCode).textbox('setValue', data[0].code);
                        $(el.supplierCode).textbox('setValue', data[0].supplierCode);
                        $(el.remark).textbox('setValue', data[0].remark);
                        $(el.agentSupplierCode).val(data[0].agentSupplierCode);
                        $(el.supplierName).textbox('setValue', data[0].supplierName);
                        $(el.agentSupplierName).textbox('setValue', data[0].agentSupplierName);
                        $(el.companyCode).combobox('setValue', data[0].companyCode);
                        $(el.currencyCode).combobox('setValue',data[0].currencyCode);
                        $(el.imgCode).textbox('setValue',data[0].imgCode);
                        initTbAttachmentData(data[0].code,data[0].mainId);
                        // el.businessCodes.push(data[0].code);
                        // 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;
                            // })
                            // $(el.tbAttachment).datagrid('options').url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+$(el.id).val()+'&businessTypeCodes=customs_declaration';
                            // if (optType===0||optType===1){
                            //     $(el.tbAttachment).datagrid('options').url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessCodes='+data[0].deliveryOrderCodes+'&businessTypeCodes=delivery_order,delivery_order_sign'+'&types='+attachmentTypeCreateConfigCodes.join(',');
                            // }
                            // $(el.tbAttachment).datagrid('load');
                        // }
                        el.choseCustomsDeclarationDetailCodeDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseCustomsDeclarationDetailCodeDialog.dialog('close');
                }
            }
        ]
    });
}

function initTbAttachmentData(businessCode,businessId) {
    el.businessCodes = [businessCode];
    $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;
    $(el.tbAttachment).datagrid('options').url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+businessId+'&businessTypeCodes=customs_declaration';
    $(el.tbAttachment).datagrid('load');
}

function loadTbCustomsDeclarationGrid() {
    var url = '';
    if ($(el.id).val()){
        url = g.ctx + 'pc/finance/customs/declaration/detail/rest/provide/detail/byPaymentMatchingId?paymentMatchingId='+$(el.id).val();
    }
    var toolbar = [];
    if (optType===0){
        toolbar.push(
            {
                text: "获取明细",
                iconCls: 'icon-add',
                handler: function () {
                    getCustomsDeclaration();
                }
            },
            "-",
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    btnCustomsDeclarationFilter();
                }
            },
            "-",
            {
                text: "剔除",
                iconCls: 'icon-remove',
                handler: function () {
                    let rows = $(el.tbCustomsDeclaration).datagrid('getSelections');
                    if (rows.length===0) {
                        layer.alert("请选择数据");
                        return;
                    }
                    //循环删除
                    for (let i = 0; i < rows.length; i++) {
                        let row = rows[i];
                        let index = $(el.tbCustomsDeclaration).datagrid('getRowIndex', row);
                        $(el.tbCustomsDeclaration).datagrid('deleteRow', index);
                        el.originalCustomsDeclarationRows = el.originalCustomsDeclarationRows.filter(oldRow => oldRow.customsDeclarationDetailId !== row.customsDeclarationDetailId);
                    }
                    if (el.filterCustomsDeclarationFlag){
                        $(el.tbCustomsDeclaration).datagrid('enableFilter');
                        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
                    }
                }
            }
        );
    }
    var searchHeight = $(el.form).outerHeight();
    $(el.tbCustomsDeclaration).datagrid({
        iconCls: 'icon-list',
        title: '报关明细',
        height: el.bodyHeight - searchHeight -50,
        pagination: true,
        pageSize: 500,
        pageList: [10, 50, 100, 200, 500, 1000,2000,3000],
        singleSelect: false,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        url: url,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'type',
                title: '单据类型',
                width: '80',
                exportEnum:getDictList('bg_type'),
                formatter: function (value) {
                    return getDicName('bg_type',value);
                }
            },
            {
                field: 'code',
                title: '委托单号',
                width: '80',
                align: 'left'
            },
            {
                field: 'codeDate',
                title: '单据日期',
                width: '80',
                align: 'left',
                formatter: function (value) {
                    if (value) {
                        return new Date(value).format('yyyy-MM-dd');
                    }
                    return value;
                }
            },
            {
                field: 'poCode',
                title: '采购订单编号',
                width: '100',
                align: 'left'
            },
            {
                field: 'materialCode',
                title: '物料编码',
                width: '100',
                align: 'left',
            },
            {
                field: 'deliveryOrderCodes',
                title: '送货单号',
                width: '100',
                align: 'left',
            },
            {
                field: 'num',
                title: '数量',
                width: '70',
                align: 'left'
            },
            {
                field: 'model',
                title: '产品型号',
                width: '120',
                align: 'left',
                // editor: {
                //     type: 'textbox',
                //     options: {
                //         // required: true,
                //         editable:true,
                //     }
                // }
            },
            {
                field: 'supplierName',
                title: '供应商简称',
                width: '120',
                align: 'left'
            },
            {
                field: 'currencyCode',
                title: '报关币种',
                width: '90',
                align: 'left',
                formatter: function (value) {
                    return getDicName('currency',value)
                }
            },
            {
                field: 'taxPrice',
                title: '进口单价',
                width: '90',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'taxAmount',
                title: '进口总价',
                width: '90',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            }
        ]],
        loadFilter: pagerCustomsDeclarationFilter,
        onClickRow: function (index, rowData) {
            if(optType !== 2){
                // if (editor !== index) {
                //     if (endEditing()) {
                //         editor = index;
                //         $(el.tbCustomsDeclaration).datagrid('updateRow', {index: index, row: {state: 2}})
                //         $(el.tbCustomsDeclaration).datagrid('selectRow', index).datagrid('beginEdit', index);
                //         editor = index;
                //     } else {
                //         editor = index;
                //         $(el.tbCustomsDeclaration).datagrid('selectRow', editor);
                //     }
                // } else {
                //     $(el.tbCustomsDeclaration).datagrid('updateRow', {index: index, row: {state: 2}})
                //     $(el.tbCustomsDeclaration).datagrid('selectRow', index).datagrid('beginEdit', index);
                //     editor = index;
                // }
            }

        },
        toolbar: toolbar,
    });
}
function loadTbReceiveVoucherGrid() {
    var url = '';
    if ($(el.id).val()){
        url = g.ctx + 'pc/finance/receipt/voucher/rest/provide/detail/byPaymentMatchingId?paymentMatchingId='+$(el.id).val();
    }
    var toolbar = [];
    if (optType===0){
        toolbar.push(
            {
                text: "获取明细",
                iconCls: 'icon-add',
                handler: function () {
                    getReceiveVoucher();
                }
            },
            "-",
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    btnReceiveVoucherFilter();
                }
            },
            "-",
            {
                text: "剔除",
                iconCls: 'icon-remove',
                handler: function () {
                    let rows = $(el.tbReceiveVoucher).datagrid('getSelections');
                    if (rows.length===0) {
                        layer.alert("请选择数据");
                        return;
                    }
                    //循环删除
                    for (let i = 0; i < rows.length; i++) {
                        let row = rows[i];
                        let index = $(el.tbReceiveVoucher).datagrid('getRowIndex', row);
                        $(el.tbReceiveVoucher).datagrid('deleteRow', index);
                        el.originalReceiveVoucherRows = el.originalReceiveVoucherRows.filter(oldRow => oldRow.customsDeclarationDetailId !== row.customsDeclarationDetailId);
                    }
                    if (el.filterCustomsDeclarationFlag){
                        $(el.tbReceiveVoucher).datagrid('enableFilter');
                        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
                    }
                }
            }
        );
    }
    var searchHeight = $(el.form).outerHeight();
    $(el.tbReceiveVoucher).datagrid({
        iconCls: 'icon-list',
        title: '物料凭证',
        height: el.bodyHeight - searchHeight -50,
        pagination: true,
        showFooter: true,
        pageSize: 500,
        pageList: [10, 50, 100, 200, 500, 1000,2000,3000],
        singleSelect: false,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        url: url,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'mvPostDate',
                title: '交货日期',
                width: 80,
                sortable: true,
                exportDateFormatter:'date',
                formatter: function (value) {
                    if (!value) {
                        return '';
                    }
                    return moment(value).format('YYYY-MM-DD');
                }
            },
            {
                field: 'receiveYear',
                title: '年度',
                width: 50,
                sortable: true
            },
            {
                field: 'mvCode',
                title: '物料凭证号',
                width: 90,
                sortable: true
            },
            {
                field: 'receiveRowNo',
                title: '行号',
                width: 50,
                sortable: true
            },
            {
                field: 'poCode',
                title: '订单号',
                width: 100,
                sortable: true,
            },
            {
                field: 'poItemNo',
                title: '行号',
                width: 50,
                sortable: true,
            },
            {
                field: 'materialCode',
                title: '物料编码',
                width: 110,
                sortable: true
            },
            {
                field: 'headUpText',
                title: '送货单号',
                width: 110,
                sortable: true
            },
            {
                field: 'voucherFlag',
                title: '入库标识',
                width: 70,
                sortable: true,
                exportEnum:[
                    {code:'S',codeWithDesc:'入库'},
                    {code:'H',codeWithDesc:'退货'}
                ],
                formatter: function (value,row) {
                    if (isBlank(row.voucherFlag)){
                        return '';
                    }
                    if (row.voucherFlag === 'S') {
                        return '<span style="color: green;">入库</span>';
                    }
                    if (row.voucherFlag === 'H') {
                        return '<span style="color: red;">退货</span>';
                    }
                }
            },
            {
                field: 'mvNum',
                title: '数量',
                width: 90,
                sortable: true,
                formatter: function (value) {
                    if (value < 0) {
                        return '<span style="color: red;">' + formatterPrice(value) + '</span>';
                    }else {
                        return formatterPrice(value)
                    }
                }
            },
            {
                field: 'taxAmount',
                title: '物料凭证金额',
                width: 100,
                sortable: true,
                formatter: function (value) {
                    if (value < 0) {
                        return '<span style="color: red;">' + formatterPrice(value) + '</span>';
                    }else {
                        return formatterPrice(value)
                    }
                }
            }
        ]],
        loadFilter: pagerReceiveVoucherFilter,
        onClickRow: function (index, rowData) {
            if(optType !== 2){
                if (editor !== index) {
                    if (endEditing()) {
                        editor = index;
                        $(el.tbReceiveVoucher).datagrid('updateRow', {index: index, row: {state: 2}})
                        $(el.tbReceiveVoucher).datagrid('selectRow', index).datagrid('beginEdit', index);
                        editor = index;
                    } else {
                        editor = index;
                        $(el.tbReceiveVoucher).datagrid('selectRow', editor);
                    }
                } else {
                    $(el.tbReceiveVoucher).datagrid('updateRow', {index: index, row: {state: 2}})
                    $(el.tbReceiveVoucher).datagrid('selectRow', index).datagrid('beginEdit', index);
                    editor = index;
                }
            }
            if(optType === 0){
                calculateTaxAmount();
            }

        },
        onSelect: function () {
            if(optType === 0){
                calculateTaxAmount();
            }
        },
        onUnselect: function () {
            if(optType === 0){
                calculateTaxAmount();
            }
        },
        onSelectAll: function () {
            if(optType === 0){
                calculateTaxAmount();
            }
        },
        onUnselectAll: function () {
            if(optType === 0){
                calculateTaxAmount();
            }
        },
        onLoadSuccess: function () {
            calculateTaxAmount();
        },
        toolbar: toolbar,
    });
}

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%',
        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: function (data) {
            if (data.rows.length>0){
                initFileForm('supplier-file-form');
            }
            var allRows = 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 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 getCustomsDeclaration() {
    var customsDeclarationDetailCode = $(el.customsDeclarationDetailCode).textbox('getValue');
    var supplierCode = $(el.supplierCode).textbox('getValue');
    if(!customsDeclarationDetailCode){
        topWin.layer.alert('请选择委托单号', {icon: 0});
        return false;
    }
    $(el.tbCustomsDeclaration).datagrid('options').queryParams = {
        code: customsDeclarationDetailCode,
        supplierCode: supplierCode
    };
    $(el.tbCustomsDeclaration).datagrid('options').loadFilter = pagerCustomsDeclarationFilter;
    $(el.tbCustomsDeclaration).datagrid('options').url = g.ctx + 'pc/finance/customs/declaration/detail/rest/create/noPage/list';
    $(el.tbCustomsDeclaration).datagrid('load');
}
function getReceiveVoucher() {
    if(el.originalCustomsDeclarationRows.length===0){
        topWin.layer.alert('请先获取委托单信息', {icon: 0});
        return false;
    }
    var companyCode = $(el.companyCode).textbox('getValue');
    if(!companyCode){
        topWin.layer.alert('请选择交易主体', {icon: 0});
        return false;
    }
    var supplierCode = $(el.supplierCode).textbox('getValue');

    //把el.originalCustomsDeclarationRows中的poCode组装成数组
    var poCode = el.originalCustomsDeclarationRows.map(function (item) {
        return item.poCode;
    })
    var materialCode = el.originalCustomsDeclarationRows.map(function (item) {
        return item.materialCode;
    })
    $(el.tbReceiveVoucher).datagrid('options').queryParams = {
        supplierCode: supplierCode,
        companyCode: companyCode,
        poCode: poCode.join(','),
        materialCode: materialCode.join(','),
        type : $(el.type).combobox('getValue')
    };
    $(el.tbReceiveVoucher).datagrid('options').loadFilter = pagerReceiveVoucherFilter;
    $(el.tbReceiveVoucher).datagrid('options').url = g.ctx + 'pc/finance/receipt/voucher/rest/provide/create/paymentMatching';
    $(el.tbReceiveVoucher).datagrid('load');
}
function btnCustomsDeclarationFilter() {
    if (el.filterCustomsDeclarationFlag){
        el.filterCustomsDeclarationFlag = false;
        $(el.tbCustomsDeclaration).datagrid('disableFilter');
    }else {
        el.filterCustomsDeclarationFlag = true;
        $(el.tbCustomsDeclaration).datagrid('enableFilter');
        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
    }
}
function btnReceiveVoucherFilter() {
    if (el.filterReceiveVoucherFlag){
        el.filterReceiveVoucherFlag = false;
        $(el.tbReceiveVoucher).datagrid('disableFilter');
    }else {
        el.filterReceiveVoucherFlag = true;
        $(el.tbReceiveVoucher).datagrid('enableFilter');
        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
    }
}

// 分页数据的操作
function pagerCustomsDeclarationFilter(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.originalCustomsDeclarationRows) {
        data.originalCustomsDeclarationRows = (data.rows);
        el.originalCustomsDeclarationRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalCustomsDeclarationRows.slice(start, end));
    return data;
}

function pagerReceiveVoucherFilter(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.originalReceiveVoucherRows) {
        data.originalReceiveVoucherRows = (data.rows);
        el.originalReceiveVoucherRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalReceiveVoucherRows.slice(start, end));
    return data;
}

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

function calculateTaxAmount(){
    var allRows = [];
    if (optType===0){
        allRows = $(el.tbReceiveVoucher).datagrid('getSelections');
    }else {
        allRows = $(el.tbReceiveVoucher).datagrid('getRows');
    }

    var total = new BigNumber(0);
    var mvNum = new BigNumber(0);
    for (let i = 0; i < allRows.length; i++) {
        if (allRows[i].taxAmount){
            total = new BigNumber(allRows[i].taxAmount).plus(total);
            mvNum = new BigNumber(allRows[i].mvNum).plus(mvNum);
        }
    }
    $(el.taxAmount).textbox('setValue',total);

    var footers = $(el.tbReceiveVoucher).datagrid('getFooterRows');
    if (footers){
        footers[0]['materialCode'] = '合计';
        footers[0]['mvNum'] = mvNum;
        footers[0]['taxAmount'] = total;
        $(el.tbReceiveVoucher).datagrid('reloadFooter');
    }

}
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 clearCustomsDeclarationPageTableData() {
    el.originalCustomsDeclarationRows = [];
    $(el.tbCustomsDeclaration).datagrid('loadData', {total: 0, rows: []});
}

function clearReceiveVoucherPageTableData() {
    el.originalReceiveVoucherRows = [];
    $(el.tbReceiveVoucher).datagrid('loadData', {total: 0, rows: []});
}

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);
        // }
        calculateTaxAmount();
        var formData = $(el.form).serializeJson();
        formData.id = optType===3?'':$(el.id).val();
        formData.taxAmount =  Number(formData.taxAmount.replace(/,/g,''));
        // formData.files = $(el.files).attr('data-fileIds');
        // endEditing();
        let customsDeclarationRows = $(el.tbCustomsDeclaration).datagrid('getSelections');
        if (customsDeclarationRows.length <= 0) {
            layer.msg('请选择报关明细', {time: 2000});
            return false;
        }
        let tbReceiveVoucherRows = $(el.tbReceiveVoucher).datagrid('getSelections');
        if (tbReceiveVoucherRows.length <= 0) {
            layer.msg('请选择物料凭证', {time: 2000});
            return false;
        }
        //统计customsDeclarationRows中的数量字段总和和tbReceiveVoucherRows的数量字段总和是否一致
        let customsDeclarationSum = new BigNumber(0);
        for (let i = 0; i < customsDeclarationRows.length; i++) {
            customsDeclarationSum = new BigNumber(customsDeclarationRows[i].num).plus(customsDeclarationSum);
        }
        let receiveVoucherSum = new BigNumber(0);
        for (let i = 0; i < tbReceiveVoucherRows.length; i++) {
            receiveVoucherSum = new BigNumber(tbReceiveVoucherRows[i].mvNum).plus(receiveVoucherSum);
        }
        if (customsDeclarationSum.toString() !== receiveVoucherSum.toString()) {
            layer.msg('报关明细数量总和物料凭证数量总和不一致', {time: 2000});
            return false;
        }

        //统计customsDeclarationRows中的金额字段总和和tbReceiveVoucherRows的金额字段总和是否一致
        let customsDeclarationAmount = new BigNumber(0);
        for (let i = 0; i < customsDeclarationRows.length; i++) {
            customsDeclarationAmount = new BigNumber(customsDeclarationRows[i].taxAmount).plus(customsDeclarationAmount);
        }
        let receiveVoucherAmount = new BigNumber(0);
        for (let i = 0; i < tbReceiveVoucherRows.length; i++) {
            receiveVoucherAmount = new BigNumber(tbReceiveVoucherRows[i].taxAmount).plus(receiveVoucherAmount);

        }
        if (customsDeclarationAmount.toString() !== receiveVoucherAmount.toString()) {
            layer.msg('报关明细进口总价总和物料凭证金额总和不一致', {time: 2000});
            return false;
        }


        formData.customsDeclarationRelationList = customsDeclarationRows;
        formData.receiveVoucherRelationList = tbReceiveVoucherRows;
        var satisfyFlagExist = false;
        const uploadAttachmentFileDataList = Number(tbAttachmentLookFlag)===1?[]:$(el.tbAttachment).datagrid("getData").rows;
        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/matching/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/matching/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: '温馨提示'});
        }
    });
}