
var el = {
    table_tb: '#table_tb',
    table_pay: '#table_pay',
    subjectCode: '#subjectCode',
    paymentStage: '#paymentStage',
    paymentWay:'#paymentWay',
    contractCurrency: '#contractCurrency',
    editIndex: undefined

}
const dictData = getDictList('contract_item_subject_sap');  // 添加 const

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

    initColumns();
    findTaxDictData();

    $('#btn_add').linkbutton('enable');
    loadGrid();
});
var taxDict = [];
function findTaxDictData() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                var obj = {};
                obj.id = data[i].id;
                obj.itemCode = data[i].taxCode;
                obj.itemName = data[i].taxName;
                obj.itemValue = data[i].taxValue;
                obj.itemRemark = data[i].taxName;
                taxDict.push(obj);
            }
        }
    });
}
function  initColumns(d) {

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

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


    //发票类型
    $("#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 );
                    } else {
                        console.log("采购组为空");
                    }
                }
            })
        }
    });

    //付款方式
    $("#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 () {
            $("#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'),
        onSelect: function(record) {
            // 当选择合同类型时检查
            checkAndSetContractDraft(record);
        },
        // onLoadSuccess: function() {
        //     // 设置默认选中项
        //     $("#contractType").combobox('select', 1);
        //     // 初始化时检查
        //     var selected = $(this).combobox('getSelected');
        //     if (selected) {
        //         checkAndSetContractDraft(selected);
        //     }
        //
        //     // 延迟检查，确保combobox已完全加载
        //     setTimeout(function() {
        //         var selected = $('#contractType').combobox('getSelected');
        //         if (selected) {
        //             checkAndSetContractDraft(selected);
        //         }
        //     }, 100);
        // },
        onChange:function (res) {
            debugger;
            if(res=== '07' ) {
                //关联合同
                $("#associationContract").textbox({required: true});
            }else{
                $("#associationContract").textbox({required: false});
            }

            if (res) {
                var data = $(this).combobox('getData');
                var selected = data.find(function(item) {
                    return item.name === res || item.code === res;
                });
                if (selected) {
                    checkAndSetContractDraft(selected);
                }
            }
        },
        // onChange: function(newValue, oldValue) {
        //     // 处理手动输入或程序设置值的情况
        //     if (newValue) {
        //         var data = $(this).combobox('getData');
        //         var selected = data.find(function(item) {
        //             return item.name === newValue || item.code === newValue;
        //         });
        //         if (selected) {
        //             checkAssociationContractRequiredByType(selected);
        //         }
        //     }
        // },
        // onLoadSuccess: function() {
        //     // 初始化时检查
        //     var selected = $(this).combobox('getSelected');
        //     if (selected) {
        //         checkAssociationContractRequiredByType(selected);
        //     }
        //
        //     // 如果有默认选中值，也检查
        //     $("#contractType").combobox('select', 1);
        //
        //     // 延迟检查，确保combobox已完全加载
        //     setTimeout(function() {
        //         var selected = $('#contractType').combobox('getSelected');
        //         if (selected) {
        //             checkAssociationContractRequiredByType(selected);
        //         }
        //     }, 100);
        // }
    });



    $('#contractDraft').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":"1","name":"甲方"},
            {"code":"2","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
                $("#mroDisplay").text('MRO数据展示');
                loadGrid();
                //订单类型
                $("#contractOrderType").textbox({required:true});
                //关联合同
                $("#associationContract").textbox({required:false});
                //货币编码
                $("#contractCurrency").textbox({required:true});

                $("#contractAmountCapital").textbox({required:true});

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

                $("#contractAmountCapital").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(),
        height: 350,
        fitColumns:true,
        singleSelect: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        // 核心：开启单元格编辑模式
        editable: true, // 必须开启
        editMode: 'cell', // 单元格编辑模式（而非行编辑）
        columns: [[
            {field: 'purchaseCode', title: '资产申请单号',width:'100',
                editor: 'text' },
            {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
                    }
                }
            },
            {
                field: 'applyProjectType',
                title: '申请样品制作项目类型',
                width: 100,
                hidden: true, // 默认隐藏
                formatter: function (value) {
                    if (value === "01") return "板金件";
                    else if (value === "02") return "散热件";
                    else if (value === "03") return "塑胶件";
                    else return "其他";
                }
            },
            {
                field: 'modelApply',
                title: '模具申请',
                width: 150,
                hidden: true,
                formatter: function (value) {
                    if (value === "01") return "手板";
                    else if (value === "02") return "开模";
                    else if (value === "03") return "修模";
                }
            },
            {field: 'projectProcess', title: '项目所处阶段',width:'120',
                hidden: true,
                editor: 'text'
            },
            {
                field: 'modelType',
                title: '模具类型',
                width: 120,
                hidden: true,
                formatter: function (value) {
                    if (value === "01") return "（01）冲压";
                    else if (value === "02") return "（02）压铸";
                    else if (value === "03") return "（03）铸塑";
                    else if (value === "04") return "（04）组件模具";
                    else return "";
                }
            },
            {
                field: 'modelNumber',
                title: '模具编号',
                width: 120,
                hidden: true
            },
            {field: 'materialName', title: '物品名称',width:'120',
                editor: 'text'
            },
            {field: 'materialSpec', title: '型号规格/参数',width:'120',
                editor: 'text'
            },
            {field: 'materialBrand', title: '品牌',width:'80',
                editor: 'text' },
            {field: 'num', title: '数量',width:'60',
                editor: {
                    type: 'numberbox',
                    options: {min: 0, precision: 0}
                }
            },
            {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
                    }
                }
            },
            {
                field: 'taxRateCode',
                title: '税率',
                width: 150,
                formatter: function (value) {
                    if (value){
                        for(var j = 0; j < taxDict.length; j++){
                            if(taxDict[j].itemCode === value){
                                return taxDict[j].itemRemark;
                            }
                        }
                    }
                    return '';
                },
                editor: {
                    type: 'combobox',
                    options: {
                        valueField: 'itemCode',
                        textField: 'itemRemark',
                        data: taxDict,
                        panelHeight: 200,
                        // onChange: function (nv, ov) {
                        //     if(ov && nv !== ov){
                        //         updateRowData(nv, 'taxRate');
                        //     }
                        // }
                    }
                }
            },

            {field: 'price', title: '含税单价',width:'120 ',
                editor: {
                    type: 'numberbox',
                    options: {min: 0, precision: 2}
                }
            },
            {field: 'noTaxPrice', title: '未税单价',width:'120 ' ,
                editor: {
                    type: 'numberbox',
                    options: {min: 0, precision: 2}
                }},
            {field: 'amount', title: '含税金额',width:'120',
                formatter: function (value, row) {
                    if (row.price !=null && row.num) {
                        return (parseFloat(row.price) * parseFloat(row.num)).toFixed(2);
                    }
                }
            },
            {field: 'useDeptName', title: '使用部门名称',width:'120',
                editor: 'text'},
            {field: 'useDeptCode', title: '使用部门编码',width:'120',
                editor: 'text', hidden: true},
            {field: 'userName', title: '使用人名称',width:'100',
                editor: 'text'},
            {field: 'userCode', title: '使用人工号',width:'100',
                editor: 'text', hidden: true},
            {
                field: 'costCenterName',
                title: '成本中心',
                width: 150,
                editor: {
                    type: 'combobox',
                    options: {
                        url: g.ctx + 'pc/mall/shoppingPay/rest/costCenterListAll',
                        valueField: 'costCenter',
                        textField: 'describe',
                        limitToList: 'false',
                        prompt: '-- 请选择 --',
                        method: 'GET',
                        editable: true,
                        panelHeight: 150,
                        onChange: function(newValue, oldValue) {
                            // 输入为空时加载全部数据
                            if (!newValue) {
                                $(this).combobox('reload', g.ctx + 'pc/mall/shoppingPay/rest/costCenterListAll');
                                return;
                            }
                        },
                        // 关键2：本地过滤（若后端不支持远程搜索，仅前端过滤）
                        filter: function(q, row) {
                            var opts = $(this).combobox('options');
                            // 模糊匹配文本字段（customerName1）
                            return row[opts.textField].toLowerCase().indexOf(q.toLowerCase()) >= 0;
                        }
                    }
                }
            },
            // {
            //     field: 'costCenterName', title: '成本中心', width: '10%', align: 'center', editor: {
            //         type: 'combobox', options: {
            //             limitToList: true,
            //             valueField: 'costCenter',
            //             textField: 'describe',
            //             panelHeight: 'auto',
            //             required: true,
            //             editable: false,
            //             data: getNecessaryDataList(g.ctx + "pc/mall/shoppingPay/rest/costCenterList")
            //         }
            //     }
            // },
            // {field: 'costCenterName', title: '成本中心<button type="button" onclick="copy(\'costCenterName\')" class="easyui-linkbutton">复制</button>',width:'120'},
            {field: 'stockPoint', title: '存放地点',width:'120',
                editor: 'text' },
            // {field: 'mainUses', title: '资产用途',width:'120',
            //     editor: 'text' },
            {
                field: 'customerName',
                title: '服务客户',
                width: 170,
                editor: {
                    type: 'combobox',
                    options: {
                        url: g.ctx + 'pc/supplier/customer/rest/listAll',
                        valueField: 'customerCode',
                        textField: 'customerName1',
                        limitToList: 'false',
                        prompt: '-- 请选择 --',
                        method: 'GET',
                        editable: true,
                        panelHeight: 150,
                        onChange: function(newValue, oldValue) {
                            // 输入为空时加载全部数据
                            if (!newValue) {
                                $(this).combobox('reload', g.ctx + 'pc/supplier/customer/rest/listAll');
                                return;
                            }
                        },
                        // 关键2：本地过滤（若后端不支持远程搜索，仅前端过滤）
                        filter: function(q, row) {
                            var opts = $(this).combobox('options');
                            // 模糊匹配文本字段（customerName1）
                            return row[opts.textField].toLowerCase().indexOf(q.toLowerCase()) >= 0;
                        }
                    }
                }
            },
            // {
            //     field: 'customerName', title: '成本中心', width: '10%', align: 'center', editor: {
            //         type: 'combobox', options: {
            //             limitToList: true,
            //             valueField: 'customerCode',
            //             textField: 'customerName1',
            //             panelHeight: 'auto',
            //             required: true,
            //             editable: true,
            //             data: getNecessaryDataList("pc/supplier/customer/rest/list")
            //         }
            //     }
            // },
            // {field: 'customerName', title: '服务客户名称<button type="button" onclick="copy(\'customerName\')" class="easyui-linkbutton">复制</button>',width:'180'},
            // {field: 'customerCode', title: '服务客户代码<button type="button" onclick="copy(\'customerCode\')" class="easyui-linkbutton">复制</button>',width:'120',hidden:true},

            // {field: 'checkState', title: '验收状态',width:'100'},
            // {field: 'checkNo', title: '验收单号',width:'120'},
            {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: 'requireName', title: '请购人<button type="button" onclick="copy(\'requireName\')" class="easyui-linkbutton">复制</button>',width:'120'},
            // {field: 'factoryCode', title: '工厂编码<button type="button" onclick="copy(\'factoryCode\')" class="easyui-linkbutton">复制</button>',width:'120',hidden:true},
            // {field: 'factoryName', title: '工厂名称<button type="button" onclick="copy(\'factoryName\')" class="easyui-linkbutton">复制</button>',width:'220'},
            // {field: 'driverAsset', title: '驱动因素',width:'120',
            //     formatter: function (value, row) {
            //         return getDicName('contract_pay_boot_item',value)
            //
            //     }},
            // {field: 'cardNumber', title: '固定资产卡号',width:'120'},
            // {field: 'bz', title: '备注',width:'200'},

        ]] ,
        //开启编辑
        onClickCell: onClickCell,
    });

    // 加载付款阶段数据（table_pay）- 补充可编辑配置
    $("#table_pay").datagrid({
        iconCls: 'icon-list',
        url: '/pc/contract/mroManage/rest/selectPayListPage?conId='+$("#id").val(),
        height: 350,
        fitColumns:true,
        singleSelect: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        // 核心：开启单元格编辑模式
        editable: true,
        editMode: 'cell',
        columns: [[
            {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
                    }
                }
            },
            {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
                    }
                }
            },
            {field: 'paymentRequirement', title: '付款前提条件',width:'220', editor: 'text'},
            {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
                    }
                }
            },
            {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'}
                }
            },
            {field: 'paymentRatio', title: '付款比例',width:'120',
                editor: {
                    type: 'numberbox',
                    options: {min: 0, max: 1, precision: 4} // 比例 0-1
                }
            },
            {field: 'paymentAmount', title: '付款金额',width:'120', editor: {
                    type: 'numberbox',
                    options: {min: 0, precision: 2}
                }},
            {field: 'remark', title: '付款描述',width:'220', editor: 'text'}
        ]] ,
        //开启编辑
        onClickCell: onClickCellPay,
    });
}
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 submitContractForm(type,call){
    debugger;
    //需要检验合同文件必填
    //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', totalAmoutnt.toFixed(2));
        $('#contractAmountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
    }
    let formData = $("#form").serializeJson();
    endEditing();
    // endEditingPay();
    //新增判断如果mro合同，则校验两个明细表都要必填，非mro合同时合同数据必填
    if(isMro === "1"){//mro
        //table_tb  table_pay rowsTableTb rows明细对象

        if (rowsTableTb.length === 0) {
            // datagrid明细表为空
            console.log('table_tb为空');
            topWin.layer.msg("明细数据展示列表不能为空！");
            return false;
        }
        if (rows.length === 0 ) {
            // datagrid明细表为空
            console.log('table_pay为空');
            topWin.layer.msg("合同缺少付款阶段，请维护付款阶段！");
            return false;
        }
        let bl = 0;
        rows.forEach(function (v,n) {
            bl += parseFloat(v.paymentRatio);
        });
        console.log('paymentRatio',bl.toFixed(2));
        if(parseFloat(bl.toFixed(2))>1 || parseFloat(bl.toFixed(2))<1){
            topWin.layer.alert("付款比例总和不为1",{icon:2});
            return false;
        }
        setMroTotalContractAmount();
    }

    let dlist = JSON.stringify(rows);
    let rowsTableTblist = JSON.stringify(rowsTableTb);
    formData.contractState = type ;
    var attachData1 = $("#contractFiles").attr('data-fileIds')
    if(!attachData1){
        topWin.layer.alert('请上传合同附件!', {icon: 0});
        return false;
    }

    formData.contractFiles = attachData1;
    var attachData2 = $("#contractSignFiels").attr('data-fileIds')
    formData.contractSignFiels = attachData2
    formData.dlist = dlist;
    formData.rowsTableTblist = rowsTableTblist;
    formData.contractAmount = Number($("#contractAmount").textbox('getValue').replace(/,/g,''));
    if ($("#form").form('validate')) {
        $.ajax({
            url: '/pc/contract/mroManage/rest/form/save',
            type: 'POST',
            async: false,
            data: formData,
            success: function (res) {
                topWin.layer.alert("保存成功!", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    call()
                });
            },
            error: function (res) {
                topWin.layer.alert(res.responseJSON.message, {icon: 2});
            }
        });
    }
    return b ;
}


