
let el = {
    tb: '#tb',
    state: '#state',
    title: '#title',
    code: '#code',
    btn_file_eSign: '#btn-file-eSign',
};

let selfData = {
    toolbar: []
};

$(function () {

    $("#fileInput").filebox({
        buttonText: 'Choose', buttonAlign: 'left', onChange: fileUpload
    });

    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-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-save', handler: function () {
                    let row = $(el.tb).datagrid('getSelected');
                    fromAudit(row.id, row.oaProcessId);
                }
            },
        ];
    }
    selfData.toolbar.push(
        // { 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_look',
        //     iconCls: 'icon-search',
        //     handler: function () {
        //         look();
        //     }
        // },
    );


}


function loadGrid() {

    let supplierFlag = $("#supplierFlag").val();
    var columns = [];
    if(supplierFlag=='true'){
        columns = [
            { field: 'ck', checkbox: true},
            { field: 'contractCode', title: '合同编号', align: 'left' , width: 180 },
            { field: 'contractState', title: '合同状态', align: 'left', width: 100,
                formatter: function (value, row) {
                    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
                    switch (value) {
                        case 0:
                            return '<span style="color:#ffcb52;">暂存</span>';
                        case 1:
                            return '<span style="color:blue;">待提交</span>';
                        case 2:
                            return '<span style="color:blue;">审批中</span>';
                        case 3:
                            return '<span style="color:black;">通过</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>';
                        default:
                            return '--';
                    }
                    return "";
                }
            },
            { field: 'oaProcessId', title: 'OA流程单号', align: 'left',width: 200 ,hidden:true,
                formatter: function (value) {
                    let supplierFlag = $("#supplierFlag").val();
                    if(supplierFlag === 'true'){
                        return '';
                    }else
                        return oaTrack(value,OaProcessType.CONTRACT_CONFIRM);
                }},

            { field: 'contractSignFileStatue', title: '盖章文件上传状态', align: 'left',width: 150,hidden:true,
                formatter: function (value) {
                    if (value==='待上传盖章文件') {
                        return '<span style="color:blue;">待上传盖章文件</span>';
                    }
                    return value;
                }
            },
            { field: 'contractTitle', title: '合同名称', align: 'left',width: 100 },
            { field: 'orderCode', title: 'SAP订单号', align: 'left',width: 150 },
            { field: 'dataSources', title: '来源', align: 'left', width: 100,
                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 },
            { field: 'contractCompanyName', title: '公司名称', align: 'left',width: 150  },
            { field: 'contractSupplierCode', title: '供应商编码', align: 'left',width: 150 },
            { field: 'contractSupplierName', title: '供应商名称', align: 'left',width: 150 },
            { field: 'contractAmount', title: '合同金额', width: '100', align: 'center' },
            { field: 'contractDemandUser', title: '采购员', align: 'left', width: 120 },
            { 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: 'createTime', title: '创建时间', align: 'left', width: 120,
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            // { field: ' ', title: '操作', align: 'left',
            //     formatter: function (value, row) {
            //         var html = "";
            //         html += '<a href="javascript:;" onclick="checkCon( '+row.id+' )">查看合同</a>';
            //         return html
            //     }
            // }
        ]
    }else{
        columns = [
            { field: 'ck', checkbox: true},
            { field: 'contractCode', title: '合同编号', align: 'left' , width: 180 },
            { field: 'contractState', title: '合同状态', align: 'left', width: 100,
                formatter: function (value, row) {
                    // 0 暂存  1 待提交  2 审批中  3 通过   4 驳回   5 签约
                    switch (value) {
                        case 0:
                            return '<span style="color:#ffcb52;">暂存</span>';
                        case 1:
                            return '<span style="color:blue;">待提交</span>';
                        case 2:
                            return '<span style="color:blue;">审批中</span>';
                        case 3:
                            return '<span style="color:black;">通过</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>';
                        default:
                            return '--';
                    }
                    return "";
                }
            },
            { field: 'oaProcessId', title: 'OA流程单号', align: 'left',width: 200,
                formatter: function (value) {
                    let supplierFlag = $("#supplierFlag").val();
                    if(supplierFlag === 'true'){
                        return '';
                    }else
                        return oaTrack(value,OaProcessType.CONTRACT_CONFIRM);
                }},

            { field: 'contractSignFileStatue', title: '盖章文件上传状态', align: 'left',width: 150,
                formatter: function (value) {
                    if (value==='待上传盖章文件') {
                        return '<span style="color:blue;">待上传盖章文件</span>';
                    }
                    return value;
                }
            },
            { field: 'contractTitle', title: '合同名称', align: 'left',width: 100 },
            { field: 'orderCode', title: 'SAP订单号', align: 'left',width: 150 },

            { field: 'dataSources', title: '来源', align: 'left', width: 100,
                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 },
            { field: 'contractCompanyName', title: '公司名称', align: 'left',width: 150  },
            { field: 'contractSupplierCode', title: '供应商编码', align: 'left',width: 150 },
            { field: 'contractSupplierName', title: '供应商名称', align: 'left',width: 150 },
            { field: 'contractAmount', title: '合同金额', width: '100', align: 'center' },
            { field: 'contractDemandUser', title: '采购员', align: 'left', width: 120 },
            { 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: 'createTime', title: '创建时间', align: 'left', width: 120,
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD HH:mm:ss');
                }
            },
            // { field: ' ', title: '操作', align: 'left',
            //     formatter: function (value, row) {
            //         var html = "";
            //         html += '<a href="javascript:;" onclick="checkCon( '+row.id+' )">查看合同</a>';
            //         return html
            //     }
            // }
        ]
    }



    $(el.tb).datagrid({
        url: '/pc/contract/manage/rest/index/page?supplierFlag='+$("#supplierFlag").val(),
        iconCls: 'icon-list',
        height: gridheight - 50,
        singleSelect: true,
        fitColumns: false,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        columns: [columns],
        toolbar: selfData.toolbar,
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var contractSignFileStatue = rows[rowIndex].contractSignFileStatue;
            switch (contractSignFileStatue) {
                case '待上传盖章文件':
                    $(el.btn_file_eSign).linkbutton('enable');
                    break;
                default:
                    $(el.btn_file_eSign).linkbutton('disable');
                    break;
            }
        },
        onLoadSuccess: function (data) {
            if(supplierFlag === 'false'){
                displayButtonByUserRole('contract_manage');
                $(el.tb).datagrid('clearSelections');
            }else {
                displayButtonByUserRole('supplier_contract_sure');
                $(el.tb).datagrid('clearSelections');
            }
            initFileForm('sign-file-form');
        },
        // var supplierFlag = $("#supplierFlag").val(),

        //     if(supplierFlag === 'false'){
        //     onLoadSuccess: function () {
        //         displayButtonByUserRole('contract_manage');
        //         $(el.tb).datagrid('clearSelections');
        //     }
        // } else {
        //     onLoadSuccess: function () {
        //         displayButtonByUserRole('supplier_contract_sure');
        //         $(el.tb).datagrid('clearSelections');
        //     }
        // }

    });
}


