var el = {
    table_tb: '#table_tb',
    table_pay: '#table_pay',
    subjectCode: '#subjectCode',
    paymentStage: '#paymentStage',
    paymentWay:'#paymentWay',
    contractCurrency: '#contractCurrency',
    checkbox_purchase: "#checkbox_purchase",
    checkbox_payment: "#checkbox_payment",
    checkbox_right: '#checkbox_right',
    contractCode: '#contractCode',
    editIndex: undefined,
    tbEditIndex: undefined,
    payEditIndex: undefined,
    purchaseDialog: null

}
const dictData = getDictList('contract_item_subject_sap');  // 添加 const
var editor = undefined;
window.handleCostCenterSelect = null;
var type = null;
$(function () {
    initDict('currency,po_type,signature_type,contract_pay_boot_item,' +
        'contractCategory,gx_contract_subject,contract_item_subject,invoice_type,' +
        'sign_order,sign_type,payment_way,payment_stage,contractContentLink,gx_contract_type,' +
        'unit,payment_period,quality_date,apply_project_type,model_type,model_apply,stock_point');
    initNecessaryDatas('pc/sys/tax/rest/listAll');

    initColumns();

    $('#btn_add').linkbutton('enable');
    loadGrid();
});

function  initColumns(d) {
    $("#subjectCode").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('gx_contract_subject')
    })

    $("#contractCover").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('contractContentLink')
    })

    $("#qualityDate").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('quality_date')
    })

    //货币编码
    $("#contractCurrency").combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: true,
        panelHeight: 'auto',
        editable: false,
        data: getDictList('currency')
    })

    //发票类型
    $("#contractInvoiceCode").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('invoice_type')
    })

    //订单类型
    $("#contractOrderType").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('po_type')
    })

    //采购组织
    $("#contractPurchaseGroupCode").combobox({
        valueField: 'purchaseOrgCode',
        textField: 'codeWithDesc',
        limitToList: true,
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseOrg/rest/listAll',
        onLoadSuccess: function () {
            $("#contractPurchaseGroupCode").combobox('select', "8000");
        }
    });

    //采购组
    $("#contractPurchaseGroup").combobox({
        valueField: 'purchaseGroupCode',
        textField: 'codeWithDesc',
        limitToList: true,
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        onLoadSuccess: function () {
            $.ajax({
                url: '/pc/sys/purchaseGroup/rest/listAll?pgName='+ $('#userName').val(),
                type: 'POST',
                async: false,
                success: function (res) {
                    if (res.length > 0) {
                        const firstCode = res[0].code;
                        $("#contractPurchaseGroup").combobox('select',firstCode );
                    }
                }
            })
        }
    });

    //付款方式
    $("#paymentWay").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('payment_way')
    });

    $("#contractAmount").textbox({
        onChange:function (newValue, oldValue) {
            $('#contractAmountCapital').textbox('setValue',number_chinese(newValue));
        }
    })

    $('#contractCompanyName').textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            layer.open({
                title: "我方公司选择",
                type: 2,
                area: ['600px', '550px'],
                content: '/pc/contract/manage/page/choseSupplier?type=1',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    type = $(layero).find("iframe")[0].contentWindow.document.getElementById("type").value;
                    if(name!=undefined&&code!=''){
                        $('#contractCompanyName').textbox('setValue',name);
                        $('#contractCompanyCode').val(code);
                        layer.close(index);
                    }else{
                        layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });

    $('#contractSupplierName').textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            layer.open({
                title: "供应商选择",
                type: 2,
                area: ['650px', '550px'],
                content: '/pc/contract/manage/page/choseSupplier?type=2',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    var currencyCode = $(layero).find("iframe")[0].contentWindow.document.getElementById("currencyCode").value;
                    if(name!=undefined&&code!=''){
                        $('#contractSupplierName').textbox('setValue',name);
                        $('#contractCurrency').combobox('setValue',currencyCode);
                        $('#contractSupplierCode').val(code);
                        layer.close(index);
                    }else{
                        layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });

    $('#contractSealType').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('sign_type'), onLoadSuccess: function () {
            $("#contractSealType").combobox('select',1);
        }
    });

    $('#contractSignOrder').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('sign_order'), onLoadSuccess: function () {
            $("#contractSignOrder").combobox('select',1);
        }
    });

    $('#contractType').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('gx_contract_type').filter(item =>
            !['05', '06'].includes(item.code) ),
        onSelect: function(record) {
            // 当选择合同类型时检查
            // checkAndSetContractDraft(record);
        },

        onChange:function (res) {
            if (res === '07') {
                // 07 状态：必填且可编辑
                $("#associationContract").textbox({
                    required: true,
                    readonly: false,
                    disabled: false
                });
            } else {
                // 非07 状态：只读且非必填
                $("#associationContract").textbox({
                    required: false,
                    readonly: true,
                    disabled: true
                });
            }

            if (res) {
                var data = $(this).combobox('getData');
                var selected = data.find(function(item) {
                    return item.name === res || item.code === res;
                });
                if (selected) {
                    checkAndSetContractDraft(selected);
                }
            }

            var isMoldContract = (res === '03'); // 表示“模具”合同
            var $table = $('#table_tb');
            var moldColumns = ['projectProcess', 'modelApply', 'modelType', 'modelNumber'];

            if (isMoldContract) {
                // 显示模具相关列
                moldColumns.forEach(function(field) {
                    $table.datagrid('showColumn', field);
                    setColumnRequired($table, field, true, el.tbEditIndex);
                });
                setColumnRequired($table, 'customerName', true, el.tbEditIndex);
            } else {
                // 隐藏模具相关列
                moldColumns.forEach(function(field) {
                    $table.datagrid('hideColumn', field);
                    setColumnRequired($table, field, false, el.tbEditIndex);
                });
                setColumnRequired($table, 'customerName', false, el.tbEditIndex);
            }

            $table.datagrid('refreshRow', el.tbEditIndex);
            // 可选：调整列宽以适应变化
            $table.datagrid('resize');
        },

    });

    $('#contractDraft').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":"01","name":"甲方"},
            {"code":"02","name":"乙方"}
        ]
    });

    $('#isMro').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":1,"name":"是"},
            {"code":2,"name":"否"}
        ], onLoadSuccess: function () {
            var id = $("#id").val();
            if (id == '') {
                $("#isMro").combobox('select',1);
                $("#mroDisplay").text('MRO数据展示');
            }
        },
        onSelect:function (d){
            let mro_flag = 0
            if(d.code == 1){
                mro_flag = 1
                $("#tbdsetMro").hide();
                $("#tbdsetOrder").show();
                $("#mroDisplay").text('MRO数据展示');
                loadGrid();
                //订单类型
                $("#contractOrderType").textbox({required:true});
                //关联合同
                $("#associationContract").textbox({required:false});
                //货币编码
                $("#contractCurrency").textbox({required:true});

            }else{
                $("#mroDisplay").text('合同数据展示');
                $("#tbdsetMro").show();
                $("#tbdsetOrder").hide();
                loadGrid();
                //订单类型
                $("#contractOrderType").textbox({required:false});
                //关联合同
                $("#associationContract").textbox({required:false});
                //货币编码
                $("#contractCurrency").textbox({required:false});
            }

            // $.ajax({
            //     url: '/pc/contract/manage/rest/getContractCategory',
            //     type: 'POST',
            //     async: false,
            //     data: {"mroFlag":mro_flag},
            //     success: function (res) {
            //         $("#contractType").combobox({
            //             valueField: 'code',
            //             textField: 'name',
            //             editable: false,
            //             panelHeight: 'auto',
            //             data: res,
            //             onChange:function (res) {
            //                 if(res== '采购补充协议' || res== '补充协议') {
            //                     //关联合同
            //                     $("#associationContract").textbox({required: true});
            //                 }else{
            //                     $("#associationContract").textbox({required: false});
            //                 }
            //             }
            //         })
            //     },
            //     error: function (res) {
            //         topWin.layer.alert(res.responseJSON.message, {icon: 2});
            //     }
            // })
        }
    });

    $('#isSap').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":"1","name":"是"},
            {"code":"2","name":"否"}
        ], onLoadSuccess: function () {
            var id = $("#id").val();
            if (id == '') {
                $("#isSap").combobox('select',2);
            }
        }
    });

    $('#isRaise').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":"1","name":"是"},
            {"code":"0","name":"否"}
        ], onLoadSuccess: function () {
            var id = $("#id").val();
            if (id == '') {
                $("#isRaise").combobox('select',0);
            }
        }
    });

    $('#isInitial').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":"1","name":"是"},
            {"code":"0","name":"否"}
        ], onLoadSuccess: function () {
            var id = $("#id").val();
            if (id == '') {
                $("#isInitial").combobox('select',0);
            }
        }
    });

    $('#associationContract').textbox({
        buttonText:'选择',
        iconAlign:'left',
        onClickButton:function () {
            layer.open({
                title: "合同选择",
                type: 2,
                area: ['650px', '550px'],
                content: '/pc/contract/manage/page/choseContract',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if(name!=undefined&&code!=''){
                        $('#associationContract').textbox('setValue',code);
                        layer.close(index);
                    }else{
                        layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });
}

function loadGrid(){
    // 加载付款明细（table_tb）- 补充可编辑配置
    $("#table_tb").datagrid({
        iconCls: 'icon-list',
        // url: '/pc/contract/mroManage/rest/selectContractDetailListPage?conId='+$("#id").val(),
        data: eval(items),
        height: 350,
        fitColumns:true,
        singleSelect: false,
        showFooter: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        // 核心：开启单元格编辑模式
        editable: true, // 必须开启
        editMode: 'cell', // 单元格编辑模式（而非行编辑）
        toolbar: [
            {
                text: '新增',
                id: 'btn_add',
                iconCls: 'icon-add',
                handler: function () {
                    addDetail();
                }
            },
            {
                text: '删除',
                id: 'btn_del',
                iconCls: 'icon-remove',
                handler: function (d) {
                    delDetail();
                }
            },
            {
                text: '导入',
                id: 'btn-data-in',
                iconCls: 'icon-upload',
                handler: function () {
                    var importDialog = openImportExcelDialog("static/excel/mro_contract_import.xlsx", "合同明细信息导入",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/contract/mroManage/rest/detail/import',
                            method: "POST",
                            data: formData,
                            contentType: false,
                            processData: false,
                            success: function (list) {
                                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                                    topWin.layer.close(idx);
                                    $.each(list, function (dataIndex, data) {
                                        $("#table_tb").datagrid('appendRow',data);
                                        setMroTotalContractAmount();
                                    });
                                    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: '温馨提示'});
                            }
                        });
                    });
                    setOperationLog("导入按钮", "MR类合同");
                }
            },
            {
                text: '导出信息',
                id: 'btn-export',
                iconCls: 'icon-filter',
                handler: function () {
                    var code=$(el.contractCode).val()
                    openExportDialog('pc/contract/mroManage/rest/detail/export', 'table_tb',code)
                    setOperationLog("导出信息按钮", "MR类合同");

                }
            }
        ],
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'purchaseCode',
                title: '资产申请单号',
                width: 150,
                editor: {
                    type: 'textbox',
                    options: {
                        required: false,
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                editor = el.tbEditIndex;
                                if (editor === undefined) {
                                    layer.alert('请先点击单元格进入编辑状态', {icon: 2});
                                    return;
                                }
                                el.purchaseDialog = openDialog('purchaseDialog', g.ctx + 'pc/inquiry/purchase/apply/bill/detail/select/purchaseDialog?purchasingBusinessType=02', {
                                    title: "采购申请选择",
                                    width: '95%',
                                    height: '95%',
                                    cache: false,
                                    modal: true,
                                    border: 'thin',
                                    onClose: function () {
                                        el.purchaseDialog.dialog('destroy');
                                    },
                                    buttons: [
                                        {
                                            text: '选择',
                                            iconCls: 'icon-ok',
                                            handler: function () {
                                                topWin.frames['purchaseDialog'].confirmChose(function (data) {
                                                    let updateRow = data[0];
                                                    updateRow.purchaseCode = updateRow.billCode;
                                                    updateRow.subjectCode = updateRow.subjectTypeCode;
                                                    updateRow.materialBrand = updateRow.brand;
                                                    updateRow.num = updateRow.requireNum;
                                                    updateRow.basisUnit = updateRow.unitCode;
                                                    updateRow.stockPointName = getDicName('stock_point', updateRow.stockPoint);
                                                    updateRow.id = null;
                                                    $(el.table_tb).datagrid('updateRow', {index: editor, row: updateRow});
                                                    $(el.table_tb).datagrid('beginEdit', editor);
                                                    el.tbEditIndex = editor;
                                                    el.purchaseDialog.dialog('close');
                                                });
                                            }
                                        },
                                        {
                                            text: '关闭',
                                            iconCls: 'icon-cancel',
                                            handler: function () {
                                                el.purchaseDialog.dialog('close');
                                            }
                                        }
                                    ]
                                });
                            }
                        }]
                    }
                }
            },
            {field: 'itemCode', title: '资产申请行项目',width:'100',
                editor: 'text' },
            {
                field: 'subjectCode', title: '资产类别<button type="button" onclick="copy(\'subjectCode\')" class="easyui-linkbutton">复制</button>',width:'140',
                formatter: function (value, row) { return getDicName('gx_contract_subject',value) },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'name',
                        data: getDictList('gx_contract_subject'),
                        editable: false,
                        required: true
                    }
                }
            },
            {
                field: 'applyProjectType',
                title: '申请样品制作项目类型',
                width: 100,
                hidden: true, // 默认隐藏
                formatter: function (value, row) { return getDicName('apply_project_type',value) },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        data: getDictList('apply_project_type'),
                        editable: false
                    }
                }
            },
            {
                field: 'modelApply',
                title: '模具申请',
                width: 150,
                hidden: true,
                formatter: function (value, row) { return getDicName('model_apply',value) },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        data: getDictList('model_apply'),
                        editable: false,
                        required: true
                    }
                }
            },
            {field: 'projectProcess', title: '项目所处阶段',width:'120',
                hidden: true,
                editor: 'text'
            },
            {
                field: 'modelType',
                title: '模具类型',
                width: 120,
                hidden: true,
                formatter: function (value, row) { return getDicName('model_type',value) },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        data: getDictList('model_type'),
                        editable: false,
                        required: true
                    }
                }
            },
            {
                field: 'modelNumber',
                title: '模具编号',
                width: 120,
                hidden: true,
                editor: {
                    type: 'textbox'
                }
            },
            {field: 'materialName', title: '物品名称/开模名称',width:'120',
                editor: {
                    type: 'textbox',
                    options: {
                        required: true
                    }
                }
            },
            {field: 'materialSpec', title: '型号规格/参数',width:'120',
                editor: {
                    type: 'textbox',
                    options: {
                        required: true
                    }
                }
            },
            {field: 'materialBrand', title: '品牌',width:'80',
                editor: {
                    type: 'text'
                }
            },
            {field: 'basisUnit', title: '单位',width:'80',
                formatter: function (value, row) { return getDicName('unit',value) },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        data: getDictList('unit'),
                        editable: false,
                        required: true
                    }
                }
            },
            {
                field: 'taxRateCode',
                title: '税率',
                width: '10%',
                align: 'center',
                editor: {
                    type: 'combobox',
                    options: {
                        limitToList: true,
                        valueField: 'code',
                        textField: 'codeWithDesc',
                        panelHeight: 'auto',
                        required: true,
                        editable: false,
                        data: getNecessaryDataList("pc/sys/tax/rest/listAll"),
                        onChange: function (newValue, oldValue) {
                            calculateDetailAmount(el.table_tb, el.tbEditIndex);
                        }
                    }
                },
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll', value);
                }
            },
            {
                field: 'price',
                title: '含税单价',
                width: '100',
                editor: {
                    type: 'numberbox',
                    options: {
                        precision: 2,
                        required: true,
                        onChange: function(newValue, oldValue) {
                            calculateDetailAmount(el.table_tb, el.tbEditIndex);
                        }
                    }
                },
                formatter: function (value) {
                    return formatMoney(value)
                }
            },
            {field: 'enablePurchaseNum', title: '资产请购可用数量', width: '100',
                editor: {
                    type: 'numberbox',
                    options: {
                        min: 0,
                        precision: 0,
                        editable: false
                    }
                },
                formatter: function(value) {
                    return (value == null || value === '') ? 0 : value;
                }
            },
            {field: 'num', title: '数量', width: '60', editor: {
                    type: 'numberbox',
                    options: {
                        min: 0,
                        precision: 0,
                        required: true,
                        onChange: function(newValue, oldValue) {
                            calculateDetailAmount(el.table_tb, el.tbEditIndex);
                        }
                    }
                }, },
            ///含税单价/（1+税码）
            {field: 'noTaxPrice', title: '未税单价',width:'120 ' ,
                editor: {
                    type: 'numberbox',
                    options: { precision: 2, readonly: true }
                },
                formatter: function (value) {
                    return formatMoney(value)
                }
            },
            {field: 'amount', title: '含税金额',width:'120',
                editor: {
                    type: 'numberbox',
                    options: { precision: 2, readonly: true }
                },
                formatter: function (value) {
                    return formatMoney(value)
                }
            },
            {field: 'useDeptName', title: '使用部门名称',width:'120',
                editor: {
                    type: 'text',
                    options: {
                        required: true
                    }
                }
            },
            {field: 'useDeptCode', title: '使用部门编码',width:'120',
                editor: 'text', hidden: true},
            {field: 'userName', title: '使用人名称',width:'100',
                editor: {
                    type: 'text',
                    options: {
                        required: true
                    }
                }
            },
            {field: 'userCode', title: '使用人工号',width:'100',
                editor: 'text', hidden: true},
            {
                field: 'costCenterCode',
                title: '成本中心编码',
                hidden: true,
                editor: 'text'
            },
            {
                field: 'costCenterName',
                title: '成本中心',
                width: 150,
                editor: {
                    type: 'textbox',
                    options: {
                        required: true,
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                // 1. 记录当前编辑行索引
                                editor = el.tbEditIndex;
                                if (editor === undefined) {
                                    layer.alert('请先点击单元格进入编辑状态', {icon: 2});
                                    return;
                                }

                                // 2. 打开弹窗
                                var layerIndex = layer.open({
                                    title: "成本中心选择",
                                    type: 2,
                                    area: ['50%', '95%'],
                                    content: g.ctx + 'pc/mall/shoppingPay/page/select',
                                    modal: true,
                                    btn: ['选择', '取消'],
                                    yes: function (index, layero) {
                                        // 获取iframe窗口对象
                                        var iframeWin = layero.find('iframe')[0].contentWindow;
                                        var grid = iframeWin.$('#tb');

                                        if (grid.length === 0) {
                                            layer.alert('未找到成本中心数据表格，请检查弹窗页面是否有id="tb"的表格', {icon: 2});
                                            return;
                                        }

                                        var rows = grid.datagrid('getChecked');
                                        if (rows.length !== 1) {
                                            layer.alert('请选中且仅选中一条成本中心数据', {icon: 2});
                                            return;
                                        }
                                        var row = rows[0];

                                        // 3. 回填成本中心名称（核心修复：先校验editor有效性）
                                        let nameEditor = $("#table_tb").edatagrid('getEditor', {
                                            index: editor,
                                            field: 'costCenterName'
                                        });
                                        if (nameEditor && nameEditor.target) {
                                            // 转为jQuery对象后操作
                                            $(nameEditor.target).textbox("setValue", row.describe || '');
                                        }

                                        // 4. 回填成本中心编码（修复readonly报错核心逻辑）
                                        let codeEditor = $("#table_tb").edatagrid('getEditor', {
                                            index: editor,
                                            field: 'costCenterCode'
                                        });
                                        if (codeEditor && codeEditor.target) {
                                            var $codeTarget = $(codeEditor.target);
                                            // 关键：先初始化textbox（如果未初始化）
                                            if (!$codeTarget.hasClass('textbox-f')) {
                                                $codeTarget.textbox(); // 手动初始化textbox组件
                                            }
                                            // 先赋值，再设置只读（分开操作避免冲突）
                                            $codeTarget.textbox("setValue", row.costCenter || '');
                                            // 正确设置readonly的方式（通过options）
                                            $codeTarget.textbox('options').readonly = true;
                                            // 刷新组件使只读生效
                                            // $codeTarget.textbox('refresh');
                                        }

                                        layer.close(index);
                                    },
                                    btn2: function (index) {
                                        layer.close(index);
                                    }
                                });
                            }
                        }]
                    }
                }
            },
            {field: 'stockPoint', title: '存放地点',width:'120', editor: 'text', hidden: true},
            {field: 'stockPointName', title: '存放地点',width:'150',
                editor: {
                    type: 'textbox',
                    options: {
                        required: true,
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                // 1. 记录当前编辑行索引
                                editor = el.tbEditIndex;
                                if (editor === undefined) {
                                    layer.alert('请先点击单元格进入编辑状态', {icon: 2});
                                    return;
                                }

                                // 2. 打开弹窗
                                var layerIndex = layer.open({
                                    title: "存放地点选择",
                                    type: 2,
                                    area: ['50%', '95%'],
                                    content: g.ctx + 'pc/sys/dict/selectDialog?dictType=stock_point',
                                    modal: true,
                                    btn: ['选择', '取消'],
                                    yes: function (index, layero) {
                                        // 获取iframe窗口对象
                                        var iframeWin = layero.find('iframe')[0].contentWindow;
                                        var grid = iframeWin.$('#tb');

                                        if (grid.length === 0) {
                                            layer.alert('未找到存放地点数据表格，请检查弹窗页面是否有id="tb"的表格', {icon: 2});
                                            return;
                                        }

                                        var rows = grid.datagrid('getChecked');
                                        if (rows.length !== 1) {
                                            layer.alert('请选中且仅选中一条存放地点数据', {icon: 2});
                                            return;
                                        }
                                        var row = rows[0];

                                        // 3. 回填名称（核心修复：先校验editor有效性）
                                        let nameEditor = $("#table_tb").edatagrid('getEditor', {
                                            index: editor,
                                            field: 'stockPointName'
                                        });
                                        if (nameEditor && nameEditor.target) {
                                            // 转为jQuery对象后操作
                                            $(nameEditor.target).textbox("setValue", row.name || '');
                                        }

                                        // 4. 回填编码（修复readonly报错核心逻辑）
                                        let codeEditor = $("#table_tb").edatagrid('getEditor', {
                                            index: editor,
                                            field: 'stockPoint'
                                        });
                                        if (codeEditor && codeEditor.target) {
                                            var $codeTarget = $(codeEditor.target);
                                            // 关键：先初始化textbox（如果未初始化）
                                            if (!$codeTarget.hasClass('textbox-f')) {
                                                $codeTarget.textbox(); // 手动初始化textbox组件
                                            }
                                            $codeTarget.textbox("setValue", row.code || '');
                                            // 正确设置readonly的方式（通过options）
                                            $codeTarget.textbox('options').readonly = true;

                                        }

                                        layer.close(index);
                                    },
                                    btn2: function (index) {
                                        layer.close(index);
                                    }
                                });
                            }
                        }]
                    }
                }
            },
            {
                field: 'customerCode',
                title: '客户编码',
                hidden: true,
                editor: 'text'
            },
            {
                field: 'customerName',
                title: '客户',
                width: 150,
                editor: {
                    type: 'textbox',
                    options: {
                        required: true,
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                // 1. 记录当前编辑行索引
                                editor = el.tbEditIndex;
                                if (editor === undefined) {
                                    layer.alert('请先点击单元格进入编辑状态', {icon: 2});
                                    return;
                                }

                                // 2. 打开弹窗
                                var layerIndex = layer.open({
                                    title: "客户选择",
                                    type: 2,
                                    area: ['50%', '95%'],
                                    content: g.ctx + 'pc/supplier/customer/page/select',
                                    modal: true,
                                    btn: ['选择', '取消'],
                                    yes: function (index, layero) {
                                        // 获取iframe窗口对象
                                        var iframeWin = layero.find('iframe')[0].contentWindow;
                                        var grid = iframeWin.$('#tb');

                                        if (grid.length === 0) {
                                            layer.alert('未找到客户数据表格，请检查弹窗页面是否有id="tb"的表格', {icon: 2});
                                            return;
                                        }

                                        var rows = grid.datagrid('getChecked');
                                        if (rows.length !== 1) {
                                            layer.alert('请选中且仅选中一条客户数据', {icon: 2});
                                            return;
                                        }
                                        var row = rows[0];

                                        // 3. 回填客户名称（核心修复：先校验editor有效性）
                                        let nameEditor = $("#table_tb").edatagrid('getEditor', {
                                            index: editor,
                                            field: 'customerName'
                                        });
                                        if (nameEditor && nameEditor.target) {
                                            // 转为jQuery对象后操作
                                            $(nameEditor.target).textbox("setValue", row.customerName1 || '');
                                        }

                                        // 4. 回填成本中心编码（修复readonly报错核心逻辑）
                                        let codeEditor = $("#table_tb").edatagrid('getEditor', {
                                            index: editor,
                                            field: 'customerCode'
                                        });
                                        if (codeEditor && codeEditor.target) {
                                            var $codeTarget = $(codeEditor.target);
                                            // 关键：先初始化textbox（如果未初始化）
                                            if (!$codeTarget.hasClass('textbox-f')) {
                                                $codeTarget.textbox(); // 手动初始化textbox组件
                                            }
                                            // 先赋值，再设置只读（分开操作避免冲突）
                                            $codeTarget.textbox("setValue", row.customerCode || '');
                                            // 正确设置readonly的方式（通过options）
                                            $codeTarget.textbox('options').readonly = true;
                                            // 刷新组件使只读生效
                                            //  $codeTarget.textbox('refresh');
                                        }

                                        layer.close(index);
                                    },
                                    btn2: function (index) {
                                        layer.close(index);
                                    }
                                });
                            }
                        }]
                    }
                }
            },

            {field: 'deliveryDate', title: '交货日期',width:'100',
                formatter: function (value) {
                    if (!value) return;
                    return moment(new Date(value)).format('YYYY-MM-DD');
                },
                editor: {
                    type: 'datebox',
                    options: {format: 'yyyy-mm-dd'}
                }},

            {field: 'currencyCode', title: '币别',width:'120',hidden:true},
            {field: 'factoryCode', title: '工厂编码<button type="button" onclick="copy(\'factoryCode\')" class="easyui-linkbutton">复制</button>',width:'120',hidden:true},

        ]] ,
        //开启编辑
        onClickCell: onClickCell,
        onLoadSuccess: function () {
            var $table = $(el.table_tb);   // 关键修复：补上 $table（datagrid 对象）
            // 默认隐藏的列，必填设置为空
            const moldColumns = ['projectProcess', 'modelApply', 'modelType', 'modelNumber'];

            // 隐藏模具相关列
            moldColumns.forEach(function(field) {
                setColumnRequired($(el.table_tb), field, false, el.tbEditIndex);
            });
            setColumnRequired($table, 'customerName', false, el.tbEditIndex);
            $table.datagrid('refreshRow', el.tbEditIndex);
            bindEndEditOnBlank(el.table_tb);
            loadFooter(el.table_tb);
        }
    });

    // 加载付款阶段数据（table_pay）- 补充可编辑配置
    $("#table_pay").datagrid({
        iconCls: 'icon-list',
        url: '/pc/contract/mroManage/rest/selectPayListPage?conId='+$("#id").val(),
        height: 350,
        fitColumns:true,
        singleSelect: false,
        showFooter: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        // 核心：开启单元格编辑模式
        editable: true,
        editMode: 'cell',
        toolbar: [
            {
                text: '新增',
                id: 'btn_add',
                iconCls: 'icon-add',
                handler: function () {
                    addPay();
                }
            },
            {
                text: '删除',
                id: 'btn_order',
                iconCls: 'icon-remove',
                handler: function (d) {
                    delPay();
                }
            },
        ],
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {field: 'paymentStage', title: '付款笔数',width:'120',
                exportEnum:getDictList('payment_stage'),
                formatter: function (value) { return getDicName('payment_stage',value); },
                // 补充：下拉框编辑器
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'name',
                        data: getDictList('payment_stage'),
                        editable: false,
                        required: true
                    }
                }
            },
            {field: 'paymentPeriod', title: '付款阶段',width:'120',
                exportEnum:getDictList('payment_period'),
                formatter: function (value) { return getDicName('payment_period',value); },
                // 补充：下拉框编辑器
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'name',
                        data: getDictList('payment_period'),
                        editable: false,
                        required: true
                    }
                }
            },
            {
                field: 'paymentRequirement',
                title: '付款前提条件 <a href="javascript:void(0)" class="help-icon" data-help="paymentRequirement">?</a>',
                width: '220',
                editor: {
                    type: 'textbox',
                    options: {min: 0, precision: 2, required: true},
                }
            },
            {field: 'paymentWay', title: '付款方式',width:'120',
                exportEnum:getDictList('payment_way'),
                formatter: function (value) { return getDicName('payment_way',value); },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'code',
                        textField: 'name',
                        data: getDictList('payment_way'),
                        editable: false,
                        required: true
                    }
                }
            },
            {field: 'paymentTime', title: '付款日期',width:'120',
                formatter: function (value) {
                    if (!value) return;
                    return moment(new Date(value)).format('YYYY-MM-DD');
                },
                editor: {
                    type: 'datebox',
                    options: {format: 'yyyy-mm-dd', required: true}
                }
            },
            {field: 'paymentRatio', title: '付款比例',width:'120',
                editor: {
                    type: 'numberbox',
                    options: {
                        min: 0,
                        max: 1,
                        precision: 4,
                        onChange: paymentRatioChange
                    }
                }
            },
            {field: 'paymentAmount', title: '付款金额',width:'120', editor: {
                    type: 'numberbox',
                    options: {min: 0, precision: 2, required: true}
                }},
            {field: 'remark', title: '备注',width:'220', editor: 'text'}
        ]] ,
        //开启编辑
        onClickCell: onClickCellPay,
        onLoadSuccess: function () {
            bindHelpIconTips(el.table_pay);
            bindEndEditOnBlank(el.table_pay);
            loadPayFooter(el.table_pay);
        }
    });
}

