var el = {
    table_tb: '#table_tb',
    table_pay: '#table_pay',
    subjectCode: '#subjectCode',
    paymentStage: '#paymentStage',
    paymentWay:'#paymentWay',
    contractCurrency: '#contractCurrency',
    changeTypeEl: "#changeTypeEl",
    checkbox_detail: "#checkbox_detail",
    checkbox_right: '#checkbox_right',
    contractCode: '#contractCode',
    editIndex: undefined,
    tbEditIndex: undefined,
    payEditIndex: undefined,
    purchaseDialog: null,
    detailTableToolIds: ['#btn_add_tb', '#btn_del', '#btn-data-in'],
    paymentTableToolIds: ['#btn_add_pay', '#btn_order']

}
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');
    initEvent();
    syncCheckboxGroupStatus();

    initColumns();

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

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 () {
            if (optType === 1) {
                $("#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;
                    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 () {
            if (optType === 0) {
                $("#contractSealType").combobox('select',1);
            }
        }
    });

    $('#contractSignOrder').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('sign_order'), onLoadSuccess: function () {
            if (optType === 0) {
                $("#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);
                }
            }

            toggleMoldColumns(res);
        },

    });

    $('#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});
            }

        }
    });

    $('#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;
                     type = $(layero).find("iframe")[0].contentWindow.document.getElementById("type").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: (optType === 2 || optType === 4) ? null : '/pc/contract/mroManage/rest/selectContractDetailListPage?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_tb',
                    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: true,
                            editable: false,
                            icons: [{
                                iconCls: 'icon-search',
                                handler: function () {

                                    const contractType = $('#contractType').combobox('getValue');
                                    const contractCompanyName = $('#contractCompanyName').textbox('getValue');
                                    const contractSupplierName = $('#contractSupplierName').textbox('getValue');
                                    var contractCompanyCode = $("#contractCompanyCode").val();
                                    var contractSupplierCode = $("#contractSupplierCode").val();

                                    if (!contractType) {
                                        layer.alert('请先选择【合同类型】！', { icon: 2 });
                                        return;
                                    }
                                    if (!contractCompanyName) {
                                        layer.alert('请先选择【甲方】！', { icon: 2 });
                                        return;
                                    }
                                    if (!contractSupplierName) {
                                        layer.alert('请先选择【乙方】！', { icon: 2 });
                                        return;
                                    }
                                    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' +
                                        '&&contractType='+contractType+'&&contractCompanyCode='+contractCompanyCode+'&&contractSupplierCode='+contractSupplierCode, {
                                        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.enablePurchaseNum = updateRow.enablePurchaseNum;
                                                        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: {
                        type: 'textbox',
                        options: {
                            required: true
                        }
                    }
                },
                {
                    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: 200,
                    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;
                                    }
                                    var contractCompanyCode = $("#contractCompanyCode").val();
                                    if(contractCompanyCode == ""){
                                        layer.alert('请先选择甲方信息！', {icon: 2});
                                        return;
                                    }
                                    // 2. 打开弹窗
                                    var layerIndex = layer.open({
                                        title: "成本中心选择",
                                        type: 2,
                                        area: ['50%', '95%'],
                                        content: g.ctx + 'pc/mall/shoppingPay/page/select?contractCompanyCode='+contractCompanyCode,
                                        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];
                                            if(row.companyCode != contractCompanyCode){
                                                layer.alert('成本中心所属公司'+contractCompanyCode+'与合同甲方'+row.companyCode+'不一致，请确认！', {icon: 2});
                                                return;
                                            }
                                            // 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: (optType === 3 || optType === 4) ? null : onClickCell,
            onLoadSuccess: function () {
                if (optType === 1 || optType === 2 || optType === 3 || optType === 4) { // 查看、编辑、发起变更、发起终止展示模具相关列
                    var currentType = $('#contractType').combobox('getValue');
                    toggleMoldColumns(currentType);
                }

                bindEndEditOnBlank(el.table_tb);
                loadFooter(el.table_tb);
            }
        });

        // 加载付款阶段数据（table_pay）- 补充可编辑配置
        $("#table_pay").datagrid({
            iconCls: 'icon-list',
            url: (optType === 2 || optType === 4) ? null : '/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_pay',
                    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}
                    },
                    formatter: function (value) {
                        return formatMoney(value);
                    }
                },
                {field: 'remark', title: '备注',width:'220', editor: 'text'}
            ]],
            //开启编辑
            onClickCell: (optType === 3 || optType === 4) ? null : 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;
    }

    // 不校验标记
    // 场景1：发起变更，责权变更
    const doNotCheckFlag = ((optType === 1 || optType === 2) && $(el.checkbox_right).prop('checked')
                            && !$(el.checkbox_detail).prop('checked'));
    if (!doNotCheckFlag && !validateRequiredFields()) {
        return; // 校验失败，停止保存
    }
    //需要检验合同文件必填
    //files
    let isMro = $("#isMro").combobox('getValue');
    let b ;
    let rows = $('#table_pay').datagrid('getRows');
    let rowsTableTb = $('#table_tb').datagrid('getRows');
    if (!doNotCheckFlag && rowsTableTb && rowsTableTb.length === 0) {
        layer.msg("采购明细数据不能为空！");
        return false;
    }
    if (!doNotCheckFlag && rows  && rows.length === 0) {
        layer.msg("付款阶段数据不能为空！");
        return false;
    }
    if (type === 2) {
        // 终止合同
        rows.forEach(row => {
            row.id = null;
            row.contractId = null;
            row.contractCode = null;
        });
        rowsTableTb.forEach(row => {
            row.id = null;
            row.contractId = null;
            row.contractCode = null;
        });
    }
    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)));
    }


    const detailRows = $('#table_tb').datagrid('getRows');
    for (let i = 0; i < detailRows.length; i++) {
        const row = detailRows[i];
        const num = parseFloat(row.num) || 0;
        const enablePurchaseNum = parseFloat(row.enablePurchaseNum) || 0;
        const purchaseCode = row.purchaseCode || '未知';
        const itemCode = row.itemCode || '未知';
        const rowIndex = i + 1; // 行号从1开始

        // 如果数量大于可用数量，且可用数量不为0（避免可用数量为0时误报）
        if (enablePurchaseNum >= 0 && num > enablePurchaseNum) {
            layer.msg(`资产申请单${purchaseCode}行号${itemCode}，数量超过资产请购可用数量，请确认！`, { icon: 2 });
            return false; // 阻止提交
        }
    }
    // 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 (!doNotCheckFlag && !endEditing(el.table_tb, el.tbEditIndex)){
        topWin.layer.alert("采购明细，请输入必填项！");
        return false;
    }
    if (!doNotCheckFlag && !endEditing(el.table_pay, el.payEditIndex)){
        topWin.layer.alert("付款阶段，请输入必填项！");
        return false;
    }
    //新增判断如果mro合同，则校验两个明细表都要必填，非mro合同时合同数据必填
    if (!doNotCheckFlag) {
        if (isMro === "1") {

            if (!validatePayProgress()) {
                return; // 校验失败，阻止提交
            }

            //权则变更 无需校验
            //采购明细变更勾选 校验采购明细必须有数据
            var isCheckedDetail = $(el.checkbox_detail).prop('checked');
            if (isCheckedDetail) {
                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++) {
                    var val = rows[i].paymentAmount;
                    var num = parseFloat(val);
                    paymentAmountTotal += isNaN(num) ? 0 : num;
                }

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

    if (type === 2) {
        formData.contractState = 1;
    } else {
        // 驳回合同保存不需要更新状态
        if (formData.contractState !== "4" && formData.contractState !== "8") {
            formData.contractState = type;
        }
    }

    formData.contractFiles = attachData1;
    var attachData2 = $("#contractSignFiels").attr('data-fileIds')
    formData.contractSignFiels = attachData2
    formData.contractAmount = Number($("#contractAmount").textbox('getValue').replace(/,/g,''));
    formData.changeType = getChangeTypeSaveValue();
    const saveData = {
        form: formData,
        contractDetailList: rowsTableTb,
        payStageDetailList: rows,
        isTerminated: type === 2? "1" : null,
    };
    // 此处后续代码不变
    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);
                if (res) {
                    topWin.layer.alert("合同终止成功，但提交共享失败!", {icon: 0}, function (idx) {
                        topWin.layer.close(idx);
                        call()
                    });
                } else {
                    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 {
    }
    if (optType === 0) {
        if (typeCode === '07') {
            controlChangeTypeDisplay(true);
            $(el.checkbox_detail).off('click');
            $(el.checkbox_right).off('click');
        } else {
            controlChangeTypeDisplay(false);
        }
    }
}

/**
 * 初始化变更类型
 */
function initChangeType() {
    controlChangeTypeDisplay(true);
    if (optType === 0) {
        // 新建
        controlChangeTypeDisplay(false);
    } else if (optType === 1) {
        // 编辑
        setChangeTypeCheckbox(changeType);
        if ($(el.checkbox_right).prop('checked')) {
            // 责权变更的情况不能修改明细
            el.detailTableToolIds.forEach(id => {
                $(id).linkbutton('disable');
            })
            el.paymentTableToolIds.forEach(id => {
                $(id).linkbutton('disable');
            })
        }
    } else if (optType === 2) {
        // 变更
        setTimeout(function () {
            const parentData = window.parentData;
            setChangeTypeCheckbox(parentData.checkbox || "", true);
            $(el.table_tb).datagrid('loadData', parentData.purchaseDetail || []);
            $(el.table_pay).datagrid('loadData', parentData.paymentDetail || []);
            if ($(el.checkbox_right).prop('checked')) {
                // 责权变更的情况不能修改明细
                el.detailTableToolIds.forEach(id => {
                    $(id).linkbutton('disable');
                })
                el.paymentTableToolIds.forEach(id => {
                    $(id).linkbutton('disable');
                })
                $("#contractAmount").textbox('setValue', formatMoney(0));
                $('#contractAmountCapital').textbox('setValue', number_chinese(0));
            }
        });
    } else if (optType === 3) {
        // 查看
        setChangeTypeCheckbox(changeType);
        el.detailTableToolIds.forEach(id => {
            $(id).linkbutton('disable');
        })
        el.paymentTableToolIds.forEach(id => {
            $(id).linkbutton('disable');
        })
    } else if (optType === 4) {
        // 终止
        setTimeout(function () {
            const row = window.parentData;
            controlChangeTypeDisplay(false);
            const detailUrl = '/pc/contract/mroManage/rest/selectContractDetailListPage?conId=' + row.id;
            const payUrl = '/pc/contract/mroManage/rest/selectPayListPage?conId=' + row.id;
            $(el.table_tb).datagrid('options').url = detailUrl;
            $(el.table_tb).datagrid('reload');
            $(el.table_pay).datagrid('options').url = payUrl;
            $(el.table_pay).datagrid('reload');
            el.detailTableToolIds.forEach(id => {
                $(id).linkbutton('disable');
            })
            el.paymentTableToolIds.forEach(id => {
                $(id).linkbutton('disable');
            })
        });
    }
}

/**
 * 获取变更类型报错值
 * @returns {string}
 */
function getChangeTypeSaveValue() {
    const changeTypes = [];

    if ($(el.checkbox_detail).prop('checked')) {
        changeTypes.push('01');
    }
    if ($(el.checkbox_right).prop('checked')) {
        changeTypes.push('03');
    }

    return changeTypes.join(',');
}

/**
 * 控制变更类型显示
 * @param display
 */
function controlChangeTypeDisplay(display) {
    const changeTypeEl = document.getElementById('changeTypeEl');
    // 根据条件isSup的值来设置显示与隐藏
    if (display) {
        changeTypeEl.style.display = 'contents';
    }else {
        changeTypeEl.style.display = 'none';
    }
}

/**
 * 控制变更类型输入框可否编辑和显示
 * @param changeType
 */
function setChangeTypeCheckbox(changeType) {
    // 先清空状态
    $(el.checkbox_detail).prop('checked', false);
    $(el.checkbox_right).prop('checked', false);

    // 回显 changeType
    if (changeType) {
        const types = changeType.split(',');
        types.forEach(function (type) {
            if (type === '01') {
                $(el.checkbox_detail).prop('checked', true);
            }
            if (type === '03') {
                $(el.checkbox_right).prop('checked', true);
            }
        });
        $(el.checkbox_detail).on('click', function (e) {
            e.preventDefault();
        });
        $(el.checkbox_right).on('click', function (e) {
            e.preventDefault();
        });
    } else {
        controlChangeTypeDisplay(false);
    }
}

/**
 * 提交前校验付款阶段是否合法
 * @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; // 所有行都合法
}

// 提取模具列显示/隐藏逻辑为可复用函数
function toggleMoldColumns(contractTypeValue) {
    var isMoldContract = (contractTypeValue === '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');
}

/**
 * 初始化事件
 */
function initEvent() {
    $(el.checkbox_detail).on('change', function () {
        syncCheckboxGroupStatus();
    });

    $(el.checkbox_right).on('change', function () {
        syncCheckboxGroupStatus();
    });
}

/**
 * 同步勾选框状态
 */
function syncCheckboxGroupStatus() {
    const detailChecked = $(el.checkbox_detail).prop('checked');
    const rightChecked    = $(el.checkbox_right).prop('checked');

    // 勾选了 采购/付款 任意一个 → 禁用 权责
    if (detailChecked) {
        $(el.checkbox_right).prop('checked', false).prop('disabled', true);
    } else {
        $(el.checkbox_right).prop('disabled', false);
    }

    // 勾选了 权责 → 禁用 采购 + 付款
    if (rightChecked) {
        $(el.checkbox_detail).prop('checked', false).prop('disabled', true);
    } else {
        $(el.checkbox_detail).prop('disabled', false);
    }
}