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


$(function () {
    initDict('unit,currency,payment_method,bg_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'
    });
    //交易主体
    initCompanyCombo();
    //类型
    $(el.type).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        data: getDictList('bg_type')
    });
    if (isSupplier===0){
        $(el.supplierName).textbox({
            prompt: '请选择代理商',
            required: true,
            editable:false,
            icons: [
                {
                    iconCls: 'icon-search',
                    handler: function () {
                        if (optType!==2&&optType!==3){
                            choseSupplier();
                        }
                    }
                }
            ]
        });
        $(el.supplierName).textbox('textbox').css('cursor', 'pointer');
        $(el.supplierName).textbox('textbox').bind('click', function () {
            if (optType!==2&&optType!==3){
                choseSupplier();
            }
        });
    }
    $(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 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.supplierCode).val(data[0].supplierCode);
                        $(el.shortName).val(data[0].shortName);
                        $(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/customs/declaration/detail/rest/getDetailListByMainId?mainId='+$(el.id).val();
    let columns = [

        // {
        //     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 (newValue && String(newValue).trim() !== '') {
                            scheduleInitFileGrid(300); // 防抖，避免每个字符都请求一次
                        } 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:[]});
                            el.businessCodes = [];
                        }
                    }
                }
            }
        },
        {
            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: 'poCode',
            title: '采购订单编号<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    // required:true
                }
            }
        },
        {
            field: 'materialCode',
            title: '物料编码',
            width: '180',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    // required: true,
                    editable:true,
                }
            }
        },
        {
            field: 'num',
            title: '数量<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    precision: 0,
                    onChange: function (newValue, oldValue) {
                        if (__recalcLock) return;
                        var idx = getIndexFromEditorDom(this);
                        if (idx !== null) recalcRowAndTotal(idx);
                    }
                }
            }
        },
        {
            field: 'model',
            title: '产品型号<span style="color: red">*</span>',
            width: '180',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    // required: true,
                    editable:true,
                }
            }
        },
        {
            field: 'supplierCode',
            title: '供应商编码<span style="color: red">*</span>',
            width: '180',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    // required: true,
                    editable:false,
                    prompt: '选择自动带出供应商信息',
                    icons: [{
                        iconCls: 'icon-search',
                        handler: function () {
                            let rowIndex = $($(this).parents('tr')[1])[0]['rowIndex'];
                            var selectSupplierElement = openDialog("choseSupplier", g.ctx + "pc/supplier/supplierSelect?single=1&state=2,3,6", {
                                title: '选择供应商',
                                width: '50%',
                                height: '80%',
                                cache: false,
                                modal: true,
                                border: false,
                                draggable: false,
                                shadow: false,
                                onClose: function () {
                                    selectSupplierElement.dialog('destroy');
                                },
                                buttons: [{
                                    text: '确定',
                                    iconCls: 'icon-save',
                                    handler: function () {
                                        topWin.frames['choseSupplier'].chooseRow(function (data) {
                                            let supplierCode = $(el.tb).datagrid('getEditor', {
                                                index: rowIndex,
                                                field: 'supplierCode'
                                            }).target;
                                            supplierCode.textbox('setValue', data.supplierCode);
                                            //物料描述
                                            let supplierName = $(el.tb).datagrid('getEditor', {
                                                index: rowIndex,
                                                field: 'supplierName'
                                            }).target;
                                            supplierName.textbox('setValue',data.shortName);
                                            selectSupplierElement.dialog('close');
                                        });
                                    }
                                }, {
                                    text: '关闭',
                                    iconCls: 'icon-cancel',
                                    handler: function () {
                                        selectSupplierElement.dialog('close');
                                    }
                                }]
                            });
                        }
                    }]
                }
            }
        },

        {
            field: 'supplierName',
            title: '供应商简称<span style="color: red">*</span>',
            width: '180',
            align: 'left',
            editor: {
                type: 'textbox',
                options: {
                    // required: true,
                    editable:true,
                }
            }
        },
        {
            field: 'currencyCode',
            title: '报关币种',
            width: '120',
            align: 'left',
            editor: {
                type: 'combobox',
                options: {
                    required: false,
                    valueField: "code",
                    textField: "codeWithDesc",
                    data: getDictList('currency'),
                    editable: false,
                    panelHeight: '150'
                }
            },
            formatter: function (value) {
                return getDicName('currency',value)
            }
        },
        {
            field: 'taxPrice',
            title: '进口单价<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    precision: priceHandle.precision,
                    onChange: function(newValue, oldValue) {
                        if (__recalcLock) return;
                        var idx = getIndexFromEditorDom(this);
                        if (idx !== null) recalcRowAndTotal(idx);
                    }
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        },
        {
            field: 'taxAmount',
            title: '进口总价<span style="color: red">*</span>',
            width: '120',
            align: 'left',
            editor: {
                type: 'numberbox',
                options: {
                    precision: priceHandle.precision,
                    readonly: true
                }
            },
            formatter: function (value) {
                return formatterPrice(value)
            }
        }
    ];
    var toolbar = [];
    if (optType===0||optType===1){
        toolbar.push(
            {
                text: "新增",
                iconCls: 'icon-add',
                handler: function () {
                    //  新增后立即编辑 + taxAmount 默认 0
                    appendAndEditRow({
                        // 你需要默认带出的字段可以在这里设置
                        // currencyCode: $(el.currencyCode).combobox('getValue'),
                        taxAmount:0
                    });
                }
            },
            "-",
            {
                text: "删除",
                iconCls: 'icon-remove',
                handler: function () {
                    var row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.alert("请选择数据");
                        return;
                    }

                    var index = $(el.tb).datagrid('getRowIndex', row);

                    // 如果删除的是正在编辑行，先 cancelEdit
                    if (__dgEditIndex === index) {
                        $(el.tb).datagrid('cancelEdit', index);
                        __dgEditIndex = undefined;
                    }

                    $(el.tb).datagrid('deleteRow', index);

                    // 删除后如果编辑行索引在后面，要前移
                    if (__dgEditIndex !== undefined && __dgEditIndex !== null && __dgEditIndex > index) {
                        __dgEditIndex = __dgEditIndex - 1;
                    }

                    recalcTotal();
                    initFileGrid();
                    setRemark();
                }
            }

            , "-",
            {
                text: '导入',
                iconCls: 'icon-import',
                handler: function () {
                    materialImport();
                }
            }
        );
    }
    $(el.tb).datagrid({
        iconCls: 'icon-list',
        height: '490',
        singleSelect: false,
        showFooter: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        url: url,
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [columns],
            onClickRow: function (index, rowData) {
                if (optType === 2 || optType === 5) return; // 查看态不编辑

                if (__dgEditIndex === index) {
                    // 已经在编辑本行
                    $(el.tb).datagrid('selectRow', index).datagrid('beginEdit', index);
                    return;
                }

                // 切换到新行：先结束旧行编辑
                if (endEditing()) {
                    $(el.tb).datagrid('selectRow', index).datagrid('beginEdit', index);
                    __dgEditIndex = index;

                    // 进入编辑后补算一次
                    recalcRowAndTotal(index);
                } else {
                    // 旧行校验未通过：仍选中旧行
                    if (__dgEditIndex !== undefined && __dgEditIndex !== null) {
                        $(el.tb).datagrid('selectRow', __dgEditIndex);
                    }
                }
            },
        toolbar: toolbar,
        onLoadSuccess: function (data) {
            if (optType !== 0) {
                initFileGrid();

                // 加载后：补齐每行 taxAmount（非编辑态不会清空）
                var rows = $(el.tb).datagrid('getRows');
                for (var i = 0; i < rows.length; i++) {
                    var rowAmount = bn(rows[i].num).times(bn(rows[i].taxPrice)).decimalPlaces(
                        2,
                        priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN
                    );
                    setRowTaxAmount(i, rowAmount.toNumber());
                }
                recalcTotal();
            }
        }
    });

}