function copy(type) {
    const allRows = $('#table_tb').datagrid('getRows');
    if (allRows.length === 0) return;

    const firstValue = allRows[0][type];
    allRows.forEach((row, index) => {
        if (index > 0) {  // 跳过第一行
            $('#table_tb').datagrid('updateRow', {
                index: index,
                row: { [type]: firstValue }
            });
        }
    });
}

function syncAllEditorsToRows() {
    var $dg = $('#table_tb');
    var rows = $dg.datagrid('getRows');
    for (var i = 0; i < rows.length; i++) {
        // 获取该行所有编辑器
        var editors = $dg.datagrid('getEditors', i);
        editors.forEach(function(ed) {
            if (ed && ed.target) {
                var val;
                if ($(ed.target).hasClass('textbox-f')) {
                    val = $(ed.target).textbox('getValue');
                } else if ($(ed.target).hasClass('combo-f')) {
                    val = $(ed.target).combobox('getValue');
                } else if ($(ed.target).hasClass('datebox-f')) {
                    val = $(ed.target).datebox('getValue');
                } else if ($(ed.target).hasClass('numberbox-f')) {
                    val = $(ed.target).numberbox('getValue');
                } else {
                    val = $(ed.target).val();
                }
                // 更新行数据
                rows[i][ed.field] = val;
            }
        });
    }
}
function submitContractForm(type,call){
    syncAllEditorsToRows();

    // 表头必填校验
    if (!$("#form").form('validate')) {
        const invalidField  = getInvalidFields("#form");
        if (invalidField && invalidField.length > 0) {
            topWin.layer.alert("请填写以下必填字段：<br>" + invalidField.join("<br>"), {icon: 2});
            return;
        }
    }
    const attachData1 = $("#contractFiles").attr('data-fileIds')
    if(!attachData1){
        topWin.layer.alert('请上传合同附件!', {icon: 0});
        return false;
    }

    if (!validateRequiredFields()) {
        return; // 校验失败，停止保存
    }
    //需要检验合同文件必填
    //files
    let isMro = $("#isMro").combobox('getValue');
    let b ;
    let rows = $('#table_pay').datagrid('getRows');
    let rowsTableTb = $('#table_tb').datagrid('getRows');
    let totalAmoutnt = 0;
    if(rowsTableTb && rowsTableTb.length>0) {
        for (var i = 0; i < rowsTableTb.length; i++) {
            totalAmoutnt = totalAmoutnt + parseFloat(rowsTableTb[i].price * rowsTableTb[i].num);
        }
        $("#contractAmount").textbox('setValue', formatMoney(totalAmoutnt));
        $('#contractAmountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
    }

    // 1. 序列化表单
    let formData = $("#form").serializeJson();

    let selectedText = $("#contractCurrency").combobox('getText');
    let data = $("#contractCurrency").combobox('getData');
    let selectedItem = data.find(item => item.name === selectedText);
    let contractCurrencyCode = selectedItem ? selectedItem.code : '';

    formData.contractCurrency = contractCurrencyCode;
    // ==============================================================
    // 明细表单校验
    if (!endEditing(el.table_tb, el.tbEditIndex)){
        topWin.layer.alert("采购明细，请输入必填项！");
        return false;
    }
    if (!endEditing(el.table_pay, el.payEditIndex)){
        topWin.layer.alert("付款阶段，请输入必填项！");
        return false;
    }
    //新增判断如果mro合同，则校验两个明细表都要必填，非mro合同时合同数据必填
    if(isMro === "1"){
        if (!validatePayProgress()) {
            return; // 校验失败，阻止提交
        }
        if (rowsTableTb.length === 0) {
            topWin.layer.msg("明细数据展示列表不能为空！");
            return false;
        }
        if (rows.length === 0 ) {
            topWin.layer.msg("合同缺少付款阶段，请维护付款阶段！");
            return false;
        }
        // 新增的付款比例校验逻辑
        let hasPaymentRatio = false;
        rows.forEach(function(v) {
            if (v.paymentRatio && v.paymentRatio !== '') {
                hasPaymentRatio = true;
            }
        });

        if (hasPaymentRatio) {
            // 检查所有付款比例是否都填写了
            for (var i = 0; i < rows.length; i++) {
                if (!rows[i].paymentRatio || rows[i].paymentRatio === '') {
                    topWin.layer.alert("付款比例不能部分填写，请全部填写或全部不填写", {icon:2});
                    return false;
                }
            }

            // 检查总和是否为1
            let bl = 0;
            for (var i = 0; i < rows.length; i++) {
                bl += parseFloat(rows[i].paymentRatio);
            }
            if (parseFloat(bl.toFixed(2)) > 1 || parseFloat(bl.toFixed(2)) < 1) {
                topWin.layer.alert("付款比例总和不为1", {icon:2});
                return false;
            }
        }else {
            // ===== 优化点：比例未填写时校验金额总和 =====
            // 1. 先确保合同总金额已设置
            let contractAmount = parseFloat($("#contractAmount").textbox('getValue').replace(/,/g, ''));

            // 2. 计算付款阶段金额总和
            let paymentAmountTotal = 0;
            for (var i = 0; i < rows.length; i++) {
                paymentAmountTotal += parseFloat(rows[i].paymentAmount || 0);
            }

            // 3. 校验金额总和是否等于合同总金额（允许0.01误差）
            if (Math.abs(paymentAmountTotal - contractAmount) > 0.01) {
                topWin.layer.alert("付款阶段金额总和必须等于合同总金额（当前合同金额: " + contractAmount.toFixed(2) + "）", {icon: 2});
                return false;
            }
        }
        setMroTotalContractAmount();
    }

    formData.contractState = type ;

    formData.contractFiles = attachData1;
    var attachData2 = $("#contractSignFiels").attr('data-fileIds')
    formData.contractSignFiels = attachData2
    formData.contractAmount = Number($("#contractAmount").textbox('getValue').replace(/,/g,''));
    const saveData = {
        form: formData,
        contractDetailList: rowsTableTb,
        payStageDetailList: rows
    };
    if ($("#form").form('validate')) {
        const loading = topWin.layer.msg('数据处理中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: '/pc/contract/mroManage/rest/form/saveMro',
            type: 'POST',
            data: JSON.stringify(saveData),
            contentType: 'application/json',
            success: function (res) {
                topWin.layer.close(loading);
                topWin.layer.alert("保存成功!", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    call()
                });
            },
            error: function (res) {
                topWin.layer.close(loading);
                topWin.layer.alert(res.responseJSON.message, {icon: 2});
            }
        });
    }
    return b ;
}

