
let el = {
    searchForm: '#searchForm',
    tb: '#tb',
    state: '#state',
    title: '#title',
    code: '#code',
    btn_file_eSign: '#btn-file-eSign',
    btn_edit: '#btn_edit',
    bodyHeight: document.documentElement.clientHeight,
    toolbarIdObject: {
        changeContract: '#btn-change',
        terminateContract: '#btn-terminate'
    }
};

let selfData = {
    toolbar: []
};

$(function () {

    $("#fileInput").filebox({
        buttonText: 'Choose', buttonAlign: 'left', onChange: fileUpload
    });
    initDict('gx_contract_type')
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll')

    initColumns();

    loadGrid();

    initCombo();
});

/**
 * 初始化表格列
 */
function initColumns() {

    let supplierFlag = $("#supplierFlag").val();
    selfData.toolbar = [];
    if(supplierFlag=='false'){
        selfData.toolbar = [
            {
                text: '新增',
                id: 'btn_add',
                iconCls: 'icon-add',
                handler: function () {
                    addContract();
                }
            },
            {
                text: '编辑',
                id: 'btn_edit',
                iconCls: 'icon-edit',
                handler: function () {
                    editContract();
                }
            },
            {
                text: '查看',
                id: 'btn_look',
                iconCls: 'icon-search',
                handler: function () {
                    look();
                }
            },
            {
                text: '删除',
                id: 'btn_remove',
                iconCls: 'icon-remove',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    delOrEdit(row.id);
                }
            },
            // {
            //     text: '废弃',
            //     id: 'btn_remove',
            //     iconCls: 'icon-remove',
            //     handler: function () {
            //         let row = $(el.tb).datagrid('getSelected');
            //         if (!row) {
            //             layer.msg("请选中一条记录");
            //             return;
            //         }
            //         cancelOrEdit(row.id);
            //     }
            // },
            { text: '确认上传盖章附件', id: 'btn-file-eSign', iconCls: 'icon-redo',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    $("#fileUpload .filebox-label").click();
                }
            },
            { text: '一步发起签署', id: 'btn-eSign', iconCls: 'icon-redo',
                handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    if (!row) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    if (!row.contractSignFileStatue) {
                        layer.msg("请先上传盖章文件!");
                        return;
                    }
                    sendSign(row.id);
                }
            },
            {
                text: '提交审批', id: 'btn-saveoa', iconCls: 'icon-ok', handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    fromAudit(row.id, row.oaProcessId);
                }
            },
            {
                text: '打印', id: 'btn_print', iconCls: 'icon-print', handler: function () {
                    let rows = $(el.tb).datagrid('getSelections');
                    if (!rows || rows.length != 1) {
                        topWin.layer.msg("请选中一条记录");
                        return;
                    }
                    setOperationLog("合同订单打印按钮", "MRO类合同");
                    let row = rows[0];
                    printContract(row) // 选择物质类模板打印

                }
            },
            {
                text: '发起变更', id: 'btn-change', iconCls: 'icon-ok', handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    changeContract(row);
                }
            },
            {
                text: '发起终止', id: 'btn-terminate', iconCls: 'icon-ok', handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    terminateContract(row);
                }
            }
        ];
    }

}

function printContract(row) {
    if (!row || !row.id) {
        alert('无效的合同信息');
        return;
    }

    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/contract/mroManage/page/print?contractId=' + row.id,
        success: function(data) {
            if (!data) {
                alert('打印内容为空');
                return;
            }

            $('#printDiv').print({
                globalStyles: true,
                mediaPrint: true,
                iframe: true,
                prepend: data

            });
        },
        error: function() {
            alert('加载打印内容失败，请稍后重试');
        }
    });
}