//2026-001-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",
//             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=customs_declaration';
//                         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: []});
//                 }
//             }
//         })
//
//     }
// }
// 防抖计时器
var __initFileGridTimer = null;

function scheduleInitFileGrid(delayMs){
    clearTimeout(__initFileGridTimer);
    __initFileGridTimer = setTimeout(function(){
        initFileGrid();
        setRemark();
    }, delayMs || 300);
}

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;
    }

    // ✅ 关键：用 getRowFieldValue 取“编辑态实时值”
    var firstEntrustNo = getRowFieldValue(0, 'code');
    if (isBlank(firstEntrustNo)) {
        return; // 委托单号没填，不做附件回填
    }

    // ✅ 如果你希望附件检查表按“所有委托单号”展示，用所有行 code 去重
    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",
        data: {entrustNo: firstEntrustNo},
        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 attachmentTypeCreateConfigCodes = attachmentTypeCreateConfigList.map(function(item){
                        return item.code;
                    });

                    let url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+$(el.id).val()+'&businessTypeCodes=customs_declaration';
                    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'); //这里 load 完，onLoadSuccess 会自动刷新 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: '导出',
                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: 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;
                        });
                        obj[attachmentTypeCreateConfig.code] = exist?1:0;
                        //是否存在校验
                        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});
            }
        },
    });
}
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/customs/declaration/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');
                    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,
                            codeDate: product.codeDate,
                            poCode: product.poCode,
                            materialCode: product.materialCode,
                            num: product.num,
                            model: product.model,
                            supplierCode: product.supplierCode,
                            supplierName: product.supplierName,
                            currencyCode: product.currencyCode,
                            taxPrice: product.taxPrice,
                            taxAmount: product.taxAmount
                        });
                    }
                    for (var i = 0; i < $(el.tb).datagrid('getRows').length; i++) {
                        // 若 taxAmount 没值则补算
                        var ta = getRowFieldValue(i, 'taxAmount');
                        if (ta === null || ta === undefined || ta === '' || Number(ta) === 0) {
                            recalcRowAndTotal(i);
                        }
                    }
                    recalcTotal();
                    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 rows = $(el.tb).datagrid('getRows');
    if (!$(el.remark).textbox('getValue')&&rows.length>0){
        if (rows[0].code&&$(el.supplierCode).val()){
            $(el.remark).textbox('setValue',rows[0].code+'_'+$(el.supplierCode).val()+'_报关单');
        }

    }
}