// 检查并设置合同拟定方
function checkAndSetContractDraft(typeRecord) {
    if (!typeRecord) return;
    var typeCode = typeRecord.code;
    // 判断是否是"模具"类型
    if (typeCode === '03') {
        // 自动设置为甲方
        $('#contractDraft').combobox('setValue', '01');
    } else {
    }
}
/**
 * 提交前校验付款阶段是否合法
 * @returns {boolean} true=通过，false=不通过
 */
function validatePayProgress() {
    const contractType = $('#contractType').combobox('getValue');
    const payRows = $('#table_pay').datagrid('getRows');

    // 如果当前合同类型本身就是 01/02，直接放行（无需逐行检查关联合同）
    if (['01', '02'].includes(contractType)) {
        return true;
    }

    // 如果是 07 类型，或其它类型，需要逐行检查
    for (const row of payRows) {
        if (row.paymentPeriod === '02') { // 是进度款
            if (contractType === '07') {
                // 检查关联合同类型
                if (['01', '02'].includes(type)) {
                    continue; // 合法，继续下一行
                }
            }
            // 不满足任何允许条件
            topWin.layer.alert("合同类型是资产-设备或资产-软件才允许选进度款！", { icon: 2 });
            return false;
        }
    }

    return true; // 所有行都合法
}