/**
 * 初始化下拉框
 */
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':'弃用'}
        ]
    })
}


function addContract(){
    var addContractDialog = openDialog('addContract', g.ctx+'pc/contract/manage/page/form?id=&check=1', {
        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 == 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/manage/page/form?id='+row.id +'&check=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("查看按钮", "合同主数据");
    // 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/manage/page/look?id='+row.id +'&check=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 delOrEdit(id) {
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.msg("请选中一条记录",{icon: 0});
        return;
    }
    debugger;

    // 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/manage/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 fromAudit(conId,oaApplyId){
    let row = $(el.tb).datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return false;
    }
    debugger;
    // 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/manage/rest/getBillByKm',
        data: {conId: conId,oaApplyId:oaApplyId},
        type: 'POST',
        success: function (data) {
            top.layer.close(loading);
            if (data.code == 'S') {
                topWin.layer.alert('OA提交成功!', {icon: 1});
                $(el.tb).datagrid("reload")
            } else {
                topWin.layer.alert('OA提交失败!', {icon: 2});
            }
        },
        error: function (data) {
            top.layer.close(loading);
            topWin.layer.alert("OA提交失败!", {icon: 2});
        }
    })

}


function checkCon(id){
    var editContractDialog = openDialog('editContract', g.ctx+'pc/contract/manage/page/form?id='+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 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/manage/rest/saveSignFile',
                type: 'POST',
                // contentType: 'application/json',
                data: saveFormData,
                processData: false,
                contentType: false,
                success: function () {
                    // topWin.layer.msg('上传成功', {icon: 1});
                    fromAudit(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/manage/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', '');
    searchGrid();
}