function copy(type) {
    $(el.tb).datagrid('endEdit', __dgEditIndex);
    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() {
    resetDetailAndHeaderTotal();
}

// ✅ 清空明细 + 清空页脚合计 + 表头总金额置 0 + 清空编辑态
function resetDetailAndHeaderTotal() {
    // 1) 结束/取消编辑（避免编辑态残留导致异常）
    try {
        if (__dgEditIndex !== undefined && __dgEditIndex !== null) {
            $(el.tb).datagrid('cancelEdit', __dgEditIndex);
        }
    } catch (e) {}
    __dgEditIndex = undefined;

    // 2) 清空明细
    $(el.tb).datagrid('loadData', { total: 0, rows: [] });

    // 3) 清空页脚合计（避免 footer 还显示旧值）
    try {
        $(el.tb).datagrid('reloadFooter', [{
            materialCode: '合计',
            num: '0',
            taxAmount: '0.00'
        }]);
    } catch (e) {}

    // 4) 表头总金额置 0
    if ($(el.taxAmount).length > 0) {
        $(el.taxAmount).textbox('setValue', '0.00');
    }
// 6) 清空附件区
    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 = [];

    // 5) 备注也可以顺带清空/重置（按你业务选）
    // $(el.remark).textbox('setValue', '');
}


async function saveOrUpdate(call){
    if($(el.form).form('validate')){
        endEditing();
        var formData = $(el.form).serializeJson();
        formData.id = optType===3?'':$(el.id).val();
        formData.taxAmount =  Number(formData.taxAmount.replace(/,/g,''));
        if (formData.type==='2'&&new BigNumber(formData.taxAmount).isGreaterThan(new BigNumber(0))){
            layer.msg('单据类型为扣款时需要总金额必须小于0', {time: 2000});
            return false;
        }
        // formData.files = $(el.files).attr('data-fileIds');
        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(!row[i].code){
                layer.msg("明细第"+ ++i+"行，单号必填");
                return false;
            }
            if(!row[i].codeDate){
                layer.msg("明细第"+ ++i+"行，单据日期必填");
                return false;
            }
            if(!row[i].poCode){
                layer.msg("明细第"+ ++i+"行，采购订单编号必填");
                return false;
            }

            if(!row[i].num){
                layer.msg("明细第"+ ++i+"行，数量必填");
                return false;
            }
            if(!row[i].model){
                layer.msg("明细第"+ ++i+"行，产品型号必填");
                return false;
            }
            if(!row[i].supplierCode){
                layer.msg("明细第"+ ++i+"行，供应商编码必填");
                return false;
            }
            if(!row[i].supplierName){
                layer.msg("明细第"+ ++i+"行，供应商简称必填");
                return false;
            }
            if(!row[i].currencyCode){
                layer.msg("明细第"+ ++i+"行，报关币种必填");
                return false;
            }

            if(!row[i].taxPrice){
                layer.msg("明细第"+ ++i+"行，进口单价必填");
                return false;
            }
            if(!row[i].taxAmount){
                layer.msg("明细第"+ ++i+"行，进口总价必填");
                return false;
            }
            if (Number(formData.type) === 1) {
                if(!row[i].materialCode){
                    layer.msg("明细第"+ ++i+"行，物料编码必填");
                    return false;
                }
            }else {

            }
            // 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/customs/declaration/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();
    let row = $(el.tb).datagrid('getRows');
    var formData = {};
    formData.id = $(el.id).val();
    formData.approveStatus = approveStatus;
    formData.approveOpinion = approveOpinion;
    formData.detailList = row;
    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/customs/declaration/rest/financeConfirmCheck',
        method: 'post',
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (result) {
            topWin.layer.close(loading);
            if (result){
                let currentIndex = 0;
                let logDetailList = [];
                function processValidationMessages(messages) {
                    if (currentIndex >= messages.length) {
                        // 所有校验通过后调用 dataSaveAjax
                        formData.logDetailList = logDetailList;
                        financeConfirmAjax(formData,call)
                        return true;
                    }

                    const currentMessage = messages[currentIndex];
                    layer.confirm(currentMessage + ',是否继续？', {
                        btn: ['确定', '取消'] // 按钮
                    }, function () {
                        layer.closeAll();
                        currentIndex++;
                        const logDetail = {
                            confirmAction: "CONFIRM",
                            warnMessage: currentMessage + ',是否继续？'
                        }
                        logDetailList.push(logDetail);
                        processValidationMessages(messages); // 继续处理下一个校验消息
                    }, function () {
                        layer.closeAll();
                        return false; // 用户取消，结束处理
                    });
                }

                // 调用函数开始处理校验消息
                processValidationMessages(result);
            }else {
                financeConfirmAjax(formData,call)
            }
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });

}

function financeConfirmAjax(formData,call){
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/customs/declaration/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: '温馨提示'});
        }
    });
}