function addPay(){
    debugger;
    const rows = $(el.table_pay).datagrid('getRows');

    let defaultPaymentWay = '';
    const $paymentWay = $(el.paymentWay); // #paymentWay 的 jQuery 实例

    // 新增行（用兜底后的默认值）
    $(el.table_pay).datagrid('appendRow', {
        id: 0,
        paymentWay: defaultPaymentWay,
    });

    // 新增行后编辑（兼容低版本）
    const newIndex = rows.length;
    try {
        $(el.table_pay).datagrid('selectRow', newIndex).datagrid('editCell', {index: newIndex, field: 'paymentStage'});
    } catch (e) {
        $(el.table_pay).datagrid('beginEdit', newIndex);
        editIndex = newIndex;
    }

}

function addDetail(){
    debugger;
    var rows = $(el.table_tb).datagrid('getRows');

    let defaultSubjectCode = '';
    const subjectCode = $(el.subjectCode); // #subjectCode 的 jQuery 实例

    // 新增行（用兜底后的默认值）
    $(el.table_tb).datagrid('appendRow', {
        id: 0,
        subjectCode: defaultSubjectCode,
    });

    // 新增行后编辑（兼容低版本）
    const newIndex = rows.length;
    try {
        $(el.table_tb).datagrid('selectRow', newIndex).datagrid('editCell', {index: newIndex, field: 'paymentStage'});
    } catch (e) {
        $(el.table_tb).datagrid('beginEdit', newIndex);
        editIndex = newIndex;
    }
    // 修复：获取资产类别的选中值
    // const defaultSubjectCode = $(el.subjectCode).combobox('getValue') || '';
    // $(el.table_tb).datagrid('appendRow', {
    //     id: 0,
    //     subjectCode: defaultSubjectCode, // 修正：赋值选中值
    //     // num: 1, // 补充默认值
    //     // price: 0.00 // 补充默认值
    // });
    // // 新增行后自动编辑物品名称列
    // const newIndex = rows.length;
    // $(el.table_tb).datagrid('selectRow', newIndex).datagrid('editCell', {index: newIndex, field: 'materialName'});
}