function loadGrid() {

    let supplierFlag = $("#supplierFlag").val();
    var columns = [];
    if(supplierFlag=='true'){
        columns = [
            {field: 'ck', checkbox: true},
            { field: 'contractCode', title: '合同编号', align: 'left' , width: 150, sortable: true },
            { field: 'contractState', title: '合同状态', align: 'left', width: 80, sortable: true,
                formatter: function (value) {
                    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
                    switch (value) {
                        case 0:
                            return '<span style="color: black;">暂存</span>';
                        case 1:
                            return '<span style="color: blue;">待提交</span>';
                        case 2:
                            return '<span style="color: blue;">审批中</span>';
                        case 3:
                            return '<span style="color: green;">通过</span>';
                        case 4:
                            return '<span style="color: red;">驳回</span>';
                        // case 5:
                        //     return '<span style="color:green;">通过(签约)</span>';
                        // case 6:
                        //     return '<span style="color:#4f504f;">弃用</span>';
                        case 7:
                            return '<span style="color: red;">终止</span>';
                        case 8:
                            return '<span style="color:red;">终止驳回</span>';
                        default:
                            return '--';
                    }
                }
            },
            {
                field: 'contractType', title: '合同类型', align: 'left', width: 160, sortable: true,
                formatter: function (value) {
                    switch (value) {
                        case "01":
                            return '<span style="color: black;">资产-设备</span>';
                        case "02":
                            return '<span style="color: black;">资产-软件</span>';
                        case "03":
                            return '<span style="color: black;">资产-模具</span>';
                        case "04":
                            return '<span style="color: black;">资产-低值易耗品</span>';
                        case "05":
                            return '<span style="color: black;">费用-设备租赁</span>';
                        case "06":
                            return '<span style="color: black;">费用-设备维修</span>';
                        case "07":
                            return '<span style="color: black;">\t\n' +
                                '原合同变更-补充协议</span>';
                        default:
                            return '--';
                    }
                }
            },
            { field: 'oaCode', title: '共享合同评审单', align: 'left',width: 150, sortable: true},

            { field: 'contractSignFileStatue', title: '盖章文件上传状态', align: 'left',width: 130, sortable: true,
                formatter: function (value) {
                    if (value==='待上传盖章文件') {
                        return '<span style="color:blue;">待上传盖章文件</span>';
                    }
                    return value;
                }
            },
            { field: 'dataSources', title: '来源', align: 'left', width: 80, sortable: true,
                formatter: function (value, row) {
                    // 0 手动创建 1招标 2询价
                    switch (value) {
                        case 0:
                            return '手动创建';
                        case 1:
                            return '招标';
                        case 2:
                            return '询价';
                        case 3:
                            return '询价';
                        default:
                            return '';
                    }
                }
            },
            { field: 'contractTitle', title: '合同名称', align: 'left',width: 180 },
            { field: 'dataSourcesNo', title: '来源单号', align: 'left',width: 150, sortable: true},
            { field: 'associationContract', title: '主合同编号', align: 'left',width: 150, sortable: true},
            { field: 'contractPurchaseGroup', title: '采购组', align: 'left', width: 80, sortable: true,
                exportEnum:getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
                formatter: function (value) {
                    if (value) {
                        return getNecessaryDataName("pc/sys/purchaseGroup/rest/listAll", value)
                    }
                }
            },
            // { field: 'signFile', title: '盖章附件', align: 'left', width: 240,
            //     formatter: function (value, row, index) {
            //         return '<div class="sign-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
            //     }
            // },
            {
                field: 'contractCompanyName', title: '甲方名称', align: 'left', width: 210
            },
            {
                field: 'contractSupplierCode', title: '乙方编码', align: 'left', width: 80, sortable: true
            },
            {
                field: 'contractSupplierName', title: '乙方名称', align: 'left', width: 210
            },
            { field: 'createTime', title: '创建时间', align: 'left', width: 140, sortable: true,
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            { field: 'contractAmount', title: '合同金额', width: '80', align: 'right',
                formatter: function (value) {
                    return formatNumber(value, 2, 1);
                }
            },
            { field: 'updateTime', title: '审批通过日期', align: 'left', width: 140, sortable: true,
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD HH:mm:ss');
                }
            },
        ]
    }else{
        columns = [
            {field: 'ck', checkbox: true},
            { field: 'contractCode', title: '合同编号', align: 'left' , width: 150, sortable: true },
            { field: 'contractState', title: '合同状态', align: 'left', width: 80, sortable: true,
                formatter: function (value, row) {
                    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
                    switch (value) {
                        case 0:
                            return '<span style="color: black;">暂存</span>';
                        case 1:
                            return '<span style="color: blue;">待提交</span>';
                        case 2:
                            return '<span style="color: blue;">审批中</span>';
                        case 3:
                            return '<span style="color: green;">通过</span>';
                        case 4:
                            return '<span style="color: red;">驳回</span>';
                        // case 5:
                        //     return '<span style="color:green;">通过(签约)</span>';
                        // case 6:
                        //     return '<span style="color:#4f504f;">弃用</span>';
                        case 7:
                            return '<span style="color: red;">终止</span>';
                        case 8:
                            return '<span style="color:red;">终止驳回</span>';
                        default:
                            return '--';
                    }
                    return "";
                }
            },
            {
                field: 'contractType', title: '合同类型', align: 'left', width: 160, sortable: true,
                formatter: function (value) {
                    return getDicName('gx_contract_type', value)
                }
            },
            { field: 'oaCode', title: '共享合同评审单', align: 'left',width: 150, sortable: true,
                formatter: function (value, row) {
                    const hasOaCode = value != null && value.toString().trim() !== '';

                    let supplierFlag = $("#supplierFlag").val();

                    if (supplierFlag === 'true' || !hasOaCode) {
                        return ''; // 供应商模式 或 oaCode 无效时，不显示
                    } else {
                        if(value.toString().trim().length >= 30){
                            return oaTrack(row.oaProcessId,OaProcessType.CONTRACT_CONFIRM);
                        }
                        return shareTrack(row.oaProcessId, shareFormId.CONTRACT_REVIEW, value);
                    }
                }
            },
            { field: 'oaProcessId', title: '共享合同评审单ID', align: 'left',width: 130, hidden: true
            },
            { field: 'contractSignFileStatue', title: '盖章文件上传状态', align: 'left',width: 130, sortable: true,
                formatter: function (value) {
                    if (value==='待上传盖章文件') {
                        return '<span style="color:blue;">待上传盖章文件</span>';
                    }
                    return value;
                }
            },
            { field: 'contractTitle', title: '合同名称', align: 'left',width: 180 },
            { field: 'dataSources', title: '来源', align: 'left', width: 80, sortable: true,
                formatter: function (value, row) {
                    // 0 手动创建 1招标 2询价
                    switch (value) {
                        case 0:
                            return '手动创建';
                        case 1:
                            return '招标';
                        case 2:
                            return '询价';
                        case 3:
                            return '询价';
                        default:
                            return '';
                    }
                }
            },
            { field: 'dataSourcesNo', title: '来源单号', align: 'left',width: 150, sortable: true },
            { field: 'associationContract', title: '主合同编号', align: 'left',width: 150, sortable: true},
            { field: 'contractPurchaseGroup', title: '采购组', align: 'left', width: 80, sortable: true,
                exportEnum:getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
                formatter: function (value) {
                    if (value) {
                        return getNecessaryDataName("pc/sys/purchaseGroup/rest/listAll", value)
                    }
                }},
            // { field: 'signFile', title: '盖章附件', align: 'left', width: 240,
            //     formatter: function (value, row, index) {
            //         return '<div class="sign-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
            //     }
            // },
            {
                field: 'contractCompanyName', title: '甲方名称', align: 'left', width: 210,
            },
            {
                field: 'contractSupplierCode', title: '乙方编码', align: 'left', width: 80, sortable: true
            },
            {
                field: 'contractSupplierName', title: '乙方名称', align: 'left', width: 210,
            },
            { field: 'createTime', title: '创建时间', align: 'left', width: 140, sortable: true,
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            { field: 'contractAmount', title: '合同金额', width: '80', align: 'right',
                formatter: function (value) {
                    return formatNumber(value, 2, 1);
                }
            },
            { field: 'updateTime', title: '审批通过日期', align: 'left', width: 140, sortable: true,
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD HH:mm:ss');
                }
            },
        ]
    }

    const searchHeight = $(el.searchForm).outerHeight();
    const pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).datagrid({
        url: '/pc/contract/mroManage/rest/index/page?supplierFlag='+$("#supplierFlag").val(),
        iconCls: 'icon-list',
        height: el.bodyHeight - searchHeight,
        singleSelect: true,
        fitColumns: false,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        columns: [columns],
        remoteSort: true,
        toolbar: selfData.toolbar,
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var contractSignFileStatue = rows[rowIndex].contractSignFileStatue;
            const contractState = rows[rowIndex].contractState;
            if(contractSignFileStatue === '待上传盖章文件' && (contractState===2 || contractState===4)){
               $(el.btn_file_eSign).linkbutton('enable');
           }else{
               $(el.btn_file_eSign).linkbutton('disable');

           }
            const contractFileState = rows[rowIndex].contractSignFiels;
            if(contractFileState && (contractState===4)){
                $(el.btn_edit).linkbutton('disable');
            }else{
                $(el.btn_edit).linkbutton('enable');
            }


            const contractType = rows[rowIndex].contractType;
            switch (contractState) {
                case 3:
                    if (contractType === '08') {
                        // 终止类合同不允许发起终止
                        $(el.toolbarIdObject.terminateContract).linkbutton('disable')
                    } else {
                        $(el.toolbarIdObject.terminateContract).linkbutton('enable')
                    }
                    if (contractType === '07' || contractType === '08') {
                        $(el.toolbarIdObject.changeContract).linkbutton('disable')
                    } else {
                        $(el.toolbarIdObject.changeContract).linkbutton('enable')
                    }
                    break;
                default:
                    $(el.toolbarIdObject.terminateContract).linkbutton('disable')
                    $(el.toolbarIdObject.changeContract).linkbutton('disable')
                    break;
            }
        },
        onLoadSuccess: function (data) {
            if(supplierFlag === 'false'){
                displayButtonByUserRole('contract_mro');
                $(el.tb).datagrid('clearSelections');
            }else {
                displayButtonByUserRole('supplier_contract_sure');
                $(el.tb).datagrid('clearSelections');
            }
            initFileForm('sign-file-form');
        },


    });
}