/**
 * 初始化交易主体下拉框
 */
function initCompanyCombo() {
    if (!isSupplier) {
        // 非供应商：直接加载全部公司
        $(el.companyCode).combobox({
            valueField: 'code',
            textField: 'codeWithDesc',
            limitToList: true,
            method: 'POST',
            prompt: '--- 请选择 ---',
            url: g.ctx + 'pc/sys/company/rest/listAll',
            onChange: function (newVal, oldVal) {
                // oldVal 为空表示初始加载不处理
                if (oldVal && newVal !== oldVal) {
                    clearPageTableData(); // ✅ 清空明细 + 表头总金额置0
                }
            }
        });
        return;
    }

    // 供应商：供应商主数据品类中的公司
    $.ajax({
        type: 'get',
        url: g.ctx + 'pc/supplier/purchaseCategory/rest/listSupplier?supplierId=' + supplierId,
        success: function (resp) {
            const rows = (resp && resp.rows) ? resp.rows : [];

            let companyCodes = [];
            for (let i = 0; i < rows.length; i++) {
                const c = rows[i] && rows[i].companyCode;
                if (c) companyCodes.push(String(c));
            }
            companyCodes = companyCodes.filter(function (item, idx, self) {
                return self.indexOf(item) === idx;
            });

            // 再拉全部公司并过滤（后端不支持按 code 查的情况下最通用）
            $.ajax({
                type: 'post',
                url: g.ctx + 'pc/sys/company/rest/listAll',
                success: function (all) {
                    // all 可能是数组，也可能是 {rows:[]}/ {data:[]}
                    const allCompanies = Array.isArray(all) ? all : (all.rows || all.data || []);
                    const filtered = allCompanies.filter(function (item) {
                        return item && item.code && companyCodes.indexOf(String(item.code)) !== -1;
                    });

                    // 最后：用本地数据初始化 combobox（不走 url，不存在 onLoadSuccess 循环）
                    $(el.companyCode).combobox({
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        limitToList: true,
                        panelHeight: 'auto',
                        prompt: '--- 请选择 ---',
                        data: filtered,
                        onChange: function (newVal, oldVal) {
                            if (oldVal && newVal !== oldVal) {
                                clearPageTableData();
                            }
                        }
                    });
                }
            });
        },
        error: function () {}
    });
}