function delPay() {

    let row = $("#table_pay").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    topWin.layer.confirm("是否删除", function (index) {
        var rowIndex = $("#table_pay").datagrid('getRowIndex', row);
        $("#table_pay").datagrid('deleteRow', rowIndex);
        var ds = $("#table_pay").datagrid('getRows');
        let je = 0;
        ds.forEach(function (v,n) {
            je = (je + v.paymentAmount );
            // v.paymentAlreadyAmount = je.toFixed(4) ;
            $("#table_pay").datagrid('updateRow',{index:n,row:ds[n]})
            $('#table_pay').datagrid('refreshRow',n);
        });
        topWin.layer.close(index);
    })
}

function delDetail() {
    let row = $("#table_tb").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    topWin.layer.confirm("是否删除", function (index) {
        var rowIndex = $("#table_tb").datagrid('getRowIndex', row);
        $("#table_tb").datagrid('deleteRow', rowIndex);
        setMroTotalContractAmount();
        topWin.layer.close(index);
    })
}

// function delDetailMro(){
//     let row = $("#table_mro").datagrid('getSelected');
//     if (!row) {
//         layer.msg("请选中一条记录");
//         return;
//     }
//     topWin.layer.confirm("是否删除", function (index) {
//         var rowIndex = $("#table_mro").datagrid('getRowIndex', row);
//         $("#table_mro").datagrid('deleteRow', rowIndex);
//         setTotalContractAmount();
//         topWin.layer.close(index);
//     })
// }
//设置非mro合同金额汇总
// function setTotalContractAmount(){
//     let rowsTableTb = $('#table_mro').datagrid('getRows');
//     let totalAmoutnt = 0;
//     if(rowsTableTb && rowsTableTb.length>0) {
//         for (var i = 0; i < rowsTableTb.length; i++) {
//             totalAmoutnt = totalAmoutnt + parseFloat(rowsTableTb[i].amount);
//         }
//         $("#contractAmount").textbox('setValue', totalAmoutnt.toFixed(2));
//         $('#contractAmountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
//         console.log("设置金额:" +　totalAmoutnt);
//
//     }
// }