/**
 * 初始化下拉框
 */
function initCombo() {
    $(el.state).combobox({
        valueField:'code',
        textField:'text',
        panelHeight:'auto',
        editable:false,
        prompt: '--- 请选择 ---',
        data:[
            {'code':'0','text':'暂存'},
            {'code':'1','text':'待提交'},
            {'code':'2','text':'审批中'},
            {'code':'3','text':'通过'},
            {'code':'4','text':'驳回'},
            // {'code':'5','text':'签约'},
            // {'code':'6','text':'弃用'},
            {'code':'7','text':'废弃'},
            {'code':'8','text':'终止驳回'}
        ]
    })
}


function addContract(){
    var addContractDialog = openDialog('addContract', g.ctx+'pc/contract/mroManage/page/form?id=&check=1&optType=0', {
        title: '新增',
        width: '90%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            addContractDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'暂存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['addContract'].submitContractForm(0,function (data) {
                        addContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['addContract'].submitContractForm(1,function (data) {
                        addContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    addContractDialog.dialog('close');
                }
            }
        ]
    });
}


function editContract(rowId){

    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录",{icon: 0});
        return;
    }
    setOperationLog("编辑按钮", "合同主数据");
    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
    if (row.contractState !== 0 &&  row.contractState !== 1 && row.contractState !== 4 ) {
        topWin.layer.msg("请选中暂存/待提交/驳回的记录");
        return;
    }

    var editContractDialog = openDialog('editContract', g.ctx+'pc/contract/mroManage/page/form?id='+row.id +'&check=1&optType=1', {
        title: '编辑',
        width: '90%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            editContractDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'暂存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['editContract'].submitContractForm(0,function (data) {
                        editContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['editContract'].submitContractForm(1,function (data) {
                        editContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    editContractDialog.dialog('close');
                }
            }
        ]
    });
}

function look(rowId){

    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录",{icon: 0});
        return;
    }
    setOperationLog("查看按钮", "MRO合同主数据");
    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
    // if (row.contractState == 2 || row.contractState == 3 || row.contractState == 5 || row.contractState == 6) {
    //     topWin.layer.msg("请选中暂存/待提交/驳回的记录");
    //     return;
    // }

    //url = '/contract/manage/formDeatil?type=' + type + '&id=' + row['id'] + "&typeStatus=" + typeStatus + "&isckeck=0&lx=" + lx;
    var editContractDialog = openDialog('editContract', g.ctx+'pc/contract/mroManage/page/look?id='+row.id +'&check=0', {
        title: '查看',
        width: '90%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            editContractDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    editContractDialog.dialog('close');
                }
            }
        ]
    });
}