/**
 * 获取所有业务附件
 */
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;
}
//2026-01-21重构计算逻辑代码
// ========== 实时计算与汇总：稳定版 ==========

// 防止 setValue 触发 onChange 导致递归
var __recalcLock = false;

// 数值转 BigNumber（空当 0）
function bn(v) {
    if (v === null || v === undefined || v === '') return new BigNumber(0);
    return new BigNumber(String(v).replace(/,/g, ''));
}

// 获取行索引（从任意 editor DOM）
function getIndexFromEditorDom(dom) {
    var idx = $(dom).closest('tr.datagrid-row').attr('datagrid-row-index');
    return (idx === undefined || idx === null) ? null : parseInt(idx, 10);
}

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

// 设置某行 taxAmount：编辑中只改当前 cell editor；非编辑中 updateRow
function setRowTaxAmount(index, amountNum) {
    var taxAmountEd = $(el.tb).datagrid('getEditor', { index: index, field: 'taxAmount' });
    if (taxAmountEd) {
        __recalcLock = true;
        $(taxAmountEd.target).numberbox('setValue', amountNum);
        __recalcLock = false;
    } else {
        $(el.tb).datagrid('updateRow', { index: index, row: { taxAmount: amountNum } });
    }
}

// 计算某行（num * taxPrice）并更新 taxAmount + 汇总
function recalcRowAndTotal(index) {
    if (__recalcLock) return;

    var numVal = getRowFieldValue(index, 'num');
    var priceVal = getRowFieldValue(index, 'taxPrice');

    var numBN = bn(numVal);
    var priceBN = bn(priceVal);

    var rowAmount = numBN.times(priceBN).decimalPlaces(
        2,
        priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN
    );

    setRowTaxAmount(index, rowAmount.toNumber());
    recalcTotal();
}

// 汇总：表头总金额 + footer（不会重绘明细行）
function recalcTotal() {
    var rows = $(el.tb).datagrid('getRows');
    var total = new BigNumber(0);
    var numTotal = new BigNumber(0);

    for (var i = 0; i < rows.length; i++) {
        numTotal = numTotal.plus(bn(getRowFieldValue(i, 'num')));
        total = total.plus(bn(getRowFieldValue(i, 'taxAmount')));
    }

    $(el.taxAmount).textbox('setValue', total.toFixed(2));

    $(el.tb).datagrid('reloadFooter', [{
        materialCode: '合计',
        num: numTotal.toFixed(0),
        taxAmount: total.toFixed(2)
    }]);
}

// 结束当前编辑行（含校验），并汇总
function endEditing() {
    if (__dgEditIndex === undefined || __dgEditIndex === null) {
        recalcTotal();
        initFileGrid();
        setRemark();
        return true;
    }
    if ($(el.tb).datagrid('validateRow', __dgEditIndex) && $(el.tb).datagrid('endEdit', __dgEditIndex)) {
        __dgEditIndex = undefined;
        recalcTotal();
        initFileGrid();
        setRemark();
        return true;
    }
    return false;
}

// 新增行：append 后立即 beginEdit，并默认 taxAmount=0
function appendAndEditRow(defaultRow) {
    if (!endEditing()) return;

    var row = $.extend(true, { taxAmount: 0 }, defaultRow || {});
    $(el.tb).datagrid('appendRow', row);

    var idx = $(el.tb).datagrid('getRows').length - 1;
    $(el.tb).datagrid('selectRow', idx).datagrid('beginEdit', idx);
    __dgEditIndex = idx;

    setRowTaxAmount(idx, 0);
    recalcTotal();
}