//设置是mro合同总金额
function setMroTotalContractAmount(){
    let rowsTableTb = $('#table_tb').datagrid('getRows');
    console.log("设置mro合同金额明细行:" +　rowsTableTb.length);
    let totalAmoutnt = 0;
    if(rowsTableTb && rowsTableTb.length>0) {
        for (var i = 0; i < rowsTableTb.length; i++) {
            console.log("价格："+rowsTableTb[i].price + "数量："+rowsTableTb[i].num);
            totalAmoutnt = totalAmoutnt +  (parseFloat(rowsTableTb[i].price) * parseFloat(rowsTableTb[i].num));
            //    totalAmoutnt = totalAmoutnt + parseFloat(rowsTableTb[i].amount);
            console.log("明细金额："+totalAmoutnt);
        }
        let rows = $('#table_pay').datagrid('getRows');
        let je = new BigNumber(0);
        //付款阶段表
        if(rows && rows.length>0) {
            let bl = 0;
            rows.forEach(function (v,n) {
                bl += parseFloat(v.paymentRatio);
            });
            console.log('paymentRatio',bl.toFixed(2));
            if(parseFloat(bl.toFixed(2))>1 || parseFloat(bl.toFixed(2))<1){
                topWin.layer.alert("付款比例总和不为1",{icon:2});
                return false;
            }
            for (var i = 0; i < rows.length; i++) {
                rows[i].paymentAmount = new BigNumber(rows[i].paymentRatio).multipliedBy( new BigNumber(totalAmoutnt)).decimalPlaces(2,  BigNumber.ROUND_HALF_UP)   ;
                console.log('paymentAmount',rows[i].paymentAmount);
                if(i< rows.length-1){
                    je = je.plus(new BigNumber(rows[i].paymentAmount) );
                }
            }
            // 最后一行 = 总金额 - 前 N-1 项和
            rows[rows.length - 1].paymentAmount = new BigNumber(totalAmoutnt).minus(je)
                .decimalPlaces(2, BigNumber.ROUND_HALF_UP);
            console.log('总和totalAmoutnt',new BigNumber(totalAmoutnt));
            console.log('最后一行paymentAmount',rows[rows.length - 1].paymentAmount);

            rows.forEach(function (v,n) {
                $("#table_pay").datagrid('updateRow',{index:n,row:rows[n]})
                $('#table_pay').datagrid('refreshRow',n);
            });

        }
        $("#contractAmount").textbox('setValue', totalAmoutnt.toFixed(2));
        $('#contractAmountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
        console.log("设置是mro金额:" +　totalAmoutnt);

    }

}



let editIndex = undefined; // 统一用全局变量，删除 el.editIndex 混用
let lastEditTg = undefined;

function onClickCell(index, field, value) {
    debugger;
    // 步骤1：结束上一个单元格的编辑
    if (endEditing('#table_tb')) {
        var $dg = $('#table_tb');
        // 步骤2：校验 index/field 有效性
        var rows = $dg.datagrid('getRows');
        var columns = $dg.datagrid('getColumnFields');
        if (index < 0 || index >= rows.length || !columns.includes(field)) {
            console.error('无效的 index/field：', {index, field});
            return;
        }
        // 步骤3：调用 editCell（兼容低版本）
        try {
            $dg.datagrid('selectRow', index).datagrid('editCell', {index: index, field: field});
            editIndex = index;
            lastEditTg = $dg;
        } catch (e) {
            // 低版本兜底：用 beginEdit 行编辑模拟
            $dg.datagrid('beginEdit', index);
            // 聚焦编辑器
            var ed = $dg.datagrid('getEditor', {index: index, field: field});
            if (ed && ed.target) $(ed.target).focus();
            editIndex = index;
            lastEditTg = $dg;
        }
    }
}

function onClickCellPay(index, field) {
    debugger;
    if (endEditing('#table_pay')) {
        var $dg = $('#table_pay');
        var rows = $dg.datagrid('getRows');
        var columns = $dg.datagrid('getColumnFields');
        if (index < 0 || index >= rows.length || !columns.includes(field)) {
            console.error('无效的 index/field：', {index, field});
            return;
        }
        try {
            $dg.datagrid('selectRow', index).datagrid('editCell', {index: index, field: field});
            editIndex = index;
            lastEditTg = $dg;
        } catch (e) {
            $dg.datagrid('beginEdit', index);
            var ed = $dg.datagrid('getEditor', {index: index, field: field});
            if (ed && ed.target) $(ed.target).focus();
            editIndex = index;
            lastEditTg = $dg;
        }
    }
}
// function changeJe(d) {
//     var hs = 0.00;
//     d.forEach(function (v, n) {
//         let amount = v.amount;
//         hs = parseFloat(hs) + parseFloat(amount);
//     });
//     $("#payeeAmount").textbox('setValue', hs.toFixed(4));
//     $("#totalAmount").textbox('setValue', hs.toFixed(4));
// }

function endEditing(dgSelector) {
    debugger;
    if (editIndex === undefined) return true;
    var $dg = $(dgSelector || lastEditTg);
    if (!$dg.length) return true;

    // 校验并结束编辑
    try {
        if ($dg.datagrid('validateRow', editIndex)) {
            // 优先结束单元格编辑（高版本）
            if ($.fn.datagrid.methods.endEditCell) {
                $dg.datagrid('endEditCell', {index: editIndex});
            } else {
                // 低版本结束行编辑
                $dg.datagrid('endEdit', editIndex);
            }
            editIndex = undefined;
            lastEditTg = undefined;
            return true;
        } else {
            return false;
        }
    } catch (e) {
        console.error('结束编辑失败：', e);
        editIndex = undefined;
        lastEditTg = undefined;
        return false;
    }
}

// 保留 endEditingPay 兼容原有调用
function endEditingPay() {
    return endEditing('#table_pay');
}
// 检查并设置合同拟定方
function checkAndSetContractDraft(typeRecord) {
    if (!typeRecord) return;
    var typeCode = typeRecord.code;
    // 判断是否是"模具"类型
    if (typeCode === '03') {
        // 自动设置为甲方
        $('#contractDraft').combobox('setValue', '01');
    } else {
    }
}