function delOrEdit(id) {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录",{icon: 0});
        return;
    }

    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
    if (row.contractState != 0 && row.contractState != 1 && row.contractState != 4) {
        topWin.layer.msg("请选中暂存、待提交、驳回的记录");
        return;
    }

    topWin.layer.confirm("确定删除吗", function (index) {
        $.ajax({
            url: g.ctx + 'pc/contract/mroManage/rest/remove',
            type: 'POST',
            data: {id: id},
            success: function (data) {
                topWin.layer.alert("删除成功", {icon: 1}, function (idx) {
                    $(el.tb).datagrid("reload")
                    topWin.layer.close(index);
                    topWin.layer.close(idx);
                });
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        })
    })
}


function cancelOrEdit(id) {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录",{icon: 0});
        return;
    }

    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
    if (row.contractState != 0 && row.contractState != 4 && row.contractState != 6) {
        topWin.layer.msg("请选中暂存/驳回的记录");
        return;
    }

    topWin.layer.confirm("确定废弃吗", function (index) {
        $.ajax({
            url: g.ctx + 'pc/contract/mroManage/rest/cancel',
            type: 'POST',
            data: {id: id},
            success: function (data) {
                topWin.layer.alert("废弃成功", {icon: 1}, function (idx) {
                    $(el.tb).datagrid("reload")
                    topWin.layer.close(index);
                    topWin.layer.close(idx);
                });
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        })
    })
}
function fromAudit(conId,gxApplyId){
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return false;
    }
    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约 6 废弃
    if (row.contractState == 0 || (row.contractState == 2 && row.contractSignFileStatue !== "待上传盖章文件") || row.contractState == 3|| row.contractState == 5 || row.contractState == 6 ) {
        topWin.layer.msg("请选中待提交/驳回的记录");
        return false;
    }

    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    //检查是否存在对应的科目流程
    $.ajax({
        url: '/pc/contract/mroManage/rest/submitContractToGx',
        data: {conId: conId,gxApplyId:gxApplyId,isTerminated: "0"},
        type: 'POST',
        success: function (data) {
            top.layer.close(loading);
            if (data.status === true) {
                topWin.layer.alert('提交合同到共享平台成功!', {icon: 1});
                $(el.tb).datagrid("reload")
            } else {
                topWin.layer.alert('提交合同到共享平台失败!', {icon: 2});
            }
        },
        error: function (data) {
            top.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    })

}

function stampFileToGx(conId,gxApplyId){
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return false;
    }
    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约 6 废弃
    // if (row.contractState == 0 || (row.contractState == 2 && row.contractSignFileStatue !== "待上传盖章文件") || row.contractState == 3|| row.contractState == 5 || row.contractState == 6 ) {
    //     topWin.layer.msg("请选中待提交/驳回的记录");
    //     return false;
    // }

    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    //检查是否存在对应的科目流程
    $.ajax({
        url: '/pc/contract/mroManage/rest/submitStampFileToGx',
        data: {conId: conId,gxApplyId:gxApplyId},
        type: 'POST',
        success: function (data) {
            top.layer.close(loading);
            console.log("data:"+data)
            if (Array.isArray(data) && data.length > 0) {
                topWin.layer.alert('上传盖章附件到共享平台失败!'+data, {icon: 2});
                $(el.tb).datagrid("reload"); // 可选：失败也刷新表格（根据业务调整）
            }else{
                topWin.layer.alert('上传盖章附件到共享平台成功!', {icon: 1});
            }
        },
        error: function (data) {
            top.layer.close(loading);
            topWin.layer.alert("上传盖章附件到共享失败!", {icon: 2});
        }
    })

}

function checkCon(id){
    var editContractDialog = openDialog('editContract', g.ctx+'pc/contract/mroManage/page/form?id='+id+"&check=0&optType=1", {
        title: '查看',
        width: '90%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            editContractDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    editContractDialog.dialog('close');
                }
            }
        ]
    });
}


function fileUpload(v1, v2) {
    let row = $(el.tb).datagrid("getSelected");
    let addFiles = [];
    let files = $("#fileInput").filebox('files'), formData = new FormData()
    for (let r = 0; r < files.length; r++) {
        addFiles.push(files[r]);
    }
    for (let n = 0; n < addFiles.length; n++) {
        formData.append('files', addFiles[n]);
    }
    if (addFiles.length > 0) {
        fileUploadAjaxWithCall(formData, function (rows) {
            const postData = []
            $.each(rows, function (idx, itm) {
                postData.push({
                    fileId: itm.id, conId: row.id
                })
            })
            // 创建新的 FormData 用于保存文件关联信息
            let saveFormData = new FormData();
            // 添加所有文件关联信息
            $.each(postData, function(idx, item) {
                saveFormData.append("fileIds", item.fileId);
            })
            saveFormData.append("conId",postData[0].conId)
            // 如果需要，也可以将原始文件添加到新的 FormData 中
            for (let n = 0; n < addFiles.length; n++) {
                saveFormData.append('files', addFiles[n]);
            }
            $.ajax({
                url: g.ctx + 'pc/contract/mroManage/rest/saveSignFile',
                type: 'POST',
                // contentType: 'application/json',
                data: saveFormData,
                processData: false,
                contentType: false,
                success: function () {
                    // topWin.layer.msg('上传成功', {icon: 1});
                    stampFileToGx(row.id, row.oaProcessId);
                    $(el.tb).datagrid('reload');
                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        }, true)
        $("#fileInput").filebox('clear')
    }
}


function sendSign(conId){
    topWin.layer.confirm("确定要发起签章流程吗!", function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/contract/mroManage/rest/sendSign',
            type: 'POST',
            data: {conId: conId},
            success: function (data) {
                top.layer.close(loading);
                topWin.layer.alert("操作成功", {icon: 1}, function (idx) {
                    $(el.tb).datagrid("reload")
                    topWin.layer.close(index);
                    topWin.layer.close(idx);
                });
            },
            error: function (data) {
                top.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        })
    })
}


/**
 * 查询
 */
function searchGrid() {
    $(el.tb).datagrid('options').queryParams = $("#searchForm").serializeJson();
    $(el.tb).datagrid('load');
}

/**
 * 重置筛选条件
 */
function resetGrid() {
    $(el.state).combobox('clear');
    $(el.title).textbox('setValue', '');
    $(el.supplierKey).textbox('setValue', '');
    $(el.code).textbox('setValue', '');
    $(el.type).combobox('clear');
    $(el.contractDraft).combobox('clear');
    searchGrid();
}

/**
 * 发起变更
 * @param row 明细行
 */
function changeContract(row) {
    if (!row || row.length === 0) {
        topWin.layer.alert('请选择一条明细', {icon: 0});
        return;
    }
    const changeContractConfirmDialog = openDialog('changeContractConfirmDialog', g.ctx+'pc/contract/mroManage/page/changeContractConfirmPage?id='+row.id, {
        title: '发起变更',
        width: '60%',
        height:'50%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            changeContractConfirmDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'确认',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['changeContractConfirmDialog'].confirm(function (data) {
                        openChangeDialog(data, row.id);
                        changeContractConfirmDialog.dialog('close');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    changeContractConfirmDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 发起终止
 * @param row 明细行
 */
function terminateContract(row) {
    if (!row || row.length === 0) {
        topWin.layer.alert('请选择一条明细', {icon: 0});
        return;
    }
    $.ajax({
        url: '/pc/contract/mroManage/rest/detail/contractTerminateCheck',
        type: 'POST',
        async: false,
        data: {
            contractId: row.id
        },
        success: function (res) {
            openTerminateContractDialog(row);
        },
        error: function (res) {
            topWin.layer.alert(res.responseJSON.message, {icon: 2});
        }
    });
}

/**
 * 打开终止合同
 * @param row 选择行
 */
function openTerminateContractDialog(row) {
    const terminateContractDialog = openDialog('terminateContractDialog', g.ctx+'pc/contract/mroManage/page/form?id=' + row.id + "&check=1&optType=4", {
        title: '发起终止',
        width: '90%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            terminateContractDialog.dialog('destroy');
        },
        onOpen: function () {
            const iframe = $(this).find('iframe')[0];
            iframe.onload = function() {
                // 将父页面的函数引用传递给iframe
                iframe.contentWindow.parentData = row;
            };
        },
        buttons: [
            {
                text:'终止',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['terminateContractDialog'].submitContractForm(2,function () {
                        terminateContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    terminateContractDialog.dialog('close');
                }
            }
        ]
    });
}

function openChangeDialog(data, id) {
    const changeContractDialog = openDialog('changeContractDialog', g.ctx+'pc/contract/mroManage/page/form?id=' + id + "&check=1&optType=2", {
        title: '发起变更',
        width: '90%',
        height:'100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            changeContractDialog.dialog('destroy');
        },
        onOpen: function () {
            const iframe = $(this).find('iframe')[0];
            iframe.onload = function() {
                // 将父页面的函数引用传递给iframe
                iframe.contentWindow.parentData = data;
            };
        },
        buttons: [
            {
                text:'暂存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['changeContractDialog'].submitContractForm(0,function () {
                        changeContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['changeContractDialog'].submitContractForm(1,function () {
                        changeContractDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    changeContractDialog.dialog('close');
                }
            }
        ]
    });
}